diff --git a/.github/workflows/build-cross-compile.yml b/.github/workflows/build-cross-compile.yml index 3afb910a3d8..dbeb3d45154 100644 --- a/.github/workflows/build-cross-compile.yml +++ b/.github/workflows/build-cross-compile.yml @@ -84,7 +84,7 @@ jobs: - target-cpu: riscv64 gnu-arch: riscv64 debian-arch: riscv64 - debian-repository: https://httpredir.debian.org/debian/ + debian-repository: https://snapshot.debian.org/archive/debian/20240228T034848Z/ debian-version: sid tolerate-sysroot-errors: true diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 07c47c9d592..e89dcb81809 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -35,7 +35,7 @@ on: platforms: description: 'Platform(s) to execute on (comma separated, e.g. "linux-x64, macos, aarch64")' required: true - default: 'linux-x64, linux-x86, linux-x64-variants, linux-cross-compile, macos-x64, macos-aarch64, windows-x64, windows-aarch64' + default: 'linux-x64, linux-x86-hs, linux-x64-variants, linux-cross-compile, macos-x64, macos-aarch64, windows-x64, windows-aarch64' configure-arguments: description: 'Additional configure arguments' required: false @@ -58,7 +58,7 @@ jobs: runs-on: ubuntu-22.04 outputs: linux-x64: ${{ steps.include.outputs.linux-x64 }} - linux-x86: ${{ steps.include.outputs.linux-x86 }} + linux-x86-hs: ${{ steps.include.outputs.linux-x86-hs }} linux-x64-variants: ${{ steps.include.outputs.linux-x64-variants }} linux-cross-compile: ${{ steps.include.outputs.linux-cross-compile }} macos-x64: ${{ steps.include.outputs.macos-x64 }} @@ -109,7 +109,7 @@ jobs: } echo "linux-x64=$(check_platform linux-x64 linux x64)" >> $GITHUB_OUTPUT - echo "linux-x86=$(check_platform linux-x86 linux x86)" >> $GITHUB_OUTPUT + echo "linux-x86-hs=$(check_platform linux-x86-hs linux x86)" >> $GITHUB_OUTPUT echo "linux-x64-variants=$(check_platform linux-x64-variants variants)" >> $GITHUB_OUTPUT echo "linux-cross-compile=$(check_platform linux-cross-compile cross-compile)" >> $GITHUB_OUTPUT echo "macos-x64=$(check_platform macos-x64 macos x64)" >> $GITHUB_OUTPUT @@ -132,12 +132,13 @@ jobs: make-arguments: ${{ github.event.inputs.make-arguments }} if: needs.select.outputs.linux-x64 == 'true' - build-linux-x86: - name: linux-x86 + build-linux-x86-hs: + name: linux-x86-hs needs: select uses: ./.github/workflows/build-linux.yml with: platform: linux-x86 + make-target: 'hotspot' gcc-major-version: '10' gcc-package-suffix: '-multilib' apt-architecture: 'i386' @@ -147,7 +148,7 @@ jobs: extra-conf-options: '--with-target-bits=32' configure-arguments: ${{ github.event.inputs.configure-arguments }} make-arguments: ${{ github.event.inputs.make-arguments }} - if: needs.select.outputs.linux-x86 == 'true' + if: needs.select.outputs.linux-x86-hs == 'true' build-linux-x64-hs-nopch: name: linux-x64-hs-nopch @@ -281,16 +282,6 @@ jobs: bootjdk-platform: linux-x64 runs-on: ubuntu-22.04 - test-linux-x86: - name: linux-x86 - needs: - - build-linux-x86 - uses: ./.github/workflows/test.yml - with: - platform: linux-x86 - bootjdk-platform: linux-x64 - runs-on: ubuntu-22.04 - test-macos-x64: name: macos-x64 needs: @@ -328,7 +319,7 @@ jobs: if: always() needs: - build-linux-x64 - - build-linux-x86 + - build-linux-x86-hs - build-linux-x64-hs-nopch - build-linux-x64-hs-zero - build-linux-x64-hs-minimal @@ -339,8 +330,8 @@ jobs: - build-windows-x64 - build-windows-aarch64 - test-linux-x64 - - test-linux-x86 - test-macos-x64 + - test-macos-aarch64 - test-windows-x64 steps: @@ -352,7 +343,7 @@ jobs: -H 'Accept: application/vnd.github+json' \ -H 'Authorization: Bearer ${{ github.token }}' \ -H 'X-GitHub-Api-Version: 2022-11-28' \ - '${{ github.api_url }}/repos/${{ github.repository }}/actions/runs/${{ github.run_id }}/artifacts')" + '${{ github.api_url }}/repos/${{ github.repository }}/actions/runs/${{ github.run_id }}/artifacts?per_page=100')" BUNDLE_ARTIFACT_IDS="$(echo "$ALL_ARTIFACT_IDS" | jq -r -c '.artifacts | map(select(.name|startswith("bundles-"))) | .[].id')" for id in $BUNDLE_ARTIFACT_IDS; do echo "Removing $id" diff --git a/.jcheck/conf b/.jcheck/conf index 046197ae090..616d6926da1 100644 --- a/.jcheck/conf +++ b/.jcheck/conf @@ -1,7 +1,7 @@ [general] project=jdk-updates jbs=JDK -version=17.0.13 +version=17.0.14 [checks] error=author,committer,reviewers,merge,issues,executable,symlink,message,hg-tag,whitespace,problemlists diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 00000000000..f4c5e7e67cb --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,3 @@ +# JDK Vulnerabilities + +Please follow the process outlined in the [OpenJDK Vulnerability Policy](https://openjdk.org/groups/vulnerability/report) to disclose vulnerabilities in the JDK. diff --git a/closed/openjdk-tag.gmk b/closed/openjdk-tag.gmk index 8bcc1d36f95..52b37afba1d 100644 --- a/closed/openjdk-tag.gmk +++ b/closed/openjdk-tag.gmk @@ -1 +1 @@ -OPENJDK_TAG := jdk-17.0.13+11 +OPENJDK_TAG := jdk-17.0.14+1 diff --git a/make/autoconf/lib-alsa.m4 b/make/autoconf/lib-alsa.m4 index 19a91f94809..8d0fb324cd0 100644 --- a/make/autoconf/lib-alsa.m4 +++ b/make/autoconf/lib-alsa.m4 @@ -70,6 +70,25 @@ AC_DEFUN_ONCE([LIB_SETUP_ALSA], PKG_CHECK_MODULES(ALSA, alsa, [ALSA_FOUND=yes], [ALSA_FOUND=no]) fi fi + if test "x$ALSA_FOUND" = xno; then + # If we have sysroot set, and no explicit library location is set, + # look at known locations in sysroot. + if test "x$SYSROOT" != "x" && test "x${with_alsa_lib}" == x; then + if test -f "$SYSROOT/usr/lib64/libasound.so" && test "x$OPENJDK_TARGET_CPU_BITS" = x64; then + ALSA_LIBS="-L$SYSROOT/usr/lib64 -lasound" + ALSA_FOUND=yes + elif test -f "$SYSROOT/usr/lib/libasound.so"; then + ALSA_LIBS="-L$SYSROOT/usr/lib -lasound" + ALSA_FOUND=yes + elif test -f "$SYSROOT/usr/lib/$OPENJDK_TARGET_CPU-$OPENJDK_TARGET_OS-$OPENJDK_TARGET_ABI/libasound.so"; then + ALSA_LIBS="-L$SYSROOT/usr/lib/$OPENJDK_TARGET_CPU-$OPENJDK_TARGET_OS-$OPENJDK_TARGET_ABI -lasound" + ALSA_FOUND=yes + elif test -f "$SYSROOT/usr/lib/$OPENJDK_TARGET_CPU_AUTOCONF-$OPENJDK_TARGET_OS-$OPENJDK_TARGET_ABI/libasound.so"; then + ALSA_LIBS="-L$SYSROOT/usr/lib/$OPENJDK_TARGET_CPU_AUTOCONF-$OPENJDK_TARGET_OS-$OPENJDK_TARGET_ABI -lasound" + ALSA_FOUND=yes + fi + fi + fi if test "x$ALSA_FOUND" = xno; then AC_CHECK_HEADERS([alsa/asoundlib.h], [ diff --git a/make/autoconf/lib-x11.m4 b/make/autoconf/lib-x11.m4 index b1902a432a1..6849b4a26c7 100644 --- a/make/autoconf/lib-x11.m4 +++ b/make/autoconf/lib-x11.m4 @@ -71,9 +71,9 @@ AC_DEFUN_ONCE([LIB_SETUP_X11], elif test -f "$SYSROOT/usr/lib/libX11.so"; then x_libraries="$SYSROOT/usr/lib" elif test -f "$SYSROOT/usr/lib/$OPENJDK_TARGET_CPU-$OPENJDK_TARGET_OS-$OPENJDK_TARGET_ABI/libX11.so"; then - x_libraries="$SYSROOT/usr/lib/$OPENJDK_TARGET_CPU-$OPENJDK_TARGET_OS-$OPENJDK_TARGET_ABI/libX11.so" + x_libraries="$SYSROOT/usr/lib/$OPENJDK_TARGET_CPU-$OPENJDK_TARGET_OS-$OPENJDK_TARGET_ABI" elif test -f "$SYSROOT/usr/lib/$OPENJDK_TARGET_CPU_AUTOCONF-$OPENJDK_TARGET_OS-$OPENJDK_TARGET_ABI/libX11.so"; then - x_libraries="$SYSROOT/usr/lib/$OPENJDK_TARGET_CPU_AUTOCONF-$OPENJDK_TARGET_OS-$OPENJDK_TARGET_ABI/libX11.so" + x_libraries="$SYSROOT/usr/lib/$OPENJDK_TARGET_CPU_AUTOCONF-$OPENJDK_TARGET_OS-$OPENJDK_TARGET_ABI" fi fi fi diff --git a/make/autoconf/toolchain.m4 b/make/autoconf/toolchain.m4 index 8105ce9e80a..98573f965b3 100644 --- a/make/autoconf/toolchain.m4 +++ b/make/autoconf/toolchain.m4 @@ -429,6 +429,11 @@ AC_DEFUN([TOOLCHAIN_EXTRACT_COMPILER_VERSION], # Copyright (C) 2013 Free Software Foundation, Inc. # This is free software; see the source for copying conditions. There is NO # warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + # or look like + # gcc (GCC) 10.2.1 20200825 (Alibaba 10.2.1-3.8 2.32) + # Copyright (C) 2020 Free Software Foundation, Inc. + # This is free software; see the source for copying conditions. There is NO + # warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. COMPILER_VERSION_OUTPUT=`$COMPILER --version 2>&1` # Check that this is likely to be GCC. $ECHO "$COMPILER_VERSION_OUTPUT" | $GREP "Free Software Foundation" > /dev/null @@ -442,7 +447,8 @@ AC_DEFUN([TOOLCHAIN_EXTRACT_COMPILER_VERSION], COMPILER_VERSION_STRING=`$ECHO $COMPILER_VERSION_OUTPUT | \ $SED -e 's/ *Copyright .*//'` COMPILER_VERSION_NUMBER=`$ECHO $COMPILER_VERSION_OUTPUT | \ - $SED -e 's/^.* \(@<:@1-9@:>@<:@0-9@:>@*\.@<:@0-9.@:>@*\)@<:@^0-9.@:>@.*$/\1/'` + $AWK -F ')' '{print [$]2}' | \ + $AWK '{print [$]1}'` elif test "x$TOOLCHAIN_TYPE" = xclang; then # clang --version output typically looks like # Apple LLVM version 5.0 (clang-500.2.79) (based on LLVM 3.3svn) diff --git a/make/conf/version-numbers.conf b/make/conf/version-numbers.conf index d5ba88b6955..710539bc0d7 100644 --- a/make/conf/version-numbers.conf +++ b/make/conf/version-numbers.conf @@ -28,15 +28,15 @@ DEFAULT_VERSION_FEATURE=17 DEFAULT_VERSION_INTERIM=0 -DEFAULT_VERSION_UPDATE=13 +DEFAULT_VERSION_UPDATE=14 DEFAULT_VERSION_PATCH=0 DEFAULT_VERSION_EXTRA1=0 DEFAULT_VERSION_EXTRA2=0 DEFAULT_VERSION_EXTRA3=0 -DEFAULT_VERSION_DATE=2024-10-15 +DEFAULT_VERSION_DATE=2025-01-21 DEFAULT_VERSION_CLASSFILE_MAJOR=61 # "`$EXPR $DEFAULT_VERSION_FEATURE + 44`" DEFAULT_VERSION_CLASSFILE_MINOR=0 DEFAULT_VERSION_DOCS_API_SINCE=11 DEFAULT_ACCEPTABLE_BOOT_VERSIONS="16 17" DEFAULT_JDK_SOURCE_TARGET_VERSION=17 -DEFAULT_PROMOTED_VERSION_PRE= +DEFAULT_PROMOTED_VERSION_PRE=ea diff --git a/make/data/publicsuffixlist/VERSION b/make/data/publicsuffixlist/VERSION index f86d2df03ca..24f4407cc89 100644 --- a/make/data/publicsuffixlist/VERSION +++ b/make/data/publicsuffixlist/VERSION @@ -1,2 +1,2 @@ -Github: https://raw.githubusercontent.com/publicsuffix/list/b5bf572c52988dbe9d865b8f090ea819024a9936/public_suffix_list.dat -Date: 2023-11-09 +Github: https://raw.githubusercontent.com/publicsuffix/list/1cbd6e71a9b83620b1d0b11e49d3d9ff48c27e22/public_suffix_list.dat +Date: 2024-05-07 diff --git a/make/data/publicsuffixlist/public_suffix_list.dat b/make/data/publicsuffixlist/public_suffix_list.dat index fff6e9a494d..34733674ea0 100644 --- a/make/data/publicsuffixlist/public_suffix_list.dat +++ b/make/data/publicsuffixlist/public_suffix_list.dat @@ -6710,7 +6710,7 @@ org.zw // newGTLDs -// List of new gTLDs imported from https://www.icann.org/resources/registries/gtlds/v2/gtlds.json on 2023-11-03T15:13:18Z +// List of new gTLDs imported from https://www.icann.org/resources/registries/gtlds/v2/gtlds.json on 2024-05-04T15:12:50Z // This list is auto-generated, don't edit it manually. // aaa : American Automobile Association, Inc. // https://www.iana.org/domains/root/db/aaa.html @@ -6896,7 +6896,7 @@ anquan // https://www.iana.org/domains/root/db/anz.html anz -// aol : Oath Inc. +// aol : Yahoo Inc. // https://www.iana.org/domains/root/db/aol.html aol @@ -6988,10 +6988,6 @@ auto // https://www.iana.org/domains/root/db/autos.html autos -// avianca : Avianca Inc. -// https://www.iana.org/domains/root/db/avianca.html -avianca - // aws : AWS Registry LLC // https://www.iana.org/domains/root/db/aws.html aws @@ -7016,10 +7012,6 @@ baidu // https://www.iana.org/domains/root/db/banamex.html banamex -// bananarepublic : The Gap, Inc. -// https://www.iana.org/domains/root/db/bananarepublic.html -bananarepublic - // band : Dog Beach, LLC // https://www.iana.org/domains/root/db/band.html band @@ -7544,10 +7536,6 @@ college // https://www.iana.org/domains/root/db/cologne.html cologne -// comcast : Comcast IP Holdings I, LLC -// https://www.iana.org/domains/root/db/comcast.html -comcast - // commbank : COMMONWEALTH BANK OF AUSTRALIA // https://www.iana.org/domains/root/db/commbank.html commbank @@ -7752,6 +7740,10 @@ dental // https://www.iana.org/domains/root/db/dentist.html dentist +// desi +// https://www.iana.org/domains/root/db/desi.html +desi + // design : Registry Services, LLC // https://www.iana.org/domains/root/db/design.html design @@ -7796,7 +7788,7 @@ discover // https://www.iana.org/domains/root/db/dish.html dish -// diy : Lifestyle Domain Holdings, Inc. +// diy : Internet Naming Company LLC // https://www.iana.org/domains/root/db/diy.html diy @@ -7928,10 +7920,6 @@ esq // https://www.iana.org/domains/root/db/estate.html estate -// etisalat : Emirates Telecommunications Corporation (trading as Etisalat) -// https://www.iana.org/domains/root/db/etisalat.html -etisalat - // eurovision : European Broadcasting Union (EBU) // https://www.iana.org/domains/root/db/eurovision.html eurovision @@ -8104,7 +8092,7 @@ fly // https://www.iana.org/domains/root/db/foo.html foo -// food : Lifestyle Domain Holdings, Inc. +// food : Internet Naming Company LLC // https://www.iana.org/domains/root/db/food.html food @@ -8164,7 +8152,7 @@ ftr // https://www.iana.org/domains/root/db/fujitsu.html fujitsu -// fun : Radix FZC DMCC +// fun : Radix Technologies Inc. // https://www.iana.org/domains/root/db/fun.html fun @@ -8312,7 +8300,7 @@ goldpoint // https://www.iana.org/domains/root/db/golf.html golf -// goo : NTT Resonant Inc. +// goo : NTT DOCOMO, INC. // https://www.iana.org/domains/root/db/goo.html goo @@ -8364,10 +8352,6 @@ grocery // https://www.iana.org/domains/root/db/group.html group -// guardian : The Guardian Life Insurance Company of America -// https://www.iana.org/domains/root/db/guardian.html -guardian - // gucci : Guccio Gucci S.p.a. // https://www.iana.org/domains/root/db/gucci.html gucci @@ -8500,7 +8484,7 @@ horse // https://www.iana.org/domains/root/db/hospital.html hospital -// host : Radix FZC DMCC +// host : Radix Technologies Inc. // https://www.iana.org/domains/root/db/host.html host @@ -8720,7 +8704,7 @@ jpmorgan // https://www.iana.org/domains/root/db/jprs.html jprs -// juegos : Internet Naming Company LLC +// juegos : Dog Beach, LLC // https://www.iana.org/domains/root/db/juegos.html juegos @@ -8908,7 +8892,7 @@ life // https://www.iana.org/domains/root/db/lifeinsurance.html lifeinsurance -// lifestyle : Lifestyle Domain Holdings, Inc. +// lifestyle : Internet Naming Company LLC // https://www.iana.org/domains/root/db/lifestyle.html lifestyle @@ -8948,7 +8932,7 @@ lipsy // https://www.iana.org/domains/root/db/live.html live -// living : Lifestyle Domain Holdings, Inc. +// living : Internet Naming Company LLC // https://www.iana.org/domains/root/db/living.html living @@ -9392,10 +9376,6 @@ olayan // https://www.iana.org/domains/root/db/olayangroup.html olayangroup -// oldnavy : The Gap, Inc. -// https://www.iana.org/domains/root/db/oldnavy.html -oldnavy - // ollo : Dish DBS Corporation // https://www.iana.org/domains/root/db/ollo.html ollo @@ -9416,7 +9396,7 @@ ong // https://www.iana.org/domains/root/db/onl.html onl -// online : Radix FZC DMCC +// online : Radix Technologies Inc. // https://www.iana.org/domains/root/db/online.html online @@ -9620,7 +9600,7 @@ pramerica // https://www.iana.org/domains/root/db/praxi.html praxi -// press : Radix FZC DMCC +// press : Radix Technologies Inc. // https://www.iana.org/domains/root/db/press.html press @@ -9928,10 +9908,6 @@ sbi // https://www.iana.org/domains/root/db/sbs.html sbs -// sca : SVENSKA CELLULOSA AKTIEBOLAGET SCA (publ) -// https://www.iana.org/domains/root/db/sca.html -sca - // scb : The Siam Commercial Bank Public Company Limited ("SCB") // https://www.iana.org/domains/root/db/scb.html scb @@ -10076,7 +10052,7 @@ sina // https://www.iana.org/domains/root/db/singles.html singles -// site : Radix FZC DMCC +// site : Radix Technologies Inc. // https://www.iana.org/domains/root/db/site.html site @@ -10156,7 +10132,7 @@ soy // https://www.iana.org/domains/root/db/spa.html spa -// space : Radix FZC DMCC +// space : Radix Technologies Inc. // https://www.iana.org/domains/root/db/space.html space @@ -10208,7 +10184,7 @@ stockholm // https://www.iana.org/domains/root/db/storage.html storage -// store : Radix FZC DMCC +// store : Radix Technologies Inc. // https://www.iana.org/domains/root/db/store.html store @@ -10324,7 +10300,7 @@ tdk // https://www.iana.org/domains/root/db/team.html team -// tech : Radix FZC DMCC +// tech : Radix Technologies Inc. // https://www.iana.org/domains/root/db/tech.html tech @@ -10508,7 +10484,7 @@ unicom // https://www.iana.org/domains/root/db/university.html university -// uno : Radix FZC DMCC +// uno : Radix Technologies Inc. // https://www.iana.org/domains/root/db/uno.html uno @@ -10524,7 +10500,7 @@ ups // https://www.iana.org/domains/root/db/vacations.html vacations -// vana : Lifestyle Domain Holdings, Inc. +// vana : Internet Naming Company LLC // https://www.iana.org/domains/root/db/vana.html vana @@ -10608,10 +10584,6 @@ vlaanderen // https://www.iana.org/domains/root/db/vodka.html vodka -// volkswagen : Volkswagen Group of America Inc. -// https://www.iana.org/domains/root/db/volkswagen.html -volkswagen - // volvo : Volvo Holding Sverige Aktiebolag // https://www.iana.org/domains/root/db/volvo.html volvo @@ -10676,10 +10648,14 @@ webcam // https://www.iana.org/domains/root/db/weber.html weber -// website : Radix FZC DMCC +// website : Radix Technologies Inc. // https://www.iana.org/domains/root/db/website.html website +// wed +// https://www.iana.org/domains/root/db/wed.html +wed + // wedding : Registry Services, LLC // https://www.iana.org/domains/root/db/wedding.html wedding @@ -10768,10 +10744,6 @@ xbox // https://www.iana.org/domains/root/db/xerox.html xerox -// xfinity : Comcast IP Holdings I, LLC -// https://www.iana.org/domains/root/db/xfinity.html -xfinity - // xihuan : Beijing Qihu Keji Co., Ltd. // https://www.iana.org/domains/root/db/xihuan.html xihuan @@ -11012,10 +10984,6 @@ xin // https://www.iana.org/domains/root/db/xn--mgba7c0bbn0a.html العليان -// xn--mgbaakc7dvf : Emirates Telecommunications Corporation (trading as Etisalat) -// https://www.iana.org/domains/root/db/xn--mgbaakc7dvf.html -اتصالات - // xn--mgbab2bd : CORE Association // https://www.iana.org/domains/root/db/xn--mgbab2bd.html بازار @@ -11152,7 +11120,7 @@ xyz // https://www.iana.org/domains/root/db/yachts.html yachts -// yahoo : Oath Inc. +// yahoo : Yahoo Inc. // https://www.iana.org/domains/root/db/yahoo.html yahoo @@ -11217,6 +11185,12 @@ zuerich // ===BEGIN PRIVATE DOMAINS=== // (Note: these are in alphabetical order by company name) +// 12CHARS: https://12chars.com +// Submitted by Kenny Niehage +12chars.dev +12chars.it +12chars.pro + // 1GB LLC : https://www.1gb.ua/ // Submitted by 1GB LLC cc.ua @@ -11226,6 +11200,15 @@ ltd.ua // 611coin : https://611project.org/ 611.to +// AAA workspace : https://aaa.vodka +// Submitted by Kirill Rezraf +aaa.vodka + +// A2 Hosting +// Submitted by Tyler Hall +a2hosted.com +cpserver.com + // Aaron Marais' Gitlab pages: https://lab.aaronleem.co.za // Submitted by Aaron Marais graphox.us @@ -11242,12 +11225,18 @@ graphox.us // Submitted by Ofer Kalaora activetrail.biz +// Adaptable.io : https://adaptable.io +// Submitted by Mark Terrel +adaptable.app + // Adobe : https://www.adobe.com/ // Submitted by Ian Boston and Lars Trieloff adobeaemcloud.com *.dev.adobeaemcloud.com +aem.live hlx.live adobeaemcloud.net +aem.page hlx.page hlx3.page @@ -11319,7 +11308,7 @@ myamaze.net // Amazon API Gateway // Submitted by AWS Security -// Reference: 4d863337-ff98-4501-a6f2-361eba8445d6 +// Reference: 9e37648f-a66c-4655-9ab1-5981f8737197 execute-api.cn-north-1.amazonaws.com.cn execute-api.cn-northwest-1.amazonaws.com.cn execute-api.af-south-1.amazonaws.com @@ -11334,6 +11323,7 @@ execute-api.ap-southeast-2.amazonaws.com execute-api.ap-southeast-3.amazonaws.com execute-api.ap-southeast-4.amazonaws.com execute-api.ca-central-1.amazonaws.com +execute-api.ca-west-1.amazonaws.com execute-api.eu-central-1.amazonaws.com execute-api.eu-central-2.amazonaws.com execute-api.eu-north-1.amazonaws.com @@ -11360,23 +11350,28 @@ cloudfront.net // Amazon Cognito // Submitted by AWS Security -// Reference: 7bee1013-f456-47df-bfe8-03c78d946d61 +// Reference: 09588633-91fe-49d8-b4e7-ec36496d11f3 auth.af-south-1.amazoncognito.com auth.ap-northeast-1.amazoncognito.com auth.ap-northeast-2.amazoncognito.com auth.ap-northeast-3.amazoncognito.com auth.ap-south-1.amazoncognito.com +auth.ap-south-2.amazoncognito.com auth.ap-southeast-1.amazoncognito.com auth.ap-southeast-2.amazoncognito.com auth.ap-southeast-3.amazoncognito.com +auth.ap-southeast-4.amazoncognito.com auth.ca-central-1.amazoncognito.com auth.eu-central-1.amazoncognito.com +auth.eu-central-2.amazoncognito.com auth.eu-north-1.amazoncognito.com auth.eu-south-1.amazoncognito.com +auth.eu-south-2.amazoncognito.com auth.eu-west-1.amazoncognito.com auth.eu-west-2.amazoncognito.com auth.eu-west-3.amazoncognito.com auth.il-central-1.amazoncognito.com +auth.me-central-1.amazoncognito.com auth.me-south-1.amazoncognito.com auth.sa-east-1.amazoncognito.com auth.us-east-1.amazoncognito.com @@ -11399,7 +11394,7 @@ us-east-1.amazonaws.com // Amazon EMR // Submitted by AWS Security -// Reference: 597f3f8e-9283-4e48-8e32-7ee25a1ff6ab +// Reference: 82f43f9f-bbb8-400e-8349-854f5a62f20d emrappui-prod.cn-north-1.amazonaws.com.cn emrnotebooks-prod.cn-north-1.amazonaws.com.cn emrstudio-prod.cn-north-1.amazonaws.com.cn @@ -11424,6 +11419,9 @@ emrstudio-prod.ap-northeast-3.amazonaws.com emrappui-prod.ap-south-1.amazonaws.com emrnotebooks-prod.ap-south-1.amazonaws.com emrstudio-prod.ap-south-1.amazonaws.com +emrappui-prod.ap-south-2.amazonaws.com +emrnotebooks-prod.ap-south-2.amazonaws.com +emrstudio-prod.ap-south-2.amazonaws.com emrappui-prod.ap-southeast-1.amazonaws.com emrnotebooks-prod.ap-southeast-1.amazonaws.com emrstudio-prod.ap-southeast-1.amazonaws.com @@ -11433,18 +11431,30 @@ emrstudio-prod.ap-southeast-2.amazonaws.com emrappui-prod.ap-southeast-3.amazonaws.com emrnotebooks-prod.ap-southeast-3.amazonaws.com emrstudio-prod.ap-southeast-3.amazonaws.com +emrappui-prod.ap-southeast-4.amazonaws.com +emrnotebooks-prod.ap-southeast-4.amazonaws.com +emrstudio-prod.ap-southeast-4.amazonaws.com emrappui-prod.ca-central-1.amazonaws.com emrnotebooks-prod.ca-central-1.amazonaws.com emrstudio-prod.ca-central-1.amazonaws.com +emrappui-prod.ca-west-1.amazonaws.com +emrnotebooks-prod.ca-west-1.amazonaws.com +emrstudio-prod.ca-west-1.amazonaws.com emrappui-prod.eu-central-1.amazonaws.com emrnotebooks-prod.eu-central-1.amazonaws.com emrstudio-prod.eu-central-1.amazonaws.com +emrappui-prod.eu-central-2.amazonaws.com +emrnotebooks-prod.eu-central-2.amazonaws.com +emrstudio-prod.eu-central-2.amazonaws.com emrappui-prod.eu-north-1.amazonaws.com emrnotebooks-prod.eu-north-1.amazonaws.com emrstudio-prod.eu-north-1.amazonaws.com emrappui-prod.eu-south-1.amazonaws.com emrnotebooks-prod.eu-south-1.amazonaws.com emrstudio-prod.eu-south-1.amazonaws.com +emrappui-prod.eu-south-2.amazonaws.com +emrnotebooks-prod.eu-south-2.amazonaws.com +emrstudio-prod.eu-south-2.amazonaws.com emrappui-prod.eu-west-1.amazonaws.com emrnotebooks-prod.eu-west-1.amazonaws.com emrstudio-prod.eu-west-1.amazonaws.com @@ -11454,6 +11464,9 @@ emrstudio-prod.eu-west-2.amazonaws.com emrappui-prod.eu-west-3.amazonaws.com emrnotebooks-prod.eu-west-3.amazonaws.com emrstudio-prod.eu-west-3.amazonaws.com +emrappui-prod.il-central-1.amazonaws.com +emrnotebooks-prod.il-central-1.amazonaws.com +emrstudio-prod.il-central-1.amazonaws.com emrappui-prod.me-central-1.amazonaws.com emrnotebooks-prod.me-central-1.amazonaws.com emrstudio-prod.me-central-1.amazonaws.com @@ -11484,9 +11497,11 @@ emrstudio-prod.us-west-2.amazonaws.com // Amazon Managed Workflows for Apache Airflow // Submitted by AWS Security -// Reference: 4ab55e6f-90c0-4a8d-b6a0-52ca5dbb1c2e +// Reference: 87f24ece-a77e-40e8-bb4a-f6b74fe9f975 *.cn-north-1.airflow.amazonaws.com.cn *.cn-northwest-1.airflow.amazonaws.com.cn +*.af-south-1.airflow.amazonaws.com +*.ap-east-1.airflow.amazonaws.com *.ap-northeast-1.airflow.amazonaws.com *.ap-northeast-2.airflow.amazonaws.com *.ap-south-1.airflow.amazonaws.com @@ -11495,17 +11510,20 @@ emrstudio-prod.us-west-2.amazonaws.com *.ca-central-1.airflow.amazonaws.com *.eu-central-1.airflow.amazonaws.com *.eu-north-1.airflow.amazonaws.com +*.eu-south-1.airflow.amazonaws.com *.eu-west-1.airflow.amazonaws.com *.eu-west-2.airflow.amazonaws.com *.eu-west-3.airflow.amazonaws.com +*.me-south-1.airflow.amazonaws.com *.sa-east-1.airflow.amazonaws.com *.us-east-1.airflow.amazonaws.com *.us-east-2.airflow.amazonaws.com +*.us-west-1.airflow.amazonaws.com *.us-west-2.airflow.amazonaws.com // Amazon S3 // Submitted by AWS Security -// Reference: 0e801048-08f2-4064-9cb8-e7373e0b57f4 +// Reference: cd5c8b3a-67b7-4b40-9236-c87ce81a3d10 s3.dualstack.cn-north-1.amazonaws.com.cn s3-accesspoint.dualstack.cn-north-1.amazonaws.com.cn s3-website.dualstack.cn-north-1.amazonaws.com.cn @@ -11604,6 +11622,16 @@ s3-accesspoint-fips.ca-central-1.amazonaws.com s3-fips.ca-central-1.amazonaws.com s3-object-lambda.ca-central-1.amazonaws.com s3-website.ca-central-1.amazonaws.com +s3.dualstack.ca-west-1.amazonaws.com +s3-accesspoint.dualstack.ca-west-1.amazonaws.com +s3-accesspoint-fips.dualstack.ca-west-1.amazonaws.com +s3-fips.dualstack.ca-west-1.amazonaws.com +s3-website.dualstack.ca-west-1.amazonaws.com +s3.ca-west-1.amazonaws.com +s3-accesspoint.ca-west-1.amazonaws.com +s3-accesspoint-fips.ca-west-1.amazonaws.com +s3-fips.ca-west-1.amazonaws.com +s3-website.ca-west-1.amazonaws.com s3.dualstack.eu-central-1.amazonaws.com s3-accesspoint.dualstack.eu-central-1.amazonaws.com s3-website.dualstack.eu-central-1.amazonaws.com @@ -11784,9 +11812,25 @@ s3-fips.us-west-2.amazonaws.com s3-object-lambda.us-west-2.amazonaws.com s3-website.us-west-2.amazonaws.com +// Amazon SageMaker Ground Truth +// Submitted by AWS Security +// Reference: 98dbfde4-7802-48c3-8751-b60f204e0d9c +labeling.ap-northeast-1.sagemaker.aws +labeling.ap-northeast-2.sagemaker.aws +labeling.ap-south-1.sagemaker.aws +labeling.ap-southeast-1.sagemaker.aws +labeling.ap-southeast-2.sagemaker.aws +labeling.ca-central-1.sagemaker.aws +labeling.eu-central-1.sagemaker.aws +labeling.eu-west-1.sagemaker.aws +labeling.eu-west-2.sagemaker.aws +labeling.us-east-1.sagemaker.aws +labeling.us-east-2.sagemaker.aws +labeling.us-west-2.sagemaker.aws + // Amazon SageMaker Notebook Instances // Submitted by AWS Security -// Reference: fe8c9e94-5a22-486d-8750-991a3a9b13c6 +// Reference: b5ea56df-669e-43cc-9537-14aa172f5dfc notebook.af-south-1.sagemaker.aws notebook.ap-east-1.sagemaker.aws notebook.ap-northeast-1.sagemaker.aws @@ -11799,6 +11843,9 @@ notebook.ap-southeast-2.sagemaker.aws notebook.ap-southeast-3.sagemaker.aws notebook.ap-southeast-4.sagemaker.aws notebook.ca-central-1.sagemaker.aws +notebook-fips.ca-central-1.sagemaker.aws +notebook.ca-west-1.sagemaker.aws +notebook-fips.ca-west-1.sagemaker.aws notebook.eu-central-1.sagemaker.aws notebook.eu-central-2.sagemaker.aws notebook.eu-north-1.sagemaker.aws @@ -11820,6 +11867,7 @@ notebook-fips.us-gov-east-1.sagemaker.aws notebook.us-gov-west-1.sagemaker.aws notebook-fips.us-gov-west-1.sagemaker.aws notebook.us-west-1.sagemaker.aws +notebook-fips.us-west-1.sagemaker.aws notebook.us-west-2.sagemaker.aws notebook-fips.us-west-2.sagemaker.aws notebook.cn-north-1.sagemaker.com.cn @@ -11827,7 +11875,7 @@ notebook.cn-northwest-1.sagemaker.com.cn // Amazon SageMaker Studio // Submitted by AWS Security -// Reference: 057ee397-6bf8-4f20-b807-d7bc145ac980 +// Reference: 69c723d9-6e1a-4bff-a203-48eecd203183 studio.af-south-1.sagemaker.aws studio.ap-east-1.sagemaker.aws studio.ap-northeast-1.sagemaker.aws @@ -11841,6 +11889,7 @@ studio.ca-central-1.sagemaker.aws studio.eu-central-1.sagemaker.aws studio.eu-north-1.sagemaker.aws studio.eu-south-1.sagemaker.aws +studio.eu-south-2.sagemaker.aws studio.eu-west-1.sagemaker.aws studio.eu-west-2.sagemaker.aws studio.eu-west-3.sagemaker.aws @@ -11885,7 +11934,7 @@ analytics-gateway.us-west-2.amazonaws.com // AWS Cloud9 // Submitted by: AWS Security -// Reference: 05c44955-977c-4b57-938a-f2af92733f9f +// Reference: 30717f72-4007-4f0f-8ed4-864c6f2efec9 webview-assets.aws-cloud9.af-south-1.amazonaws.com vfs.cloud9.af-south-1.amazonaws.com webview-assets.cloud9.af-south-1.amazonaws.com @@ -11931,6 +11980,8 @@ webview-assets.cloud9.eu-west-2.amazonaws.com webview-assets.aws-cloud9.eu-west-3.amazonaws.com vfs.cloud9.eu-west-3.amazonaws.com webview-assets.cloud9.eu-west-3.amazonaws.com +webview-assets.aws-cloud9.il-central-1.amazonaws.com +vfs.cloud9.il-central-1.amazonaws.com webview-assets.aws-cloud9.me-south-1.amazonaws.com vfs.cloud9.me-south-1.amazonaws.com webview-assets.cloud9.me-south-1.amazonaws.com @@ -11950,6 +12001,11 @@ webview-assets.aws-cloud9.us-west-2.amazonaws.com vfs.cloud9.us-west-2.amazonaws.com webview-assets.cloud9.us-west-2.amazonaws.com +// AWS Directory Service +// Submitted by AWS Security +// Reference: a13203e8-42dc-4045-a0d2-2ee67bed1068 +awsapps.com + // AWS Elastic Beanstalk // Submitted by AWS Security // Reference: bb5a965c-dec3-4967-aa22-e306ad064797 @@ -11993,6 +12049,11 @@ us-west-2.elasticbeanstalk.com // Reference: d916759d-a08b-4241-b536-4db887383a6a awsglobalaccelerator.com +// AWS re:Post Private +// Submitted by AWS Security +// Reference: 83385945-225f-416e-9aa0-ad0632bfdcee +*.private.repost.aws + // eero // Submitted by Yue Kang // Reference: 264afe70-f62c-4c02-8ab9-b5281ed24461 @@ -12010,6 +12071,10 @@ tele.amune.org // Submitted by Apigee Security Team apigee.io +// Apis Networks: https://apisnetworks.com +// Submitted by Matt Saladna +panel.dev + // Apphud : https://apphud.com // Submitted by Alexander Selivanov siiites.com @@ -12027,6 +12092,10 @@ appudo.net // Submitted by Thomas Orozco on-aptible.com +// Aquapal : https://aquapal.net/ +// Submitted by Aki Ueno +f5.si + // ASEINet : https://www.aseinet.com/ // Submitted by Asei SEKIGUCHI user.aseinet.ne.jp @@ -12062,6 +12131,7 @@ autocode.dev // AVM : https://avm.de // Submitted by Andreas Weise +myfritz.link myfritz.net // AVStack Pte. Ltd. : https://avstack.io @@ -12121,10 +12191,18 @@ beagleboard.io // Submitted by Lev Nekrasov *.beget.app +// Besties : https://besties.house +// Submitted by Hazel Cora +pages.gay + // BetaInABox // Submitted by Adrian betainabox.com +// University of Bielsko-Biala regional domain: http://dns.bielsko.pl/ +// Submitted by Marcin +bielsko.pl + // BinaryLane : http://www.binarylane.com // Submitted by Nathan O'Sullivan bnr.la @@ -12166,8 +12244,13 @@ square7.de bplaced.net square7.net +// Brave : https://brave.com +// Submitted by Andrea Brancaleoni +*.s.brave.io + // Brendly : https://brendly.rs -// Submitted by Dusan Radovanovic +// Submitted by Dusan Radovanovic +shop.brendly.hr shop.brendly.rs // BrowserSafetyMark @@ -12191,7 +12274,9 @@ mycd.eu // Canva Pty Ltd : https://canva.com/ // Submitted by Joel Aquilina canva-apps.cn +*.my.canvasite.cn canva-apps.com +*.my.canva.site // Carrd : https://carrd.co // Submitted by AJ @@ -12329,6 +12414,12 @@ pages.dev r2.dev workers.dev +// cloudscale.ch AG : https://www.cloudscale.ch/ +// Submitted by Gaudenz Steinlin +cust.cloudscale.ch +objects.lpg.cloudscale.ch +objects.rma.cloudscale.ch + // Clovyr : https://clovyr.io // Submitted by Patrick Nielsen wnext.app @@ -12346,22 +12437,33 @@ co.cz // CDN77.com : http://www.cdn77.com // Submitted by Jan Krpes -c.cdn77.org +cdn77-storage.com +rsc.contentproxy9.cz cdn77-ssl.net r.cdn77.net -rsc.cdn77.org ssl.origin.cdn77-secure.org +c.cdn77.org +rsc.cdn77.org // Cloud DNS Ltd : http://www.cloudns.net -// Submitted by Aleksander Hristov +// Submitted by Aleksander Hristov & Boyan Peychev cloudns.asia +cloudns.be cloudns.biz -cloudns.club cloudns.cc +cloudns.ch +cloudns.cl +cloudns.club +dnsabr.com +cloudns.cx cloudns.eu cloudns.in cloudns.info +dns-cloud.net +dns-dynamic.net +cloudns.nz cloudns.org +cloudns.ph cloudns.pro cloudns.pw cloudns.us @@ -12374,6 +12476,11 @@ cnpy.gdn // Submitted by Moritz Marquardt codeberg.page +// CodeSandbox B.V. : https://codesandbox.io +// Submitted by Ives van Hoorne +csb.app +preview.csb.app + // CoDNS B.V. co.nl co.no @@ -12383,6 +12490,10 @@ co.no webhosting.be hosting-cluster.nl +// Convex : https://convex.dev/ +// Submitted by James Cowling +convex.site + // Coordination Center for TLD RU and XN--P1AI : https://cctld.ru/en/domains/domens_ru/reserved/ // Submitted by George Georgievsky ac.ru @@ -12404,10 +12515,18 @@ feste-ip.net knx-server.net static-access.net +// cPanel L.L.C. : https://www.cpanel.net/ +// Submitted by Dustin Scherer +*.cprapid.com + // Craynic, s.r.o. : http://www.craynic.com/ // Submitted by Ales Krajnik realm.cz +// Crisp IM SAS : https://crisp.chat/ +// Submitted by Baptiste Jamin +on.crisp.email + // Cryptonomic : https://cryptonomic.net/ // Submitted by Andrew Cady *.cryptonomic.net @@ -12428,6 +12547,13 @@ curv.dev *.ocp.customer-oci.com *.ocs.customer-oci.com +// Cyclic Software : https://www.cyclic.sh +// Submitted by Kam Lasater +cyclic.app +cyclic.cloud +cyclic-app.com +cyclic.co.in + // cyon GmbH : https://www.cyon.ch/ // Submitted by Dominic Luechinger cyon.link @@ -12473,6 +12599,7 @@ dyndns.dappnode.io // Dark, Inc. : https://darklang.com // Submitted by Paul Biggar builtwithdark.com +darklang.io // DataDetect, LLC. : https://datadetect.com // Submitted by Andrew Banchich @@ -12871,6 +12998,10 @@ ondigitalocean.app // Submitted by Robin H. Johnson *.digitaloceanspaces.com +// DigitalPlat : https://www.digitalplat.org/ +// Submitted by Edward Hsing +us.kg + // dnstrace.pro : https://dnstrace.pro/ // Submitted by Chris Partridge bci.dnstrace.pro @@ -12908,6 +13039,18 @@ e4.cz easypanel.app easypanel.host +// EasyWP : https://www.easywp.com +// Submitted by +*.ewp.live + +// Electromagnetic Field : https://www.emfcamp.org +// Submitted by +at.emf.camp + +// Elefunc, Inc. : https://elefunc.com +// Submitted by Cetin Sert +rt.ht + // Elementor : Elementor Ltd. // Submitted by Anton Barkan elementor.cloud @@ -13022,10 +13165,6 @@ url.tw // Submitted by Eric Jiang onfabrica.com -// Facebook, Inc. -// Submitted by Peter Ruibal -apps.fbsbx.com - // FAITID : https://faitid.org/ // Submitted by Maxim Alzoba // https://www.flexireg.net/stat_info @@ -13183,6 +13322,10 @@ flap.id onflashdrive.app fldrv.com +// FlutterFlow : https://flutterflow.io +// Submitted by Anton Emelyanov +flutterflow.app + // fly.io: https://fly.io // Submitted by Kurt Mackey fly.dev @@ -13193,13 +13336,14 @@ shw.io // Submitted by Jonathan Rudenberg flynnhosting.net -// Forgerock : https://www.forgerock.com +// Forgerock : https://www.forgerock.com // Submitted by Roderick Parr forgeblocks.com id.forgerock.io // Framer : https://www.framer.com -// Submitted by Koen Rouwhorst +// Submitted by Koen Rouwhorst +framer.ai framer.app framercanvas.com framer.media @@ -13240,6 +13384,24 @@ freemyip.com // Submitted by Daniel A. Maierhofer wien.funkfeuer.at +// Future Versatile Group. :https://www.fvg-on.net/ +// T.Kabu +daemon.asia +dix.asia +mydns.bz +0am.jp +0g0.jp +0j0.jp +0t0.jp +mydns.jp +pgw.jp +wjg.jp +keyword-on.net +live-on.net +server-on.net +mydns.tw +mydns.vc + // Futureweb GmbH : https://www.futureweb.at // Submitted by Andreas Schnederle-Wagner *.futurecms.at @@ -13251,6 +13413,10 @@ futuremailing.at *.kunden.ortsinfo.at *.statics.cloud +// GCom Internet : https://www.gcom.net.au +// Submitted by Leo Julius +aliases121.com + // GDS : https://www.gov.uk/service-manual/technology/managing-domain-names // Submitted by Stephen Ford independent-commission.uk @@ -13279,9 +13445,11 @@ gentlentapis.com lab.ms cdn-edges.net -// Ghost Foundation : https://ghost.org -// Submitted by Matt Hanley -ghost.io +// Getlocalcert: https://www.getlocalcert.net +// Submitted by Robert Alexander +localcert.net +localhostcert.net +corpnet.work // GignoSystemJapan: http://gsj.bz // Submitted by GignoSystemJapan @@ -13425,6 +13593,10 @@ whitesnow.jp zombie.jp heteml.net +// GoDaddy Registry : https://registry.godaddy +// Submitted by Rohan Durrant +graphic.design + // GOV.UK Platform as a Service : https://www.cloud.service.gov.uk/ // Submitted by Tom Whitwell cloudapps.digital @@ -13434,10 +13606,6 @@ london.cloudapps.digital // Submitted by Richard Baker pymnt.uk -// UKHomeOffice : https://www.gov.uk/government/organisations/home-office -// Submitted by Jon Shanks -homeoffice.gov.uk - // GlobeHosting, Inc. // Submitted by Zoltan Egresi ro.im @@ -13448,8 +13616,7 @@ goip.de // Google, Inc. // Submitted by Eduardo Vela -run.app -a.run.app +*.run.app web.app *.0emm.com appspot.com @@ -13549,6 +13716,10 @@ goupile.fr // Submitted by gov.nl +// GrayJay Web Solutions Inc. : https://grayjaysports.ca +// Submitted by Matt Yamkowy +grayjayleagues.com + // Group 53, LLC : https://www.group53.com // Submitted by Tyler Todd awsmppl.com @@ -13583,6 +13754,11 @@ hasura-app.io // Submitted by Richard Zowalla pages.it.hs-heilbronn.de +// Helio Networks : https://heliohost.org +// Submitted by Ben Frede +helioho.st +heliohost.us + // Hepforge : https://www.hepforge.org // Submitted by David Grellscheid hepforge.org @@ -13596,7 +13772,6 @@ herokussl.com // Submitted by Oren Eini ravendb.cloud ravendb.community -ravendb.me development.run ravendb.run @@ -13604,6 +13779,12 @@ ravendb.run // Submitted by Krzysztof Wolski homesklep.pl +// Homebase : https://homebase.id/ +// Submitted by Jason Babo +*.kin.one +*.id.pub +*.kin.pub + // Hong Kong Productivity Council: https://www.hkpc.org/ // Submitted by SECaaS Team secaas.hk @@ -13681,7 +13862,7 @@ biz.at info.at // info.cx : http://info.cx -// Submitted by Jacob Slater +// Submitted by June Slater info.cx // Interlegis : http://www.interlegis.leg.br @@ -13730,6 +13911,14 @@ iopsys.se // Submitted by Matthew Hardeman ipifony.net +// is-a.dev : https://www.is-a.dev +// Submitted by William Harrison +is-a.dev + +// ir.md : https://nic.ir.md +// Submitted by Ali Soizi +ir.md + // IServ GmbH : https://iserv.de // Submitted by Mario Hoberg iservschule.de @@ -13838,6 +14027,11 @@ myjino.ru // Submitted by Daniel Fariña jotelulu.cloud +// JouwWeb B.V. : https://www.jouwweb.nl +// Submitted by Camilo Sperberg +jouwweb.site +webadorsite.com + // Joyent : https://www.joyent.com/ // Submitted by Brian Bennett *.triton.zone @@ -13911,6 +14105,10 @@ lpusercontent.com // Submitted by Lelux Admin lelux.site +// Libre IT Ltd : https://libre.nz +// Submitted by Tomas Maggio +runcontainers.dev + // Lifetime Hosting : https://Lifetime.Hosting/ // Submitted by Mike Fillator co.business @@ -13921,10 +14119,6 @@ co.network co.place co.technology -// Lightmaker Property Manager, Inc. : https://app.lmpm.com/ -// Submitted by Greg Holland -app.lmpm.com - // linkyard ldt: https://www.linkyard.ch/ // Submitted by Mario Siegenthaler linkyard.cloud @@ -14057,6 +14251,11 @@ memset.net // Submitted by Ruben Schmidmeister messerli.app +// Meta Platforms, Inc. : https://meta.com/ +// Submitted by Jacob Cordero +atmeta.com +apps.fbsbx.com + // MetaCentrum, CESNET z.s.p.o. : https://www.metacentrum.cz/en/ // Submitted by Zdeněk Šustr *.cloud.metacentrum.cz @@ -14077,10 +14276,14 @@ co.pl // Microsoft Corporation : http://microsoft.com // Submitted by Public Suffix List Admin +// Managed by Corporate Domains +// Microsoft Azure : https://home.azure *.azurecontainer.io +azure-api.net +azureedge.net +azurefd.net azurewebsites.net azure-mobile.net -cloudapp.net azurestaticapps.net 1.azurestaticapps.net 2.azurestaticapps.net @@ -14094,6 +14297,10 @@ eastasia.azurestaticapps.net eastus2.azurestaticapps.net westeurope.azurestaticapps.net westus2.azurestaticapps.net +cloudapp.net +trafficmanager.net +blob.core.windows.net +servicebus.windows.net // minion.systems : http://minion.systems // Submitted by Robert Böttinger @@ -14107,6 +14314,10 @@ mintere.site // Submitted by Grayson Martin forte.id +// MODX Systems LLC : https://modx.com +// Submitted by Elizabeth Southwell +modx.dev + // Mozilla Corporation : https://mozilla.com // Submitted by Ben Francis mozilla-iot.org @@ -14153,6 +14364,10 @@ netlify.app // Submitted by Trung Tran 4u.com +// NGO.US Registry : https://nic.ngo.us +// Submitted by Alstra Solutions Ltd. Networking Team +ngo.us + // ngrok : https://ngrok.com/ // Submitted by Alan Shreve ngrok.app @@ -14168,18 +14383,24 @@ jp.ngrok.io sa.ngrok.io us.ngrok.io ngrok.pizza +ngrok.pro // Nicolaus Copernicus University in Torun - MSK TORMAN (https://www.man.torun.pl) torun.pl // Nimbus Hosting Ltd. : https://www.nimbushosting.co.uk/ -// Submitted by Nicholas Ford +// Submitted by Nicholas Ford nh-serv.co.uk +nimsite.uk // NFSN, Inc. : https://www.NearlyFreeSpeech.NET/ // Submitted by Jeff Wheelhouse nfshost.com +// NFT.Storage : https://nft.storage/ +// Submitted by Vasco Santos or +ipfs.nftstorage.link + // Noop : https://noop.app // Submitted by Nathaniel Schweinberg *.developer.app @@ -14330,6 +14551,10 @@ pcloud.host // Submitted by Matthew Brown nyc.mn +// O3O.Foundation : https://o3o.foundation/ +// Submitted by the prvcy.page Registry Team +prvcy.page + // Observable, Inc. : https://observablehq.com // Submitted by Mike Bostock static.observableusercontent.com @@ -14359,7 +14584,6 @@ omniwe.site 123minsida.se 123miweb.es 123paginaweb.pt -123sait.ru 123siteweb.fr 123webseite.at 123webseite.de @@ -14377,6 +14601,13 @@ simplesite.pl // Submitted by Eddie Jones nid.io +// Open Domains : https://open-domains.net +// Submitted by William Harrison +is-cool.dev +is-not-a.dev +localplayer.dev +is-local.org + // Open Social : https://www.getopensocial.com/ // Submitted by Alexander Varwijk opensocial.site @@ -14397,6 +14628,11 @@ operaunite.com // Submitted by Alexandre Linte tech.orange +// OsSav Technology Ltd. : https://ossav.com/ +// TLD Nic: http://nic.can.re - TLD Whois Server: whois.can.re +// Submitted by OsSav Technology Ltd. +can.re + // Oursky Limited : https://authgear.com/, https://skygear.io/ // Submitted by Authgear Team , Skygear Developer authgear-staging.com @@ -14447,10 +14683,11 @@ pagexl.com // pcarrier.ca Software Inc: https://pcarrier.ca/ // Submitted by Pierre Carrier -bar0.net -bar1.net -bar2.net -rdv.to +*.xmit.co +xmit.dev +srv.us +gh.srv.us +gl.srv.us // .pl domains (grandfathered) art.pl @@ -14483,7 +14720,8 @@ on-web.fr // Platform.sh : https://platform.sh // Submitted by Nikola Kotur -bc.platform.sh +*.upsun.app +upsunapp.com ent.platform.sh eu.platform.sh us.platform.sh @@ -14502,6 +14740,10 @@ pdns.page plesk.page pleskns.com +// Pley AB : https://www.pley.com/ +// Submitted by Henning Pohl +pley.games + // Port53 : https://port53.io/ // Submitted by Maximilian Schieder dyn53.io @@ -14533,10 +14775,6 @@ xen.prgmr.com // Submitted by registry priv.at -// privacytools.io : https://www.privacytools.io/ -// Submitted by Jonah Aragon -prvcy.page - // Protocol Labs : https://protocol.ai/ // Submitted by Michael Burns *.dweb.link @@ -14578,6 +14816,8 @@ qbuser.com // Rad Web Hosting: https://radwebhosting.com // Submitted by Scott Claeys cloudsite.builders +myradweb.net +servername.us // Redgate Software: https://red-gate.com // Submitted by Andrew Farries @@ -14601,9 +14841,12 @@ qcx.io *.sys.qcx.io // QNAP System Inc : https://www.qnap.com -// Submitted by Nick Chang -dev-myqnapcloud.com +// Submitted by Nick Chang +myqnapcloud.cn alpha-myqnapcloud.com +dev-myqnapcloud.com +mycloudnas.com +mynascloud.com myqnapcloud.com // Quip : https://quip.com @@ -14644,11 +14887,40 @@ app.render.com onrender.com // Repl.it : https://repl.it -// Submitted by Lincoln Bergeson +// Submitted by Lincoln Bergeson +replit.app +id.replit.app firewalledreplit.co id.firewalledreplit.co repl.co id.repl.co +replit.dev +archer.replit.dev +bones.replit.dev +canary.replit.dev +global.replit.dev +hacker.replit.dev +id.replit.dev +janeway.replit.dev +kim.replit.dev +kira.replit.dev +kirk.replit.dev +odo.replit.dev +paris.replit.dev +picard.replit.dev +pike.replit.dev +prerelease.replit.dev +reed.replit.dev +riker.replit.dev +sisko.replit.dev +spock.replit.dev +staging.replit.dev +sulu.replit.dev +tarpit.replit.dev +teams.replit.dev +tucker.replit.dev +wesley.replit.dev +worf.replit.dev repl.run // Resin.io : https://resin.io @@ -14745,10 +15017,11 @@ from.tv sakura.tv // Salesforce.com, Inc. https://salesforce.com/ -// Submitted by Michael Biven +// Submitted by Michael Biven and Aaron Romeo *.builder.code.com *.dev-builder.code.com *.stg-builder.code.com +*.001.test.code-builder-stg.platform.salesforce.com // Sandstorm Development Group, Inc. : https://sandcats.io/ // Submitted by Asheesh Laroia @@ -14764,6 +15037,7 @@ logoip.com fr-par-1.baremetal.scw.cloud fr-par-2.baremetal.scw.cloud nl-ams-1.baremetal.scw.cloud +cockpit.fr-par.scw.cloud fnc.fr-par.scw.cloud functions.fnc.fr-par.scw.cloud k8s.fr-par.scw.cloud @@ -14774,11 +15048,13 @@ whm.fr-par.scw.cloud priv.instances.scw.cloud pub.instances.scw.cloud k8s.scw.cloud +cockpit.nl-ams.scw.cloud k8s.nl-ams.scw.cloud nodes.k8s.nl-ams.scw.cloud s3.nl-ams.scw.cloud s3-website.nl-ams.scw.cloud whm.nl-ams.scw.cloud +cockpit.pl-waw.scw.cloud k8s.pl-waw.scw.cloud nodes.k8s.pl-waw.scw.cloud s3.pl-waw.scw.cloud @@ -14800,6 +15076,10 @@ service.gov.scot // Submitted by Shante Adam scrysec.com +// Scrypted : https://scrypted.app +// Submitted by Koushik Dutta +client.scrypted.io + // Securepoint GmbH : https://www.securepoint.de // Submitted by Erik Anders firewall-gateway.com @@ -14839,6 +15119,10 @@ biz.ua co.ua pp.ua +// Sheezy.Art : https://sheezy.art +// Submitted by Nyoom +sheezy.games + // Shift Crypto AG : https://shiftcrypto.ch // Submitted by alex shiftcrypto.dev @@ -14887,7 +15171,7 @@ alpha.bounty-full.com beta.bounty-full.com // Smallregistry by Promopixel SARL: https://www.smallregistry.net -// Former AFNIC's SLDs +// Former AFNIC's SLDs // Submitted by Jérôme Lipowicz aeroport.fr avocat.fr @@ -14909,9 +15193,9 @@ small-web.org vp4.me // Snowflake Inc : https://www.snowflake.com/ -// Submitted by Faith Olapade -snowflake.app -privatelink.snowflake.app +// Submitted by Sam Haar +*.snowflake.app +*.privatelink.snowflake.app streamlit.app streamlitapp.com @@ -14923,10 +15207,24 @@ try-snowplow.com // Submitted by Drew DeVault srht.site +// StackBlitz : https://stackblitz.com +// Submitted by Dominic Elm +w-corp-staticblitz.com +w-credentialless-staticblitz.com +w-staticblitz.com + // Stackhero : https://www.stackhero.io // Submitted by Adrien Gillon stackhero-network.com +// STACKIT : https://www.stackit.de/en/ +// Submitted by STACKIT-DNS Team (Simon Stier) +runs.onstackit.cloud +stackit.gg +stackit.rocks +stackit.run +stackit.zone + // Staclar : https://staclar.com // Submitted by Q Misell musician.io @@ -14993,6 +15291,19 @@ myspreadshop.co.uk // Submitted by Jacob Lee api.stdlib.com +// stereosense GmbH : https://www.involve.me +// Submitted by Florian Burmann +feedback.ac +forms.ac +assessments.cx +calculators.cx +funnels.cx +paynow.cx +quizzes.cx +researched.cx +tests.cx +surveys.so + // Storipress : https://storipress.com // Submitted by Benno Liu storipress.app @@ -15001,6 +15312,12 @@ storipress.app // Submitted by Philip Hutchins storj.farm +// Streak : https://streak.com +// Submitted by Blake Kadatz +streak-link.com +streaklinks.com +streakusercontent.com + // Studenten Net Twente : http://www.snt.utwente.nl/ // Submitted by Silke Hofstra utwente.io @@ -15063,6 +15380,7 @@ taifun-dns.de // Submitted by David Anderson beta.tailscale.net ts.net +*.c.ts.net // TASK geographical domains (www.task.gda.pl/uslugi/dns) gda.pl @@ -15196,6 +15514,10 @@ inc.hk // Submitted by ITComdomains it.com +// Unison Computing, PBC : https://unison.cloud +// Submitted by Simon Højberg +unison-services.cloud + // UNIVERSAL DOMAIN REGISTRY : https://www.udr.org.yt/ // see also: whois -h whois.udr.org.yt help // Submitted by Atanunu Igbunuroghene @@ -15245,48 +15567,6 @@ v-info.info // Submitted by Nathan van Bakel voorloper.cloud -// Voxel.sh DNS : https://voxel.sh/dns/ -// Submitted by Mia Rehlinger -neko.am -nyaa.am -be.ax -cat.ax -es.ax -eu.ax -gg.ax -mc.ax -us.ax -xy.ax -nl.ci -xx.gl -app.gp -blog.gt -de.gt -to.gt -be.gy -cc.hn -blog.kg -io.kg -jp.kg -tv.kg -uk.kg -us.kg -de.ls -at.md -de.md -jp.md -to.md -indie.porn -vxl.sh -ch.tc -me.tc -we.tc -nyan.to -at.vg -blog.vu -dev.vu -me.vu - // V.UA Domain Administrator : https://domain.v.ua/ // Submitted by Serhii Rostilo v.ua @@ -15299,6 +15579,11 @@ v.ua // Submitted by Masayuki Note wafflecell.com +// Webflow, Inc. : https://www.webflow.com +// Submitted by Webflow Security Team +webflow.io +webflowtest.io + // WebHare bv: https://www.webhare.com/ // Submitted by Arnold Hendriks *.webhare.dev @@ -15310,6 +15595,10 @@ reserve-online.com bookonline.app hotelwithflight.com +// WebWaddle Ltd: https://webwaddle.com/ +// Submitted by Merlin Glander +*.wadl.top + // WeDeploy by Liferay, Inc. : https://www.wedeploy.com // Submitted by Henrique Vicente wedeploy.io @@ -15418,6 +15707,10 @@ noho.st za.net za.org +// ZAP-Hosting GmbH & Co. KG : https://zap-hosting.com +// Submitted by Julian Alker +zap.cloud + // Zine EOOD : https://zine.bg/ // Submitted by Martin Angelov bss.design diff --git a/make/jdk/src/classes/build/tools/tzdb/TzdbZoneRulesProvider.java b/make/jdk/src/classes/build/tools/tzdb/TzdbZoneRulesProvider.java index d82e58e3420..760397255b8 100644 --- a/make/jdk/src/classes/build/tools/tzdb/TzdbZoneRulesProvider.java +++ b/make/jdk/src/classes/build/tools/tzdb/TzdbZoneRulesProvider.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -364,33 +364,35 @@ int parseYear(String year, int defaultYear) { } 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; - } + int len = mon.length(); + + if (mon.regionMatches(true, 0, "January", 0, len)) return Month.JANUARY; + if (mon.regionMatches(true, 0, "February", 0, len)) return Month.FEBRUARY; + if (mon.regionMatches(true, 0, "March", 0, len)) return Month.MARCH; + if (mon.regionMatches(true, 0, "April", 0, len)) return Month.APRIL; + if (mon.regionMatches(true, 0, "May", 0, len)) return Month.MAY; + if (mon.regionMatches(true, 0, "June", 0, len)) return Month.JUNE; + if (mon.regionMatches(true, 0, "July", 0, len)) return Month.JULY; + if (mon.regionMatches(true, 0, "August", 0, len)) return Month.AUGUST; + if (mon.regionMatches(true, 0, "September", 0, len)) return Month.SEPTEMBER; + if (mon.regionMatches(true, 0, "October", 0, len)) return Month.OCTOBER; + if (mon.regionMatches(true, 0, "November", 0, len)) return Month.NOVEMBER; + if (mon.regionMatches(true, 0, "December", 0, len)) 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; - } + int len = dow.length(); + + if (dow.regionMatches(true, 0, "Monday", 0, len)) return DayOfWeek.MONDAY; + if (dow.regionMatches(true, 0, "Tuesday", 0, len)) return DayOfWeek.TUESDAY; + if (dow.regionMatches(true, 0, "Wednesday", 0, len)) return DayOfWeek.WEDNESDAY; + if (dow.regionMatches(true, 0, "Thursday", 0, len)) return DayOfWeek.THURSDAY; + if (dow.regionMatches(true, 0, "Friday", 0, len)) return DayOfWeek.FRIDAY; + if (dow.regionMatches(true, 0, "Saturday", 0, len)) return DayOfWeek.SATURDAY; + if (dow.regionMatches(true, 0, "Sunday", 0, len)) return DayOfWeek.SUNDAY; + throw new IllegalArgumentException("Unknown day-of-week: " + dow); } diff --git a/src/java.base/macosx/native/libjava/ProcessHandleImpl_macosx.c b/src/java.base/macosx/native/libjava/ProcessHandleImpl_macosx.c index 30fa8eea206..b9f3428c1fa 100644 --- a/src/java.base/macosx/native/libjava/ProcessHandleImpl_macosx.c +++ b/src/java.base/macosx/native/libjava/ProcessHandleImpl_macosx.c @@ -89,25 +89,35 @@ jint os_getChildren(JNIEnv *env, jlong jpid, jlongArray jarray, } } - // Get buffer size needed to read all processes - int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_ALL, 0}; - if (sysctl(mib, 4, NULL, &bufSize, NULL, 0) < 0) { - JNU_ThrowByNameWithLastError(env, - "java/lang/RuntimeException", "sysctl failed"); - return -1; - } + int errsysctl; + int maxRetries = 100; + void *buffer = NULL; + do { + int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_ALL, 0}; + if (buffer != NULL) free(buffer); + // Get buffer size needed to read all processes + if (sysctl(mib, 4, NULL, &bufSize, NULL, 0) < 0) { + JNU_ThrowByNameWithMessageAndLastError(env, + "java/lang/RuntimeException", "sysctl failed"); + return -1; + } - // Allocate buffer big enough for all processes - void *buffer = malloc(bufSize); - if (buffer == NULL) { - JNU_ThrowOutOfMemoryError(env, "malloc failed"); - return -1; - } + // Allocate buffer big enough for all processes; add a little + // bit of space to be able to hold a few more proc infos + // for processes started right after the first sysctl call + buffer = malloc(bufSize + 4 * sizeof(struct kinfo_proc)); + if (buffer == NULL) { + JNU_ThrowOutOfMemoryError(env, "malloc failed"); + return -1; + } - // Read process info for all processes - if (sysctl(mib, 4, buffer, &bufSize, NULL, 0) < 0) { - JNU_ThrowByNameWithLastError(env, - "java/lang/RuntimeException", "sysctl failed"); + // Read process info for all processes + errsysctl = sysctl(mib, 4, buffer, &bufSize, NULL, 0); + } while (errsysctl < 0 && errno == ENOMEM && maxRetries-- > 0); + + if (errsysctl < 0) { + JNU_ThrowByNameWithMessageAndLastError(env, + "java/lang/RuntimeException", "sysctl failed to get info about all processes"); free(buffer); return -1; } diff --git a/src/java.base/share/classes/java/lang/invoke/VarHandles.java b/src/java.base/share/classes/java/lang/invoke/VarHandles.java index fb86bfab0e8..97d53c7bbb0 100644 --- a/src/java.base/share/classes/java/lang/invoke/VarHandles.java +++ b/src/java.base/share/classes/java/lang/invoke/VarHandles.java @@ -38,8 +38,6 @@ import java.util.List; import java.util.Map; import java.util.Objects; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; import java.util.stream.Stream; import static java.lang.invoke.MethodHandleStatics.UNSAFE; @@ -50,13 +48,6 @@ final class VarHandles { - static ClassValue> ADDRESS_FACTORIES = new ClassValue<>() { - @Override - protected ConcurrentMap computeValue(Class type) { - return new ConcurrentHashMap<>(); - } - }; - static VarHandle makeFieldHandle(MemberName f, Class refc, Class type, boolean isWriteAllowedOnFinalFields) { if (!f.isStatic()) { long foffset = MethodHandleNatives.objectFieldOffset(f); diff --git a/src/java.base/share/classes/java/nio/charset/Charset.java b/src/java.base/share/classes/java/nio/charset/Charset.java index 0ac18a23ba8..2b194212209 100644 --- a/src/java.base/share/classes/java/nio/charset/Charset.java +++ b/src/java.base/share/classes/java/nio/charset/Charset.java @@ -41,7 +41,6 @@ import java.util.Locale; import java.util.Map; import java.util.NoSuchElementException; -import java.util.Objects; import java.util.ServiceConfigurationError; import java.util.ServiceLoader; import java.util.Set; @@ -636,7 +635,12 @@ public static Charset defaultCharset() { * If the canonical name or any of the aliases are illegal */ protected Charset(String canonicalName, String[] aliases) { - String[] as = Objects.requireNonNullElse(aliases, zeroAliases); + String[] as = + aliases == null ? + zeroAliases : + VM.isSystemDomainLoader(getClass().getClassLoader()) ? + aliases : + Arrays.copyOf(aliases, aliases.length); // Skip checks for the standard, built-in Charsets we always load // during initialization. diff --git a/src/java.base/share/classes/java/nio/file/Files.java b/src/java.base/share/classes/java/nio/file/Files.java index 6270f00be26..dec80152cc6 100644 --- a/src/java.base/share/classes/java/nio/file/Files.java +++ b/src/java.base/share/classes/java/nio/file/Files.java @@ -806,7 +806,7 @@ private static void createAndCheckIsDirectory(Path dir, try { createDirectory(dir, attrs); } catch (FileAlreadyExistsException x) { - if (!isDirectory(dir, LinkOption.NOFOLLOW_LINKS)) + if (!isDirectory(dir)) throw x; } } diff --git a/src/java.base/share/classes/java/security/cert/X509CertSelector.java b/src/java.base/share/classes/java/security/cert/X509CertSelector.java index b838b3f51c2..f5448c479a9 100644 --- a/src/java.base/share/classes/java/security/cert/X509CertSelector.java +++ b/src/java.base/share/classes/java/security/cert/X509CertSelector.java @@ -1970,10 +1970,10 @@ public boolean match(Certificate cert) { } if (debug != null) { - debug.println("X509CertSelector.match(SN: " - + (xcert.getSerialNumber()).toString(16) + "\n Issuer: " - + xcert.getIssuerX500Principal() + "\n Subject: " + xcert.getSubjectX500Principal() - + ")"); + debug.println("X509CertSelector.match(Serial number: " + + Debug.toString(xcert.getSerialNumber()) + + "\n Issuer: " + xcert.getIssuerX500Principal() + "\n Subject: " + + xcert.getSubjectX500Principal() + ")"); } /* match on X509Certificate */ diff --git a/src/java.base/share/classes/java/util/zip/ZipFile.java b/src/java.base/share/classes/java/util/zip/ZipFile.java index bdf48d3955a..17a8015dc0c 100644 --- a/src/java.base/share/classes/java/util/zip/ZipFile.java +++ b/src/java.base/share/classes/java/util/zip/ZipFile.java @@ -1673,6 +1673,9 @@ private void initCEN(int knownTotal) throws IOException { zerror("invalid END header (bad central directory offset)"); } // read in the CEN and END + if (end.cenlen + ENDHDR >= Integer.MAX_VALUE) { + zerror("invalid END header (central directory size too large)"); + } cen = this.cen = new byte[(int)(end.cenlen + ENDHDR)]; if (readFullyAt(cen, 0, cen.length, cenpos) != end.cenlen + ENDHDR) { zerror("read CEN tables failed"); diff --git a/src/java.base/share/classes/sun/net/www/protocol/http/HttpURLConnection.java b/src/java.base/share/classes/sun/net/www/protocol/http/HttpURLConnection.java index 288ebfd8504..e3e72723428 100644 --- a/src/java.base/share/classes/sun/net/www/protocol/http/HttpURLConnection.java +++ b/src/java.base/share/classes/sun/net/www/protocol/http/HttpURLConnection.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1995, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1995, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -303,7 +303,8 @@ private static Set schemesListToSet(String list) { } static final String httpVersion = "HTTP/1.1"; - static final String acceptString = "*/*"; + static final String acceptString = + "text/html, image/gif, image/jpeg, */*; q=0.2"; // the following http request headers should NOT have their values // returned for security reasons. diff --git a/src/java.base/share/classes/sun/nio/cs/StreamDecoder.java b/src/java.base/share/classes/sun/nio/cs/StreamDecoder.java index 15cdaedf4b9..c8a6a476e66 100644 --- a/src/java.base/share/classes/sun/nio/cs/StreamDecoder.java +++ b/src/java.base/share/classes/sun/nio/cs/StreamDecoder.java @@ -186,7 +186,13 @@ public int read(char[] cbuf, int offset, int length) throws IOException { return n + 1; } - return n + implRead(cbuf, off, off + len); + // Read remaining characters + int nr = implRead(cbuf, off, off + len); + + // At this point, n is either 1 if a leftover character was read, + // or 0 if no leftover character was read. If n is 1 and nr is -1, + // indicating EOF, then we don't return their sum as this loses data. + return (nr < 0) ? (n == 1 ? 1 : nr) : (n + nr); } } diff --git a/src/java.base/share/classes/sun/security/jca/JCAUtil.java b/src/java.base/share/classes/sun/security/jca/JCAUtil.java index 862a33530ed..0e2d0e29cb4 100644 --- a/src/java.base/share/classes/sun/security/jca/JCAUtil.java +++ b/src/java.base/share/classes/sun/security/jca/JCAUtil.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -34,6 +34,7 @@ import jdk.internal.event.EventHelper; import jdk.internal.event.X509CertificateEvent; import sun.security.util.KeyUtil; +import sun.security.util.Debug; /** * Collection of static utility methods used by the security framework. @@ -105,7 +106,7 @@ public static void tryCommitCertEvent(Certificate cert) { (cert instanceof X509Certificate x509)) { PublicKey pKey = x509.getPublicKey(); String algId = x509.getSigAlgName(); - String serNum = x509.getSerialNumber().toString(16); + String serNum = Debug.toString(x509.getSerialNumber()); String subject = x509.getSubjectX500Principal().toString(); String issuer = x509.getIssuerX500Principal().toString(); String keyType = pKey.getAlgorithm(); diff --git a/src/java.base/share/classes/sun/security/pkcs/SignerInfo.java b/src/java.base/share/classes/sun/security/pkcs/SignerInfo.java index af466e66156..52b916b5bd6 100644 --- a/src/java.base/share/classes/sun/security/pkcs/SignerInfo.java +++ b/src/java.base/share/classes/sun/security/pkcs/SignerInfo.java @@ -698,14 +698,15 @@ private void verifyTimestamp(TimestampToken token) md.digest(encryptedDigest))) { throw new SignatureException("Signature timestamp (#" + - token.getSerialNumber() + ") generated on " + token.getDate() + - " is inapplicable"); + Debug.toString(token.getSerialNumber()) + + ") generated on " + token.getDate() + " is inapplicable"); } if (debug != null) { debug.println(); debug.println("Detected signature timestamp (#" + - token.getSerialNumber() + ") generated on " + token.getDate()); + Debug.toString(token.getSerialNumber()) + + ") generated on " + token.getDate()); debug.println(); } } diff --git a/src/java.base/share/classes/sun/security/provider/certpath/BasicChecker.java b/src/java.base/share/classes/sun/security/provider/certpath/BasicChecker.java index 7fc691bd2db..a09be783e6b 100644 --- a/src/java.base/share/classes/sun/security/provider/certpath/BasicChecker.java +++ b/src/java.base/share/classes/sun/security/provider/certpath/BasicChecker.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -244,7 +244,7 @@ private void updateState(X509Certificate currCert) debug.println("BasicChecker.updateState issuer: " + currCert.getIssuerX500Principal().toString() + "; subject: " + currCert.getSubjectX500Principal() + "; serial#: " + - currCert.getSerialNumber().toString()); + Debug.toString(currCert.getSerialNumber())); } if (PKIX.isDSAPublicKeyWithoutParams(cKey)) { // cKey needs to inherit DSA parameters from prev key diff --git a/src/java.base/share/classes/sun/security/provider/certpath/Builder.java b/src/java.base/share/classes/sun/security/provider/certpath/Builder.java index c920ad02826..f48bf83ce73 100644 --- a/src/java.base/share/classes/sun/security/provider/certpath/Builder.java +++ b/src/java.base/share/classes/sun/security/provider/certpath/Builder.java @@ -435,8 +435,7 @@ boolean addMatchingCerts(X509CertSelector selector, if (debug != null) { debug.println("Builder.addMatchingCerts: " + "adding target cert" + - "\n SN: " + Debug.toHexString( - targetCert.getSerialNumber()) + + "\n SN: " + Debug.toString(targetCert.getSerialNumber()) + "\n Subject: " + targetCert.getSubjectX500Principal() + "\n Issuer: " + targetCert.getIssuerX500Principal()); } diff --git a/src/java.base/share/classes/sun/security/provider/certpath/CertId.java b/src/java.base/share/classes/sun/security/provider/certpath/CertId.java index 34c06a464df..54a37aaeafe 100644 --- a/src/java.base/share/classes/sun/security/provider/certpath/CertId.java +++ b/src/java.base/share/classes/sun/security/provider/certpath/CertId.java @@ -108,7 +108,7 @@ public CertId(X500Principal issuerName, PublicKey issuerKey, encoder.encodeBuffer(issuerNameHash)); System.out.println("issuerKeyHash is " + encoder.encodeBuffer(issuerKeyHash)); - System.out.println("SerialNumber is " + serialNumber.getNumber()); + System.out.println("SerialNumber is " + Debug.toString(serialNumber.getNumber())); } } diff --git a/src/java.base/share/classes/sun/security/provider/certpath/DistributionPointFetcher.java b/src/java.base/share/classes/sun/security/provider/certpath/DistributionPointFetcher.java index 16d9b7f606f..8cde6d66be8 100644 --- a/src/java.base/share/classes/sun/security/provider/certpath/DistributionPointFetcher.java +++ b/src/java.base/share/classes/sun/security/provider/certpath/DistributionPointFetcher.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -349,7 +349,7 @@ static boolean verifyCRL(X509CertImpl certImpl, DistributionPoint point, if (debug != null) { debug.println("DistributionPointFetcher.verifyCRL: " + "checking revocation status for" + - "\n SN: " + Debug.toHexString(certImpl.getSerialNumber()) + + "\n SN: " + Debug.toString(certImpl.getSerialNumber()) + "\n Subject: " + certImpl.getSubjectX500Principal() + "\n Issuer: " + certImpl.getIssuerX500Principal()); } diff --git a/src/java.base/share/classes/sun/security/provider/certpath/ForwardBuilder.java b/src/java.base/share/classes/sun/security/provider/certpath/ForwardBuilder.java index 50f2daa6081..77c8f3825d9 100644 --- a/src/java.base/share/classes/sun/security/provider/certpath/ForwardBuilder.java +++ b/src/java.base/share/classes/sun/security/provider/certpath/ForwardBuilder.java @@ -280,7 +280,7 @@ private void getMatchingCACerts(ForwardState currentState, debug.println("ForwardBuilder.getMatchingCACerts: " + "found matching trust anchor." + "\n SN: " + - Debug.toHexString(trustedCert.getSerialNumber()) + + Debug.toString(trustedCert.getSerialNumber()) + "\n Subject: " + trustedCert.getSubjectX500Principal() + "\n Issuer: " + @@ -703,7 +703,7 @@ void verifyCert(X509Certificate cert, State currentState, { if (debug != null) { debug.println("ForwardBuilder.verifyCert(SN: " - + Debug.toHexString(cert.getSerialNumber()) + + Debug.toString(cert.getSerialNumber()) + "\n Issuer: " + cert.getIssuerX500Principal() + ")" + "\n Subject: " + cert.getSubjectX500Principal() + ")"); } diff --git a/src/java.base/share/classes/sun/security/provider/certpath/OCSPResponse.java b/src/java.base/share/classes/sun/security/provider/certpath/OCSPResponse.java index d31f206bf08..dcaa0f4a0e4 100644 --- a/src/java.base/share/classes/sun/security/provider/certpath/OCSPResponse.java +++ b/src/java.base/share/classes/sun/security/provider/certpath/OCSPResponse.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -404,7 +404,8 @@ void verify(List certIds, IssuerInfo issuerInfo, } if (debug != null) { debug.println("Status of certificate (with serial number " + - certId.getSerialNumber() + ") is: " + sr.getCertStatus()); + Debug.toString(certId.getSerialNumber()) + + ") is: " + sr.getCertStatus()); } } diff --git a/src/java.base/share/classes/sun/security/provider/certpath/RevocationChecker.java b/src/java.base/share/classes/sun/security/provider/certpath/RevocationChecker.java index 9da1405a628..bdb8dffac2e 100644 --- a/src/java.base/share/classes/sun/security/provider/certpath/RevocationChecker.java +++ b/src/java.base/share/classes/sun/security/provider/certpath/RevocationChecker.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -351,7 +351,7 @@ private void check(X509Certificate xcert, { if (debug != null) { debug.println("RevocationChecker.check: checking cert" + - "\n SN: " + Debug.toHexString(xcert.getSerialNumber()) + + "\n SN: " + Debug.toString(xcert.getSerialNumber()) + "\n Subject: " + xcert.getSubjectX500Principal() + "\n Issuer: " + xcert.getIssuerX500Principal()); } @@ -647,7 +647,7 @@ private void checkApprovedCRLs(X509Certificate cert, debug.println("RevocationChecker.checkApprovedCRLs() " + "starting the final sweep..."); debug.println("RevocationChecker.checkApprovedCRLs()" + - " cert SN: " + sn.toString()); + " cert SN: " + Debug.toString(sn)); } CRLReason reasonCode = CRLReason.UNSPECIFIED; diff --git a/src/java.base/share/classes/sun/security/provider/certpath/Vertex.java b/src/java.base/share/classes/sun/security/provider/certpath/Vertex.java index 06bfb2f111d..be48402f0d7 100644 --- a/src/java.base/share/classes/sun/security/provider/certpath/Vertex.java +++ b/src/java.base/share/classes/sun/security/provider/certpath/Vertex.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2022, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -150,7 +150,7 @@ public String certToString() { sb.append("Subject: ").append (x509Cert.getSubjectX500Principal()).append("\n"); sb.append("SerialNum: ").append - (x509Cert.getSerialNumber().toString(16)).append("\n"); + (Debug.toString(x509Cert.getSerialNumber())).append("\n"); sb.append("Expires: ").append (x509Cert.getNotAfter().toString()).append("\n"); boolean[] iUID = x509Cert.getIssuerUniqueID(); diff --git a/src/java.base/share/classes/sun/security/ssl/SSLLogger.java b/src/java.base/share/classes/sun/security/ssl/SSLLogger.java index 9f2cbaf4837..a97eb68dfa6 100644 --- a/src/java.base/share/classes/sun/security/ssl/SSLLogger.java +++ b/src/java.base/share/classes/sun/security/ssl/SSLLogger.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2023, Oracle and/or its affiliates. All rights reserved. * 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,6 +46,7 @@ import sun.security.action.GetPropertyAction; import sun.security.util.HexDumpEncoder; +import sun.security.util.Debug; import sun.security.x509.*; import static java.nio.charset.StandardCharsets.UTF_8; @@ -471,8 +472,7 @@ private static String formatCertificate(Certificate certificate) { if (certExts == null) { Object[] certFields = { x509.getVersion(), - Utilities.toHexString( - x509.getSerialNumber().toByteArray()), + Debug.toString(x509.getSerialNumber()), x509.getSigAlgName(), x509.getIssuerX500Principal().toString(), dateTimeFormat.format(x509.getNotBefore().toInstant()), @@ -496,8 +496,7 @@ private static String formatCertificate(Certificate certificate) { } Object[] certFields = { x509.getVersion(), - Utilities.toHexString( - x509.getSerialNumber().toByteArray()), + Debug.toString(x509.getSerialNumber()), x509.getSigAlgName(), x509.getIssuerX500Principal().toString(), dateTimeFormat.format(x509.getNotBefore().toInstant()), diff --git a/src/java.base/share/classes/sun/security/ssl/StatusResponseManager.java b/src/java.base/share/classes/sun/security/ssl/StatusResponseManager.java index c659cdeb5ba..65f373dc5c1 100644 --- a/src/java.base/share/classes/sun/security/ssl/StatusResponseManager.java +++ b/src/java.base/share/classes/sun/security/ssl/StatusResponseManager.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -53,6 +53,7 @@ import sun.security.provider.certpath.OCSPResponse; import sun.security.provider.certpath.ResponderId; import sun.security.util.Cache; +import sun.security.util.Debug; import sun.security.x509.PKIXExtensions; import sun.security.x509.SerialNumber; import sun.security.ssl.X509Authentication.X509Possession; @@ -419,8 +420,8 @@ private ResponseCacheEntry getFromCache(CertId cid, if (SSLLogger.isOn && SSLLogger.isOn("respmgr")) { SSLLogger.fine( - "Check cache for SN" + cid.getSerialNumber() + ": " + - (respEntry != null ? "HIT" : "MISS")); + "Check cache for SN" + Debug.toString(cid.getSerialNumber()) + + ": " + (respEntry != null ? "HIT" : "MISS")); } return respEntry; } @@ -516,7 +517,7 @@ public String toString() { StringBuilder sb = new StringBuilder("StatusInfo:"); sb.append("\n\tCert: ").append( this.cert.getSubjectX500Principal()); - sb.append("\n\tSerial: ").append(this.cert.getSerialNumber()); + sb.append("\n\tSerial: ").append(Debug.toString(this.cert.getSerialNumber())); sb.append("\n\tResponder: ").append(this.responder); sb.append("\n\tResponse data: ").append( this.responseData != null ? @@ -563,7 +564,7 @@ static class ResponseCacheEntry { } else { throw new IOException( "Unable to find SingleResponse for SN " + - cid.getSerialNumber()); + Debug.toString(cid.getSerialNumber())); } } else { nextUpdate = null; @@ -614,7 +615,7 @@ public StatusInfo call() { if (SSLLogger.isOn && SSLLogger.isOn("respmgr")) { SSLLogger.fine( "Starting fetch for SN " + - statInfo.cid.getSerialNumber()); + Debug.toString(statInfo.cid.getSerialNumber())); } try { ResponseCacheEntry cacheEntry; @@ -706,7 +707,7 @@ private void addToCache(CertId certId, ResponseCacheEntry entry) { if (SSLLogger.isOn && SSLLogger.isOn("respmgr")) { SSLLogger.fine( "Added response for SN " + - certId.getSerialNumber() + + Debug.toString(certId.getSerialNumber()) + " to cache"); } } diff --git a/src/java.base/share/classes/sun/security/ssl/X509TrustManagerImpl.java b/src/java.base/share/classes/sun/security/ssl/X509TrustManagerImpl.java index 681bb25904b..adb763f7924 100644 --- a/src/java.base/share/classes/sun/security/ssl/X509TrustManagerImpl.java +++ b/src/java.base/share/classes/sun/security/ssl/X509TrustManagerImpl.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -429,8 +429,17 @@ static void checkIdentity(SSLSession session, } if (!identifiable) { - checkIdentity(peerHost, - trustedChain[0], algorithm, chainsToPublicCA); + try { + checkIdentity(peerHost, + trustedChain[0], algorithm, chainsToPublicCA); + } catch(CertificateException ce) { + if (checkClientTrusted && "HTTPS".equalsIgnoreCase(algorithm)) { + throw new CertificateException("Endpoint Identification Algorithm " + + "HTTPS is not supported on the server side"); + } else { + throw ce; + } + } } } diff --git a/src/java.base/share/classes/sun/security/tools/keytool/Main.java b/src/java.base/share/classes/sun/security/tools/keytool/Main.java index 575367a405b..215b4a24c09 100644 --- a/src/java.base/share/classes/sun/security/tools/keytool/Main.java +++ b/src/java.base/share/classes/sun/security/tools/keytool/Main.java @@ -1125,7 +1125,6 @@ && isKeyStoreRelated(command) } } - KeyStore cakstore = buildTrustedCerts(); // -trustcacerts can be specified on -importcert, -printcert or -printcrl. // Reset it so that warnings on CA cert will remain for other command. if (command != IMPORTCERT && command != PRINTCERT @@ -1134,6 +1133,7 @@ && isKeyStoreRelated(command) } if (trustcacerts) { + KeyStore cakstore = buildTrustedCerts(); if (cakstore != null) { caks = cakstore; } else { diff --git a/src/java.base/share/classes/sun/security/util/Debug.java b/src/java.base/share/classes/sun/security/util/Debug.java index ef03423f322..5a197cd242f 100644 --- a/src/java.base/share/classes/sun/security/util/Debug.java +++ b/src/java.base/share/classes/sun/security/util/Debug.java @@ -398,6 +398,10 @@ public static String toString(byte[] b) { return HexFormat.ofDelimiter(":").formatHex(b); } + public static String toString(BigInteger b) { + return toString(b.toByteArray()); + } + // Holder class to break cyclic dependency seen during build private static class FormatHolder { private static final String PATTERN = "yyyy-MM-dd kk:mm:ss.SSS"; diff --git a/src/java.base/share/classes/sun/security/x509/SerialNumber.java b/src/java.base/share/classes/sun/security/x509/SerialNumber.java index 2264edfd4ab..2fea710a44b 100644 --- a/src/java.base/share/classes/sun/security/x509/SerialNumber.java +++ b/src/java.base/share/classes/sun/security/x509/SerialNumber.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2002, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2023, Oracle and/or its affiliates. All rights reserved. * 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,6 +27,7 @@ import java.io.IOException; import java.io.InputStream; import java.math.BigInteger; +import java.util.HexFormat; import sun.security.util.*; @@ -101,7 +102,7 @@ public SerialNumber(InputStream in) throws IOException { * Return the SerialNumber as user readable string. */ public String toString() { - return "SerialNumber: [" + Debug.toHexString(serialNum) + ']'; + return "SerialNumber: " + Debug.toString(serialNum); } /** diff --git a/src/java.base/share/legal/public_suffix.md b/src/java.base/share/legal/public_suffix.md index 2c8c9712787..6bd89c8d7cf 100644 --- a/src/java.base/share/legal/public_suffix.md +++ b/src/java.base/share/legal/public_suffix.md @@ -11,7 +11,7 @@ If you do not wish to use the Public Suffix List, you may remove the The Source Code of this file is available under the Mozilla Public License, v. 2.0 and is located at -https://raw.githubusercontent.com/publicsuffix/list/b5bf572c52988dbe9d865b8f090ea819024a9936/public_suffix_list.dat. +https://raw.githubusercontent.com/publicsuffix/list/1cbd6e71a9b83620b1d0b11e49d3d9ff48c27e22/public_suffix_list.dat. If a copy of the MPL was not distributed with this file, you can obtain one at https://mozilla.org/MPL/2.0/. diff --git a/src/java.base/unix/native/libjava/ProcessHandleImpl_unix.c b/src/java.base/unix/native/libjava/ProcessHandleImpl_unix.c index d53e88764c5..8b900dcf6f6 100644 --- a/src/java.base/unix/native/libjava/ProcessHandleImpl_unix.c +++ b/src/java.base/unix/native/libjava/ProcessHandleImpl_unix.c @@ -537,7 +537,7 @@ jint unix_getChildren(JNIEnv *env, jlong jpid, jlongArray jarray, * position integer as a filename. */ if ((dir = opendir("/proc")) == NULL) { - JNU_ThrowByNameWithLastError(env, + JNU_ThrowByNameWithMessageAndLastError(env, "java/lang/RuntimeException", "Unable to open /proc"); return -1; } diff --git a/src/java.base/unix/native/libjava/ProcessImpl_md.c b/src/java.base/unix/native/libjava/ProcessImpl_md.c index 640f449d3f0..d9a16dad422 100644 --- a/src/java.base/unix/native/libjava/ProcessImpl_md.c +++ b/src/java.base/unix/native/libjava/ProcessImpl_md.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 1995, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1995, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -562,8 +562,17 @@ spawnChild(JNIEnv *env, jobject process, ChildStuff *c, const char *helperpath) } offset = copystrings(buf, 0, &c->argv[0]); offset = copystrings(buf, offset, &c->envv[0]); - memcpy(buf+offset, c->pdir, sp.dirlen); - offset += sp.dirlen; + if (c->pdir != NULL) { + if (sp.dirlen > 0) { + memcpy(buf+offset, c->pdir, sp.dirlen); + offset += sp.dirlen; + } + } else { + if (sp.dirlen > 0) { + free(buf); + return -1; + } + } offset = copystrings(buf, offset, parentPathv); assert(offset == bufsize); diff --git a/src/java.base/unix/native/libnio/fs/UnixNativeDispatcher.c b/src/java.base/unix/native/libnio/fs/UnixNativeDispatcher.c index ea9eac66963..7bc14a0da97 100644 --- a/src/java.base/unix/native/libnio/fs/UnixNativeDispatcher.c +++ b/src/java.base/unix/native/libnio/fs/UnixNativeDispatcher.c @@ -703,14 +703,16 @@ Java_sun_nio_fs_UnixNativeDispatcher_stat0(JNIEnv* env, jclass this, if (my_statx_func != NULL) { // Prefer statx over stat64 on Linux if it's available + // statx is not allowed on the old Docker versions and returns EPERM, + // fallback to stat64 in this case RESTARTABLE(statx_wrapper(AT_FDCWD, path, flags, mask, &statx_buf), err); if (err == 0) { copy_statx_attributes(env, &statx_buf, attrs); - } else { + return; + } else if (errno != EPERM) { throwUnixException(env, errno); + return; } - // statx was available, so return now - return; } #endif RESTARTABLE(stat64(path, &buf), err); @@ -734,10 +736,12 @@ Java_sun_nio_fs_UnixNativeDispatcher_stat1(JNIEnv* env, jclass this, jlong pathA if (my_statx_func != NULL) { // Prefer statx over stat64 on Linux if it's available + // statx is not allowed on the old Docker versions and returns EPERM, + // fallback to stat64 in this case RESTARTABLE(statx_wrapper(AT_FDCWD, path, flags, mask, &statx_buf), err); if (err == 0) { return (jint)statx_buf.stx_mode; - } else { + } else if (errno != EPERM) { return 0; } } @@ -764,14 +768,16 @@ Java_sun_nio_fs_UnixNativeDispatcher_lstat0(JNIEnv* env, jclass this, if (my_statx_func != NULL) { // Prefer statx over stat64 on Linux if it's available + // statx is not allowed on the old Docker versions and returns EPERM, + // fallback to lstat64 in this case RESTARTABLE(statx_wrapper(AT_FDCWD, path, flags, mask, &statx_buf), err); if (err == 0) { copy_statx_attributes(env, &statx_buf, attrs); - } else { + return; + } else if (errno != EPERM) { throwUnixException(env, errno); + return; } - // statx was available, so return now - return; } #endif RESTARTABLE(lstat64(path, &buf), err); @@ -796,14 +802,16 @@ Java_sun_nio_fs_UnixNativeDispatcher_fstat(JNIEnv* env, jclass this, jint fd, if (my_statx_func != NULL) { // statx supports FD use via dirfd iff pathname is an empty string and the // AT_EMPTY_PATH flag is specified in flags + // statx is not allowed on the old Docker versions and returns EPERM, + // fallback to fstat64 in this case RESTARTABLE(statx_wrapper((int)fd, "", flags, mask, &statx_buf), err); if (err == 0) { copy_statx_attributes(env, &statx_buf, attrs); - } else { + return; + } else if (errno != EPERM) { throwUnixException(env, errno); + return; } - // statx was available, so return now - return; } #endif RESTARTABLE(fstat64((int)fd, &buf), err); @@ -831,14 +839,16 @@ Java_sun_nio_fs_UnixNativeDispatcher_fstatat0(JNIEnv* env, jclass this, jint dfd if (((int)flag & AT_SYMLINK_NOFOLLOW) > 0) { // flag set in java code flags |= AT_SYMLINK_NOFOLLOW; } + // statx is not allowed on the old Docker versions and returns EPERM, + // fallback to fstatat64 in this case RESTARTABLE(statx_wrapper((int)dfd, path, flags, mask, &statx_buf), err); if (err == 0) { copy_statx_attributes(env, &statx_buf, attrs); - } else { + return; + } else if (errno != EPERM) { throwUnixException(env, errno); + return; } - // statx was available, so return now - return; } #endif diff --git a/src/java.base/windows/classes/sun/nio/fs/WindowsFileSystemProvider.java b/src/java.base/windows/classes/sun/nio/fs/WindowsFileSystemProvider.java index 84658566873..964e338466d 100644 --- a/src/java.base/windows/classes/sun/nio/fs/WindowsFileSystemProvider.java +++ b/src/java.base/windows/classes/sun/nio/fs/WindowsFileSystemProvider.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2008, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2008, 2022, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -374,8 +374,19 @@ public void checkAccess(Path obj, AccessMode... modes) throws IOException { } } + // check file exists only + if (!(r || w || x)) { + file.checkRead(); + try { + WindowsFileAttributes.get(file, true); + return; + } catch (WindowsException exc) { + exc.rethrowAsIOException(file); + } + } + // special-case read access to avoid needing to determine effective - // access to file; default if modes not specified + // access to file if (!w && !x) { checkReadAccess(file); return; diff --git a/src/java.desktop/macosx/classes/com/apple/laf/AquaFileView.java b/src/java.desktop/macosx/classes/com/apple/laf/AquaFileView.java index d9f9a66e44c..4177e32f63d 100644 --- a/src/java.desktop/macosx/classes/com/apple/laf/AquaFileView.java +++ b/src/java.desktop/macosx/classes/com/apple/laf/AquaFileView.java @@ -25,8 +25,11 @@ package com.apple.laf; -import java.io.*; -import java.util.*; +import java.io.File; +import java.io.IOException; +import java.util.LinkedHashMap; +import java.util.LinkedList; +import java.util.Map; import java.util.Map.Entry; import javax.swing.Icon; @@ -34,6 +37,8 @@ import com.apple.laf.AquaUtils.RecyclableSingleton; +import static java.nio.charset.StandardCharsets.UTF_8; + @SuppressWarnings("serial") // JDK implementation class class AquaFileView extends FileView { private static final boolean DEBUG = false; @@ -111,11 +116,7 @@ static class FileInfo { FileInfo(final File file){ isDirectory = file.isDirectory(); absolutePath = file.getAbsolutePath(); - try { - pathBytes = absolutePath.getBytes("UTF-8"); - } catch (final UnsupportedEncodingException e) { - pathBytes = new byte[0]; - } + pathBytes = absolutePath.getBytes(UTF_8); } } diff --git a/src/java.desktop/macosx/classes/sun/lwawt/macosx/CDataTransferer.java b/src/java.desktop/macosx/classes/sun/lwawt/macosx/CDataTransferer.java index 795e4296c70..0ea70549d43 100644 --- a/src/java.desktop/macosx/classes/sun/lwawt/macosx/CDataTransferer.java +++ b/src/java.desktop/macosx/classes/sun/lwawt/macosx/CDataTransferer.java @@ -1,6 +1,5 @@ - /* - * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 2021, Oracle and/or its affiliates. All rights reserved. * 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,20 +25,27 @@ package sun.lwawt.macosx; -import java.awt.*; - -import java.io.*; -import java.net.URI; -import java.net.URISyntaxException; +import java.awt.Image; +import java.awt.datatransfer.DataFlavor; +import java.awt.datatransfer.Transferable; +import java.awt.datatransfer.UnsupportedFlavorException; +import java.io.ByteArrayOutputStream; +import java.io.IOException; import java.net.URL; import java.nio.charset.Charset; import java.text.Normalizer; import java.text.Normalizer.Form; -import java.util.*; -import java.util.regex.*; -import java.awt.datatransfer.*; -import java.nio.charset.StandardCharsets; -import sun.awt.datatransfer.*; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import sun.awt.datatransfer.DataTransferer; +import sun.awt.datatransfer.ToolkitThreadBlockedHandler; + +import static java.nio.charset.StandardCharsets.UTF_8; public class CDataTransferer extends DataTransferer { private static final Map predefinedClipboardNameMap; @@ -133,7 +139,7 @@ public Object translateBytes(byte[] bytes, DataFlavor flavor, String charset = Charset.defaultCharset().name(); if (transferable != null && transferable.isDataFlavorSupported(javaTextEncodingFlavor)) { try { - charset = new String((byte[]) transferable.getTransferData(javaTextEncodingFlavor), StandardCharsets.UTF_8); + charset = new String((byte[]) transferable.getTransferData(javaTextEncodingFlavor), UTF_8); } catch (UnsupportedFlavorException cannotHappen) { } } @@ -160,7 +166,8 @@ public Object translateBytes(byte[] bytes, DataFlavor flavor, // class by base method format = CF_STRING; } else if (format == CF_STRING) { - bytes = Normalizer.normalize(new String(bytes, "UTF8"), Form.NFC).getBytes("UTF8"); + String src = new String(bytes, UTF_8); + bytes = Normalizer.normalize(src, Form.NFC).getBytes(UTF_8); } return super.translateBytes(bytes, flavor, format, transferable); diff --git a/src/java.desktop/macosx/classes/sun/lwawt/macosx/CPlatformWindow.java b/src/java.desktop/macosx/classes/sun/lwawt/macosx/CPlatformWindow.java index 587612dafea..dd231e84f3a 100644 --- a/src/java.desktop/macosx/classes/sun/lwawt/macosx/CPlatformWindow.java +++ b/src/java.desktop/macosx/classes/sun/lwawt/macosx/CPlatformWindow.java @@ -42,6 +42,7 @@ import java.awt.Window; import java.awt.event.FocusEvent; import java.awt.event.WindowEvent; +import java.awt.event.WindowStateListener; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.lang.reflect.InvocationTargetException; @@ -964,6 +965,33 @@ public boolean isFullScreenMode() { return isFullScreenMode; } + private void waitForWindowState(int state) { + if (peer.getState() == state) { + return; + } + + Object lock = new Object(); + WindowStateListener wsl = new WindowStateListener() { + public void windowStateChanged(WindowEvent e) { + synchronized (lock) { + if (e.getNewState() == state) { + lock.notifyAll(); + } + } + } + }; + + target.addWindowStateListener(wsl); + if (peer.getState() != state) { + synchronized (lock) { + try { + lock.wait(); + } catch (InterruptedException ie) {} + } + } + target.removeWindowStateListener(wsl); + } + @Override public void setWindowState(int windowState) { if (peer == null || !peer.isVisible()) { @@ -985,6 +1013,7 @@ public void setWindowState(int windowState) { // let's return into the normal states first // the zoom call toggles between the normal and the max states unmaximize(); + waitForWindowState(Frame.NORMAL); } execute(CWrapper.NSWindow::miniaturize); break; @@ -992,6 +1021,8 @@ public void setWindowState(int windowState) { if (prevWindowState == Frame.ICONIFIED) { // let's return into the normal states first execute(CWrapper.NSWindow::deminiaturize); + waitForWindowState(Frame.NORMAL); + } maximize(); break; diff --git a/src/java.desktop/share/classes/com/sun/beans/introspect/MethodInfo.java b/src/java.desktop/share/classes/com/sun/beans/introspect/MethodInfo.java index 5216f4423d4..25c95988393 100644 --- a/src/java.desktop/share/classes/com/sun/beans/introspect/MethodInfo.java +++ b/src/java.desktop/share/classes/com/sun/beans/introspect/MethodInfo.java @@ -25,18 +25,35 @@ package com.sun.beans.introspect; +import java.io.Closeable; +import java.io.Externalizable; +import java.io.Serializable; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.Type; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; +import java.util.Set; import com.sun.beans.TypeResolver; import com.sun.beans.finder.MethodFinder; final class MethodInfo { + + // These are some common interfaces that we know a priori + // will not contain any bean property getters or setters. + static final Set> IGNORABLE_INTERFACES = Set.of( + AutoCloseable.class, + Cloneable.class, + Closeable.class, + Comparable.class, + Externalizable.class, + Serializable.class + ); + final Method method; final Class type; @@ -66,6 +83,8 @@ static Class resolve(Method method, Type type) { static List get(Class type) { List list = null; if (type != null) { + + // Add declared methods boolean inaccessible = !Modifier.isPublic(type.getModifiers()); for (Method method : type.getMethods()) { if (method.getDeclaringClass().equals(type)) { @@ -81,10 +100,19 @@ static List get(Class type) { } } if (method != null) { - if (list == null) { - list = new ArrayList<>(); - } - list.add(method); + (list = createIfNeeded(list)).add(method); + } + } + } + + // Add default methods inherited from interfaces + for (Class iface : type.getInterfaces()) { + if (IGNORABLE_INTERFACES.contains(iface)) { + continue; + } + for (Method method : iface.getMethods()) { + if (!Modifier.isAbstract(method.getModifiers())) { + (list = createIfNeeded(list)).add(method); } } } @@ -96,6 +124,10 @@ static List get(Class type) { return Collections.emptyList(); } + private static List createIfNeeded(List list) { + return list != null ? list : new ArrayList<>(); + } + /** * A comparator that defines a total order so that methods have the same * name and identical signatures appear next to each others. diff --git a/src/java.desktop/share/classes/com/sun/imageio/plugins/bmp/BMPMetadata.java b/src/java.desktop/share/classes/com/sun/imageio/plugins/bmp/BMPMetadata.java index 4510882ad4b..5e5a4a52d35 100644 --- a/src/java.desktop/share/classes/com/sun/imageio/plugins/bmp/BMPMetadata.java +++ b/src/java.desktop/share/classes/com/sun/imageio/plugins/bmp/BMPMetadata.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2021, Oracle and/or its affiliates. All rights reserved. * 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,19 +25,15 @@ package com.sun.imageio.plugins.bmp; -import java.io.UnsupportedEncodingException; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import javax.imageio.ImageTypeSpecifier; import javax.imageio.metadata.IIOMetadata; -import javax.imageio.metadata.IIOMetadataNode; -import javax.imageio.metadata.IIOMetadataFormat; import javax.imageio.metadata.IIOMetadataFormatImpl; -import org.w3c.dom.Node; -import com.sun.imageio.plugins.common.I18N; +import javax.imageio.metadata.IIOMetadataNode; +import com.sun.imageio.plugins.common.I18N; import com.sun.imageio.plugins.common.ImageUtil; +import org.w3c.dom.Node; + +import static java.nio.charset.StandardCharsets.ISO_8859_1; public class BMPMetadata extends IIOMetadata implements BMPConstants { public static final String nativeMetadataFormatName = @@ -114,11 +110,7 @@ public Node getAsTree(String formatName) { } private String toISO8859(byte[] data) { - try { - return new String(data, "ISO-8859-1"); - } catch (UnsupportedEncodingException e) { - return ""; - } + return new String(data, ISO_8859_1); } private Node getNativeTree() { diff --git a/src/java.desktop/share/classes/com/sun/imageio/plugins/gif/GIFImageMetadata.java b/src/java.desktop/share/classes/com/sun/imageio/plugins/gif/GIFImageMetadata.java index d865a58d431..061f3b1eaf0 100644 --- a/src/java.desktop/share/classes/com/sun/imageio/plugins/gif/GIFImageMetadata.java +++ b/src/java.desktop/share/classes/com/sun/imageio/plugins/gif/GIFImageMetadata.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2021, Oracle and/or its affiliates. All rights reserved. * 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,18 +25,17 @@ package com.sun.imageio.plugins.gif; -import java.io.UnsupportedEncodingException; -import java.util.ArrayList; import java.util.Iterator; import java.util.List; -import javax.imageio.ImageTypeSpecifier; + import javax.imageio.metadata.IIOInvalidTreeException; -import javax.imageio.metadata.IIOMetadata; -import javax.imageio.metadata.IIOMetadataNode; -import javax.imageio.metadata.IIOMetadataFormat; import javax.imageio.metadata.IIOMetadataFormatImpl; +import javax.imageio.metadata.IIOMetadataNode; + import org.w3c.dom.Node; +import static java.nio.charset.StandardCharsets.ISO_8859_1; + public class GIFImageMetadata extends GIFMetadata { // package scope @@ -132,11 +131,7 @@ public Node getAsTree(String formatName) { } private String toISO8859(byte[] data) { - try { - return new String(data, "ISO-8859-1"); - } catch (UnsupportedEncodingException e) { - return ""; - } + return new String(data, ISO_8859_1); } private Node getNativeTree() { @@ -384,12 +379,7 @@ public IIOMetadataNode getStandardTextNode() { while (commentIter.hasNext()) { byte[] comment = commentIter.next(); - String s = null; - try { - s = new String(comment, "ISO-8859-1"); - } catch (UnsupportedEncodingException e) { - throw new RuntimeException("Encoding ISO-8859-1 unknown!"); - } + String s = new String(comment, ISO_8859_1); node = new IIOMetadataNode("TextEntry"); node.setAttribute("value", s); diff --git a/src/java.desktop/share/classes/com/sun/imageio/plugins/gif/GIFWritableImageMetadata.java b/src/java.desktop/share/classes/com/sun/imageio/plugins/gif/GIFWritableImageMetadata.java index dc780602a90..8566d45f6a4 100644 --- a/src/java.desktop/share/classes/com/sun/imageio/plugins/gif/GIFWritableImageMetadata.java +++ b/src/java.desktop/share/classes/com/sun/imageio/plugins/gif/GIFWritableImageMetadata.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2021, Oracle and/or its affiliates. All rights reserved. * 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,19 +25,17 @@ package com.sun.imageio.plugins.gif; -import java.io.UnsupportedEncodingException; import java.nio.charset.Charset; import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import javax.imageio.ImageTypeSpecifier; + import javax.imageio.metadata.IIOInvalidTreeException; -import javax.imageio.metadata.IIOMetadata; -import javax.imageio.metadata.IIOMetadataNode; -import javax.imageio.metadata.IIOMetadataFormat; import javax.imageio.metadata.IIOMetadataFormatImpl; +import javax.imageio.metadata.IIOMetadataNode; + import org.w3c.dom.Node; +import static java.nio.charset.StandardCharsets.ISO_8859_1; + class GIFWritableImageMetadata extends GIFImageMetadata { // package scope @@ -95,11 +93,7 @@ public void reset() { } private byte[] fromISO8859(String data) { - try { - return data.getBytes("ISO-8859-1"); - } catch (UnsupportedEncodingException e) { - return "".getBytes(); - } + return data.getBytes(ISO_8859_1); } protected void mergeNativeTree(Node root) throws IIOInvalidTreeException { diff --git a/src/java.desktop/share/classes/com/sun/imageio/plugins/jpeg/COMMarkerSegment.java b/src/java.desktop/share/classes/com/sun/imageio/plugins/jpeg/COMMarkerSegment.java index d4a996ee3ee..f28e7b35658 100644 --- a/src/java.desktop/share/classes/com/sun/imageio/plugins/jpeg/COMMarkerSegment.java +++ b/src/java.desktop/share/classes/com/sun/imageio/plugins/jpeg/COMMarkerSegment.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 2021, Oracle and/or its affiliates. All rights reserved. * 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,15 +25,16 @@ package com.sun.imageio.plugins.jpeg; +import java.io.IOException; + +import javax.imageio.metadata.IIOInvalidTreeException; import javax.imageio.metadata.IIOMetadataNode; import javax.imageio.stream.ImageOutputStream; -import javax.imageio.metadata.IIOInvalidTreeException; - -import java.io.IOException; -import java.io.UnsupportedEncodingException; import org.w3c.dom.Node; +import static java.nio.charset.StandardCharsets.ISO_8859_1; + /** * A Comment marker segment. Retains an array of bytes representing the * comment data as it is read from the stream. If the marker segment is @@ -45,7 +46,6 @@ * byte array, again assuming the default local encoding. */ class COMMarkerSegment extends MarkerSegment { - private static final String ENCODING = "ISO-8859-1"; /** * Constructs a marker segment from the given buffer, which contains @@ -96,10 +96,7 @@ class COMMarkerSegment extends MarkerSegment { * consulted directly. */ String getComment() { - try { - return new String (data, ENCODING); - } catch (UnsupportedEncodingException e) {} // Won't happen - return null; + return new String(data, ISO_8859_1); } /** diff --git a/src/java.desktop/share/classes/com/sun/imageio/plugins/jpeg/JFIFMarkerSegment.java b/src/java.desktop/share/classes/com/sun/imageio/plugins/jpeg/JFIFMarkerSegment.java index 1de4f53a813..e944847ed57 100644 --- a/src/java.desktop/share/classes/com/sun/imageio/plugins/jpeg/JFIFMarkerSegment.java +++ b/src/java.desktop/share/classes/com/sun/imageio/plugins/jpeg/JFIFMarkerSegment.java @@ -25,40 +25,41 @@ package com.sun.imageio.plugins.jpeg; -import javax.imageio.IIOException; -import javax.imageio.IIOImage; -import javax.imageio.ImageTypeSpecifier; -import javax.imageio.ImageReader; -import javax.imageio.metadata.IIOInvalidTreeException; -import javax.imageio.metadata.IIOMetadataNode; -import javax.imageio.metadata.IIOMetadata; -import javax.imageio.stream.ImageInputStream; -import javax.imageio.stream.ImageOutputStream; -import javax.imageio.stream.MemoryCacheImageOutputStream; -import javax.imageio.event.IIOReadProgressListener; - import java.awt.Graphics; -import java.awt.color.ICC_Profile; -import java.awt.color.ICC_ColorSpace; import java.awt.color.ColorSpace; +import java.awt.color.ICC_ColorSpace; +import java.awt.color.ICC_Profile; +import java.awt.image.BufferedImage; import java.awt.image.ColorModel; -import java.awt.image.SampleModel; -import java.awt.image.IndexColorModel; import java.awt.image.ComponentColorModel; -import java.awt.image.BufferedImage; import java.awt.image.DataBuffer; import java.awt.image.DataBufferByte; +import java.awt.image.IndexColorModel; import java.awt.image.Raster; +import java.awt.image.SampleModel; import java.awt.image.WritableRaster; -import java.io.IOException; import java.io.ByteArrayOutputStream; -import java.util.List; +import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; +import java.util.List; +import javax.imageio.IIOException; +import javax.imageio.IIOImage; +import javax.imageio.ImageReader; +import javax.imageio.ImageTypeSpecifier; +import javax.imageio.event.IIOReadProgressListener; +import javax.imageio.metadata.IIOInvalidTreeException; +import javax.imageio.metadata.IIOMetadataNode; +import javax.imageio.stream.ImageInputStream; +import javax.imageio.stream.ImageOutputStream; +import javax.imageio.stream.MemoryCacheImageOutputStream; + +import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; -import org.w3c.dom.NamedNodeMap; + +import static java.nio.charset.StandardCharsets.US_ASCII; /** * A JFIF (JPEG File Interchange Format) APP0 (Application-Specific) @@ -1353,7 +1354,7 @@ static void writeICC(ICC_Profile profile, ImageOutputStream ios) ios.write(0xff); ios.write(JPEG.APP2); MarkerSegment.write2bytes(ios, segLength); - byte [] id = ID.getBytes("US-ASCII"); + byte[] id = ID.getBytes(US_ASCII); ios.write(id); ios.write(0); // Null-terminate the string ios.write(chunkNum++); diff --git a/src/java.desktop/share/classes/com/sun/imageio/plugins/png/PNGImageReader.java b/src/java.desktop/share/classes/com/sun/imageio/plugins/png/PNGImageReader.java index 8576419a4bf..f4d51b40eb9 100644 --- a/src/java.desktop/share/classes/com/sun/imageio/plugins/png/PNGImageReader.java +++ b/src/java.desktop/share/classes/com/sun/imageio/plugins/png/PNGImageReader.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2021, Oracle and/or its affiliates. All rights reserved. * 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,10 +36,11 @@ import java.awt.image.WritableRaster; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.EOFException; -import java.io.InputStream; import java.io.IOException; +import java.io.InputStream; import java.io.SequenceInputStream; import java.util.ArrayList; import java.util.Arrays; @@ -47,19 +48,23 @@ import java.util.Iterator; import java.util.zip.Inflater; import java.util.zip.InflaterInputStream; + import javax.imageio.IIOException; -import javax.imageio.ImageReader; import javax.imageio.ImageReadParam; +import javax.imageio.ImageReader; import javax.imageio.ImageTypeSpecifier; import javax.imageio.metadata.IIOMetadata; import javax.imageio.spi.ImageReaderSpi; import javax.imageio.stream.ImageInputStream; + import com.sun.imageio.plugins.common.InputStreamAdapter; import com.sun.imageio.plugins.common.ReaderUtil; import com.sun.imageio.plugins.common.SubImageInputStream; -import java.io.ByteArrayOutputStream; import sun.awt.image.ByteInterleavedRaster; +import static java.nio.charset.StandardCharsets.ISO_8859_1; +import static java.nio.charset.StandardCharsets.UTF_8; + class PNGImageDataEnumeration implements Enumeration { boolean firstTime = true; @@ -486,9 +491,9 @@ private void parse_iTXt_chunk(int chunkLength) throws IOException { stream.readFully(b); if (compressionFlag == 1) { // Decompress the text - text = new String(inflate(b), "UTF8"); + text = new String(inflate(b), UTF_8); } else { - text = new String(b, "UTF8"); + text = new String(b, UTF_8); } metadata.iTXt_text.add(text); @@ -589,7 +594,7 @@ private void parse_tEXt_chunk(int chunkLength) throws IOException { byte[] b = new byte[textLength]; stream.readFully(b); - metadata.tEXt_text.add(new String(b, "ISO-8859-1")); + metadata.tEXt_text.add(new String(b, ISO_8859_1)); // Check if the text chunk contains image creation time if (keyword.equals(PNGMetadata.tEXt_creationTimeKey)) { @@ -690,7 +695,7 @@ private void parse_zTXt_chunk(int chunkLength) throws IOException { byte[] b = new byte[textLength]; stream.readFully(b); - metadata.zTXt_text.add(new String(inflate(b), "ISO-8859-1")); + metadata.zTXt_text.add(new String(inflate(b), ISO_8859_1)); // Check if the text chunk contains image creation time if (keyword.equals(PNGMetadata.tEXt_creationTimeKey)) { diff --git a/src/java.desktop/share/classes/com/sun/imageio/plugins/png/PNGImageWriter.java b/src/java.desktop/share/classes/com/sun/imageio/plugins/png/PNGImageWriter.java index 9dc60991d13..449661b8c91 100644 --- a/src/java.desktop/share/classes/com/sun/imageio/plugins/png/PNGImageWriter.java +++ b/src/java.desktop/share/classes/com/sun/imageio/plugins/png/PNGImageWriter.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2021, Oracle and/or its affiliates. All rights reserved. * 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,15 +28,16 @@ import java.awt.Rectangle; import java.awt.image.IndexColorModel; import java.awt.image.Raster; -import java.awt.image.WritableRaster; import java.awt.image.RenderedImage; import java.awt.image.SampleModel; +import java.awt.image.WritableRaster; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Iterator; import java.util.Locale; import java.util.zip.Deflater; import java.util.zip.DeflaterOutputStream; + import javax.imageio.IIOException; import javax.imageio.IIOImage; import javax.imageio.ImageTypeSpecifier; @@ -47,6 +48,9 @@ import javax.imageio.stream.ImageOutputStream; import javax.imageio.stream.ImageOutputStreamImpl; +import static java.nio.charset.StandardCharsets.ISO_8859_1; +import static java.nio.charset.StandardCharsets.UTF_8; + final class CRC { private static final int[] crcTable = new int[256]; @@ -801,15 +805,14 @@ private void write_iTXt() throws IOException { cs.writeBytes(languageIter.next()); cs.writeByte(0); - - cs.write(translatedKeywordIter.next().getBytes("UTF8")); + cs.write(translatedKeywordIter.next().getBytes(UTF_8)); cs.writeByte(0); String text = textIter.next(); if (compressed) { - cs.write(deflate(text.getBytes("UTF8"))); + cs.write(deflate(text.getBytes(UTF_8))); } else { - cs.write(text.getBytes("UTF8")); + cs.write(text.getBytes(UTF_8)); } cs.finish(); } @@ -833,7 +836,7 @@ private void write_zTXt() throws IOException { cs.writeByte(compressionMethod); String text = textIter.next(); - cs.write(deflate(text.getBytes("ISO-8859-1"))); + cs.write(deflate(text.getBytes(ISO_8859_1))); cs.finish(); } } diff --git a/src/java.desktop/share/classes/com/sun/imageio/plugins/tiff/TIFFIFD.java b/src/java.desktop/share/classes/com/sun/imageio/plugins/tiff/TIFFIFD.java index 5c0334abbef..3d307e9ad1b 100644 --- a/src/java.desktop/share/classes/com/sun/imageio/plugins/tiff/TIFFIFD.java +++ b/src/java.desktop/share/classes/com/sun/imageio/plugins/tiff/TIFFIFD.java @@ -22,24 +22,27 @@ * or visit www.oracle.com if you need additional information or have any * questions. */ + package com.sun.imageio.plugins.tiff; import java.io.EOFException; import java.io.IOException; -import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Set; + import javax.imageio.IIOException; -import javax.imageio.stream.ImageInputStream; -import javax.imageio.stream.ImageOutputStream; import javax.imageio.plugins.tiff.BaselineTIFFTagSet; import javax.imageio.plugins.tiff.TIFFDirectory; import javax.imageio.plugins.tiff.TIFFField; import javax.imageio.plugins.tiff.TIFFTag; import javax.imageio.plugins.tiff.TIFFTagSet; +import javax.imageio.stream.ImageInputStream; +import javax.imageio.stream.ImageOutputStream; + +import static java.nio.charset.StandardCharsets.US_ASCII; public class TIFFIFD extends TIFFDirectory { private static final long MAX_SAMPLES_PER_PIXEL = 0xffff; @@ -283,8 +286,7 @@ private static int readFieldValue(ImageInputStream stream, if (inString) { // end of string String s = new String(bvalues, prevIndex, - index - prevIndex, - StandardCharsets.US_ASCII); + index - prevIndex, US_ASCII); v.add(s); inString = false; } diff --git a/src/java.desktop/share/classes/com/sun/imageio/plugins/tiff/TIFFImageWriter.java b/src/java.desktop/share/classes/com/sun/imageio/plugins/tiff/TIFFImageWriter.java index fdf9d49b467..1d2cff42311 100644 --- a/src/java.desktop/share/classes/com/sun/imageio/plugins/tiff/TIFFImageWriter.java +++ b/src/java.desktop/share/classes/com/sun/imageio/plugins/tiff/TIFFImageWriter.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -22,6 +22,7 @@ * or visit www.oracle.com if you need additional information or have any * questions. */ + package com.sun.imageio.plugins.tiff; import java.awt.Point; @@ -34,8 +35,8 @@ import java.awt.image.DataBuffer; import java.awt.image.DataBufferByte; import java.awt.image.IndexColorModel; -import java.awt.image.RenderedImage; import java.awt.image.Raster; +import java.awt.image.RenderedImage; import java.awt.image.SampleModel; import java.awt.image.WritableRaster; import java.io.EOFException; @@ -44,27 +45,30 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; + import javax.imageio.IIOException; import javax.imageio.IIOImage; +import javax.imageio.ImageTypeSpecifier; import javax.imageio.ImageWriteParam; import javax.imageio.ImageWriter; -import javax.imageio.ImageTypeSpecifier; import javax.imageio.metadata.IIOInvalidTreeException; import javax.imageio.metadata.IIOMetadata; import javax.imageio.metadata.IIOMetadataFormatImpl; -import javax.imageio.spi.ImageWriterSpi; -import javax.imageio.stream.ImageOutputStream; -import org.w3c.dom.Node; -import com.sun.imageio.plugins.common.ImageUtil; import javax.imageio.plugins.tiff.BaselineTIFFTagSet; import javax.imageio.plugins.tiff.ExifParentTIFFTagSet; import javax.imageio.plugins.tiff.ExifTIFFTagSet; import javax.imageio.plugins.tiff.TIFFField; import javax.imageio.plugins.tiff.TIFFTag; import javax.imageio.plugins.tiff.TIFFTagSet; +import javax.imageio.spi.ImageWriterSpi; +import javax.imageio.stream.ImageOutputStream; + +import com.sun.imageio.plugins.common.ImageUtil; import com.sun.imageio.plugins.common.SimpleRenderedImage; import com.sun.imageio.plugins.common.SingleTileRenderedImage; -import java.nio.charset.StandardCharsets; +import org.w3c.dom.Node; + +import static java.nio.charset.StandardCharsets.US_ASCII; public class TIFFImageWriter extends ImageWriter { @@ -1512,7 +1516,7 @@ void setupMetadata(ColorModel cm, SampleModel sm, (exifTags.getTag(ExifTIFFTagSet.TAG_EXIF_VERSION), TIFFTag.TIFF_UNDEFINED, 4, - ExifTIFFTagSet.EXIF_VERSION_2_2.getBytes(StandardCharsets.US_ASCII)); + ExifTIFFTagSet.EXIF_VERSION_2_2.getBytes(US_ASCII)); exifIFD.addTIFFField(f); } diff --git a/src/java.desktop/share/classes/com/sun/imageio/plugins/wbmp/WBMPMetadata.java b/src/java.desktop/share/classes/com/sun/imageio/plugins/wbmp/WBMPMetadata.java index 28ad467eadd..3a13bcca94f 100644 --- a/src/java.desktop/share/classes/com/sun/imageio/plugins/wbmp/WBMPMetadata.java +++ b/src/java.desktop/share/classes/com/sun/imageio/plugins/wbmp/WBMPMetadata.java @@ -25,19 +25,13 @@ package com.sun.imageio.plugins.wbmp; -import java.io.UnsupportedEncodingException; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import javax.imageio.ImageTypeSpecifier; import javax.imageio.metadata.IIOMetadata; -import javax.imageio.metadata.IIOMetadataNode; -import javax.imageio.metadata.IIOMetadataFormat; import javax.imageio.metadata.IIOMetadataFormatImpl; -import org.w3c.dom.Node; -import com.sun.imageio.plugins.common.I18N; +import javax.imageio.metadata.IIOMetadataNode; +import com.sun.imageio.plugins.common.I18N; import com.sun.imageio.plugins.common.ImageUtil; +import org.w3c.dom.Node; public class WBMPMetadata extends IIOMetadata { diff --git a/src/java.desktop/share/classes/com/sun/java/swing/plaf/gtk/GTKEngine.java b/src/java.desktop/share/classes/com/sun/java/swing/plaf/gtk/GTKEngine.java index 7bb07cce215..eb32ca630ff 100644 --- a/src/java.desktop/share/classes/com/sun/java/swing/plaf/gtk/GTKEngine.java +++ b/src/java.desktop/share/classes/com/sun/java/swing/plaf/gtk/GTKEngine.java @@ -337,7 +337,8 @@ static WidgetType getWidgetType(JComponent c, Region id) { return widgets[0]; } } else if (id == Region.ARROW_BUTTON) { - if (c.getParent() instanceof JScrollBar) { + if (c.getParent() instanceof JScrollBar + || c.getParent() instanceof JTabbedPane) { Integer prop = (Integer) c.getClientProperty("__arrow_direction__"); int dir = (prop != null) ? diff --git a/src/java.desktop/share/classes/com/sun/java/swing/plaf/gtk/Metacity.java b/src/java.desktop/share/classes/com/sun/java/swing/plaf/gtk/Metacity.java index 042ca187874..141184087d0 100644 --- a/src/java.desktop/share/classes/com/sun/java/swing/plaf/gtk/Metacity.java +++ b/src/java.desktop/share/classes/com/sun/java/swing/plaf/gtk/Metacity.java @@ -22,29 +22,76 @@ * or visit www.oracle.com if you need additional information or have any * questions. */ -package com.sun.java.swing.plaf.gtk; -import sun.swing.SwingUtilities2; -import com.sun.java.swing.plaf.gtk.GTKConstants.ArrowType; -import com.sun.java.swing.plaf.gtk.GTKConstants.ShadowType; +package com.sun.java.swing.plaf.gtk; +import java.awt.AlphaComposite; +import java.awt.BasicStroke; +import java.awt.Color; +import java.awt.Component; +import java.awt.Composite; +import java.awt.Container; +import java.awt.Dimension; +import java.awt.Font; +import java.awt.FontMetrics; +import java.awt.GradientPaint; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.Image; +import java.awt.Insets; +import java.awt.LayoutManager; +import java.awt.Point; +import java.awt.Rectangle; +import java.awt.Shape; +import java.awt.Stroke; +import java.awt.geom.AffineTransform; +import java.awt.geom.PathIterator; +import java.awt.geom.Rectangle2D; +import java.awt.geom.RectangularShape; +import java.awt.image.FilteredImageSource; +import java.awt.image.ImageProducer; +import java.awt.image.RGBImageFilter; +import java.io.BufferedInputStream; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.Reader; +import java.net.MalformedURLException; +import java.net.URL; +import java.security.AccessController; +import java.security.PrivilegedAction; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; +import java.util.NoSuchElementException; +import java.util.StringTokenizer; + +import javax.swing.Icon; +import javax.swing.ImageIcon; +import javax.swing.JButton; +import javax.swing.JComponent; +import javax.swing.JInternalFrame; import javax.swing.plaf.ColorUIResource; import javax.swing.plaf.basic.BasicInternalFrameTitlePane; -import javax.swing.plaf.synth.*; - -import java.awt.*; -import java.awt.geom.*; -import java.awt.image.*; -import java.io.*; -import java.net.*; -import java.security.*; -import java.util.*; +import javax.swing.plaf.synth.ColorType; +import javax.swing.plaf.synth.SynthConstants; +import javax.swing.plaf.synth.SynthContext; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; -import javax.swing.*; - -import javax.xml.parsers.*; +import com.sun.java.swing.plaf.gtk.GTKConstants.ArrowType; +import com.sun.java.swing.plaf.gtk.GTKConstants.ShadowType; +import org.w3c.dom.Document; +import org.w3c.dom.NamedNodeMap; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; import org.xml.sax.SAXException; -import org.w3c.dom.*; +import sun.swing.SwingUtilities2; + +import static java.nio.charset.StandardCharsets.ISO_8859_1; /** */ @@ -536,7 +583,8 @@ public Object run() { URL url = new URL(new File(userHome).toURI().toURL(), ".gconf/apps/metacity/general/%25gconf.xml"); // Pending: verify character encoding spec for gconf - Reader reader = new InputStreamReader(url.openStream(), "ISO-8859-1"); + Reader reader = new InputStreamReader(url.openStream(), + ISO_8859_1); char[] buf = new char[1024]; StringBuilder sb = new StringBuilder(); int n; diff --git a/src/java.desktop/share/classes/com/sun/media/sound/DLSSoundbank.java b/src/java.desktop/share/classes/com/sun/media/sound/DLSSoundbank.java index 55f937f0333..ebd6fba65b1 100644 --- a/src/java.desktop/share/classes/com/sun/media/sound/DLSSoundbank.java +++ b/src/java.desktop/share/classes/com/sun/media/sound/DLSSoundbank.java @@ -47,6 +47,8 @@ import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; +import static java.nio.charset.StandardCharsets.US_ASCII; + /** * A DLS Level 1 and Level 2 soundbank reader (from files/url/streams). * @@ -1147,7 +1149,7 @@ private void writeInfoStringChunk(RIFFWriter writer, return; RIFFWriter chunk = writer.writeChunk(name); chunk.writeString(value); - int len = value.getBytes("ascii").length; + int len = value.getBytes(US_ASCII).length; chunk.write(0); len++; if (len % 2 != 0) diff --git a/src/java.desktop/share/classes/com/sun/media/sound/RIFFReader.java b/src/java.desktop/share/classes/com/sun/media/sound/RIFFReader.java index 4266fbe8193..62789e4493f 100644 --- a/src/java.desktop/share/classes/com/sun/media/sound/RIFFReader.java +++ b/src/java.desktop/share/classes/com/sun/media/sound/RIFFReader.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -29,6 +29,8 @@ import java.io.IOException; import java.io.InputStream; +import static java.nio.charset.StandardCharsets.US_ASCII; + /** * Resource Interchange File Format (RIFF) stream decoder. * @@ -76,14 +78,14 @@ public RIFFReader(final InputStream stream) throws IOException { byte[] fourcc = new byte[4]; fourcc[0] = (byte) b; readFully(fourcc, 1, 3); - this.fourcc = new String(fourcc, "ascii"); + this.fourcc = new String(fourcc, US_ASCII); ckSize = readUnsignedInt(); avail = ckSize; if (getFormat().equals("RIFF") || getFormat().equals("LIST")) { byte[] format = new byte[4]; readFully(format); - this.riff_type = new String(format, "ascii"); + this.riff_type = new String(format, US_ASCII); } } @@ -227,10 +229,10 @@ public String readString(final int len) throws IOException { readFully(buff); for (int i = 0; i < buff.length; i++) { if (buff[i] == 0) { - return new String(buff, 0, i, "ascii"); + return new String(buff, 0, i, US_ASCII); } } - return new String(buff, "ascii"); + return new String(buff, US_ASCII); } // Read 8 bit signed integer from stream diff --git a/src/java.desktop/share/classes/com/sun/media/sound/RIFFWriter.java b/src/java.desktop/share/classes/com/sun/media/sound/RIFFWriter.java index f6943c9ef3c..6650e413613 100644 --- a/src/java.desktop/share/classes/com/sun/media/sound/RIFFWriter.java +++ b/src/java.desktop/share/classes/com/sun/media/sound/RIFFWriter.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 2021, Oracle and/or its affiliates. All rights reserved. * 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,8 @@ import java.io.OutputStream; import java.io.RandomAccessFile; +import static java.nio.charset.StandardCharsets.US_ASCII; + /** * Resource Interchange File Format (RIFF) stream encoder. * @@ -208,11 +210,11 @@ private RIFFWriter(RandomAccessWriter raf, String format, int chunktype) raf.write(0); if (chunktype == 0) - raf.write("RIFF".getBytes("ascii")); + raf.write("RIFF".getBytes(US_ASCII)); else if (chunktype == 1) - raf.write("LIST".getBytes("ascii")); + raf.write("LIST".getBytes(US_ASCII)); else - raf.write((format + " ").substring(0, 4).getBytes("ascii")); + raf.write((format + " ").substring(0, 4).getBytes(US_ASCII)); chunksizepointer = raf.getPointer(); this.chunktype = 2; @@ -220,8 +222,7 @@ else if (chunktype == 1) this.chunktype = chunktype; startpointer = raf.getPointer(); if (chunktype != 2) - raf.write((format + " ").substring(0, 4).getBytes("ascii")); - + raf.write((format + " ").substring(0, 4).getBytes(US_ASCII)); } public void seek(long pos) throws IOException { diff --git a/src/java.desktop/share/classes/com/sun/media/sound/SF2Soundbank.java b/src/java.desktop/share/classes/com/sun/media/sound/SF2Soundbank.java index 7d7cff36377..ccade6b1a2e 100644 --- a/src/java.desktop/share/classes/com/sun/media/sound/SF2Soundbank.java +++ b/src/java.desktop/share/classes/com/sun/media/sound/SF2Soundbank.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 2021, Oracle and/or its affiliates. All rights reserved. * 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,8 @@ import javax.sound.midi.Soundbank; import javax.sound.midi.SoundbankResource; +import static java.nio.charset.StandardCharsets.US_ASCII; + /** * A SoundFont 2.04 soundbank reader. * @@ -539,7 +541,7 @@ private void writeInfoStringChunk(RIFFWriter writer, String name, return; RIFFWriter chunk = writer.writeChunk(name); chunk.writeString(value); - int len = value.getBytes("ascii").length; + int len = value.getBytes(US_ASCII).length; chunk.write(0); len++; if (len % 2 != 0) diff --git a/src/java.desktop/share/classes/com/sun/media/sound/SoftMainMixer.java b/src/java.desktop/share/classes/com/sun/media/sound/SoftMainMixer.java index f603375f3b5..616332f105f 100644 --- a/src/java.desktop/share/classes/com/sun/media/sound/SoftMainMixer.java +++ b/src/java.desktop/share/classes/com/sun/media/sound/SoftMainMixer.java @@ -124,102 +124,126 @@ public double[] get(int instance, String name) { private void processSystemExclusiveMessage(byte[] data) { synchronized (synth.control_mutex) { activity(); - + if (data.length < 3 || (data[1] & 0xFF) != 0x7E && (data[1] & 0xFF) != 0x7F ) { + // Not enough data to determine SysEx type or SysEx type is not supported + return; + } // Universal Non-Real-Time SysEx if ((data[1] & 0xFF) == 0x7E) { int deviceID = data[2] & 0xFF; if (deviceID == 0x7F || deviceID == synth.getDeviceID()) { + if (data.length < 4) { + return; + } int subid1 = data[3] & 0xFF; int subid2; switch (subid1) { - case 0x08: // MIDI Tuning Standard - subid2 = data[4] & 0xFF; - switch (subid2) { - case 0x01: // BULK TUNING DUMP - { - // http://www.midi.org/about-midi/tuning.shtml - SoftTuning tuning = synth.getTuning(new Patch(0, - data[5] & 0xFF)); - tuning.load(data); - break; - } - case 0x04: // KEY-BASED TUNING DUMP - case 0x05: // SCALE/OCTAVE TUNING DUMP, 1 byte format - case 0x06: // SCALE/OCTAVE TUNING DUMP, 2 byte format - case 0x07: // SINGLE NOTE TUNING CHANGE (NON REAL-TIME) + case 0x08: // MIDI Tuning Standard + if (data.length < 5) { + break; + } + subid2 = data[4] & 0xFF; + switch (subid2) { + case 0x01: // BULK TUNING DUMP + { + if (data.length < 6) { + break; + } + // http://www.midi.org/about-midi/tuning.shtml + SoftTuning tuning = synth.getTuning(new Patch(0, + data[5] & 0xFF)); + tuning.load(data); + break; + } + case 0x04: // KEY-BASED TUNING DUMP + case 0x05: // SCALE/OCTAVE TUNING DUMP, 1 byte format + case 0x06: // SCALE/OCTAVE TUNING DUMP, 2 byte format + case 0x07: // SINGLE NOTE TUNING CHANGE (NON REAL-TIME) // (BANK) - { - // http://www.midi.org/about-midi/tuning_extens.shtml - SoftTuning tuning = synth.getTuning(new Patch( - data[5] & 0xFF, data[6] & 0xFF)); - tuning.load(data); - break; - } - case 0x08: // scale/octave tuning 1-byte form (Non + { + if (data.length < 7) { + break; + } + // http://www.midi.org/about-midi/tuning_extens.shtml + SoftTuning tuning = synth.getTuning(new Patch( + data[5] & 0xFF, data[6] & 0xFF)); + tuning.load(data); // Check inside! + break; + } + case 0x08: // scale/octave tuning 1-byte form (Non // Real-Time) - case 0x09: // scale/octave tuning 2-byte form (Non + case 0x09: // scale/octave tuning 2-byte form (Non // Real-Time) - { - // http://www.midi.org/about-midi/tuning-scale.shtml - SoftTuning tuning = new SoftTuning(data); - int channelmask = (data[5] & 0xFF) * 16384 - + (data[6] & 0xFF) * 128 + (data[7] & 0xFF); - SoftChannel[] channels = synth.channels; - for (int i = 0; i < channels.length; i++) - if ((channelmask & (1 << i)) != 0) - channels[i].tuning = tuning; - break; - } - default: - break; - } - break; - case 0x09: // General Midi Message - subid2 = data[4] & 0xFF; - switch (subid2) { - case 0x01: // General Midi 1 On - synth.setGeneralMidiMode(1); - reset(); - break; - case 0x02: // General Midi Off - synth.setGeneralMidiMode(0); - reset(); - break; - case 0x03: // General MidI Level 2 On - synth.setGeneralMidiMode(2); - reset(); - break; - default: - break; - } - break; - case 0x0A: // DLS Message - subid2 = data[4] & 0xFF; - switch (subid2) { - case 0x01: // DLS On - if (synth.getGeneralMidiMode() == 0) - synth.setGeneralMidiMode(1); - synth.voice_allocation_mode = 1; - reset(); - break; - case 0x02: // DLS Off - synth.setGeneralMidiMode(0); - synth.voice_allocation_mode = 0; - reset(); + { + if (data.length < 8) { + break; + } + // http://www.midi.org/about-midi/tuning-scale.shtml + SoftTuning tuning = new SoftTuning(data); + int channelmask = (data[5] & 0xFF) * 16384 + + (data[6] & 0xFF) * 128 + (data[7] & 0xFF); + SoftChannel[] channels = synth.channels; + for (int i = 0; i < channels.length; i++) + if ((channelmask & (1 << i)) != 0) + channels[i].tuning = tuning; + break; + } + default: + break; + } break; - case 0x03: // DLS Static Voice Allocation Off - synth.voice_allocation_mode = 0; + case 0x09: // General Midi Message + if (data.length < 5) { + break; + } + subid2 = data[4] & 0xFF; + switch (subid2) { + case 0x01: // General Midi 1 On + synth.setGeneralMidiMode(1); + reset(); + break; + case 0x02: // General Midi Off + synth.setGeneralMidiMode(0); + reset(); + break; + case 0x03: // General MidI Level 2 On + synth.setGeneralMidiMode(2); + reset(); + break; + default: + break; + } break; - case 0x04: // DLS Static Voice Allocation On - synth.voice_allocation_mode = 1; + case 0x0A: // DLS Message + if (data.length < 5) { + break; + } + subid2 = data[4] & 0xFF; + switch (subid2) { + case 0x01: // DLS On + if (synth.getGeneralMidiMode() == 0) + synth.setGeneralMidiMode(1); + synth.voice_allocation_mode = 1; + reset(); + break; + case 0x02: // DLS Off + synth.setGeneralMidiMode(0); + synth.voice_allocation_mode = 0; + reset(); + break; + case 0x03: // DLS Static Voice Allocation Off + synth.voice_allocation_mode = 0; + break; + case 0x04: // DLS Static Voice Allocation On + synth.voice_allocation_mode = 1; + break; + default: + break; + } break; + default: break; - } - break; - - default: - break; } } } @@ -228,197 +252,240 @@ private void processSystemExclusiveMessage(byte[] data) { if ((data[1] & 0xFF) == 0x7F) { int deviceID = data[2] & 0xFF; if (deviceID == 0x7F || deviceID == synth.getDeviceID()) { + if (data.length < 4) { + return; + } int subid1 = data[3] & 0xFF; int subid2; switch (subid1) { - case 0x04: // Device Control - - subid2 = data[4] & 0xFF; - switch (subid2) { - case 0x01: // Master Volume - case 0x02: // Master Balane - case 0x03: // Master fine tuning - case 0x04: // Master coarse tuning - int val = (data[5] & 0x7F) - + ((data[6] & 0x7F) * 128); - if (subid2 == 0x01) - setVolume(val); - else if (subid2 == 0x02) - setBalance(val); - else if (subid2 == 0x03) - setFineTuning(val); - else if (subid2 == 0x04) - setCoarseTuning(val); - break; - case 0x05: // Global Parameter Control - int ix = 5; - int slotPathLen = (data[ix++] & 0xFF); - int paramWidth = (data[ix++] & 0xFF); - int valueWidth = (data[ix++] & 0xFF); - int[] slotPath = new int[slotPathLen]; - for (int i = 0; i < slotPathLen; i++) { - int msb = (data[ix++] & 0xFF); - int lsb = (data[ix++] & 0xFF); - slotPath[i] = msb * 128 + lsb; + case 0x04: // Device Control + if (data.length < 5) { + break; } - int paramCount = (data.length - 1 - ix) - / (paramWidth + valueWidth); - long[] params = new long[paramCount]; - long[] values = new long[paramCount]; - for (int i = 0; i < paramCount; i++) { - values[i] = 0; - for (int j = 0; j < paramWidth; j++) - params[i] = params[i] * 128 - + (data[ix++] & 0xFF); - for (int j = 0; j < valueWidth; j++) - values[i] = values[i] * 128 - + (data[ix++] & 0xFF); - + subid2 = data[4] & 0xFF; + switch (subid2) { + case 0x01: // Master Volume + case 0x02: // Master Balane + case 0x03: // Master fine tuning + case 0x04: // Master coarse tuning + if (data.length < 7) { + break; + } + int val = (data[5] & 0x7F) + + ((data[6] & 0x7F) * 128); + if (subid2 == 0x01) + setVolume(val); + else if (subid2 == 0x02) + setBalance(val); + else if (subid2 == 0x03) + setFineTuning(val); + else if (subid2 == 0x04) + setCoarseTuning(val); + break; + case 0x05: // Global Parameter Control + if (data.length < 6) { + break; + } + int ix = 5; + int slotPathLen = (data[ix++] & 0xFF); + if (data.length < slotPathLen * 2 + 8) { + break; + } + int paramWidth = (data[ix++] & 0xFF); + int valueWidth = (data[ix++] & 0xFF); + int[] slotPath = new int[slotPathLen]; + for (int i = 0; i < slotPathLen; i++) { + int msb = (data[ix++] & 0xFF); + int lsb = (data[ix++] & 0xFF); + slotPath[i] = msb * 128 + lsb; + } + int paramCount = (data.length - 1 - ix) + / (paramWidth + valueWidth); + if (paramCount < 1) { + break; + } + long[] params = new long[paramCount]; + long[] values = new long[paramCount]; + for (int i = 0; i < paramCount; i++) { + values[i] = 0; + for (int j = 0; j < paramWidth; j++) + params[i] = params[i] * 128 + + (data[ix++] & 0xFF); + for (int j = 0; j < valueWidth; j++) + values[i] = values[i] * 128 + + (data[ix++] & 0xFF); + + } + globalParameterControlChange(slotPath, params, values); + break; + default: + break; } - globalParameterControlChange(slotPath, params, values); - break; - default: break; - } - break; - case 0x08: // MIDI Tuning Standard - subid2 = data[4] & 0xFF; - switch (subid2) { - case 0x02: // SINGLE NOTE TUNING CHANGE (REAL-TIME) - { - // http://www.midi.org/about-midi/tuning.shtml - SoftTuning tuning = synth.getTuning(new Patch(0, - data[5] & 0xFF)); - tuning.load(data); - SoftVoice[] voices = synth.getVoices(); - for (int i = 0; i < voices.length; i++) - if (voices[i].active) - if (voices[i].tuning == tuning) - voices[i].updateTuning(tuning); - break; - } - case 0x07: // SINGLE NOTE TUNING CHANGE (REAL-TIME) + case 0x08: // MIDI Tuning Standard + if (data.length < 5) { + break; + } + subid2 = data[4] & 0xFF; + switch (subid2) { + case 0x02: // SINGLE NOTE TUNING CHANGE (REAL-TIME) + { + // http://www.midi.org/about-midi/tuning.shtml + if (data.length < 6) { + break; + } + SoftTuning tuning = synth.getTuning(new Patch(0, + data[5] & 0xFF)); + tuning.load(data); + SoftVoice[] voices = synth.getVoices(); + for (int i = 0; i < voices.length; i++) + if (voices[i].active) + if (voices[i].tuning == tuning) + voices[i].updateTuning(tuning); + break; + } + case 0x07: // SINGLE NOTE TUNING CHANGE (REAL-TIME) // (BANK) - { - // http://www.midi.org/about-midi/tuning_extens.shtml - SoftTuning tuning = synth.getTuning(new Patch( - data[5] & 0xFF, data[6] & 0xFF)); - tuning.load(data); - SoftVoice[] voices = synth.getVoices(); - for (int i = 0; i < voices.length; i++) - if (voices[i].active) - if (voices[i].tuning == tuning) - voices[i].updateTuning(tuning); - break; - } - case 0x08: // scale/octave tuning 1-byte form + { + // http://www.midi.org/about-midi/tuning_extens.shtml + if (data.length < 7) { + break; + } + SoftTuning tuning = synth.getTuning(new Patch( + data[5] & 0xFF, data[6] & 0xFF)); + tuning.load(data); + SoftVoice[] voices = synth.getVoices(); + for (int i = 0; i < voices.length; i++) + if (voices[i].active) + if (voices[i].tuning == tuning) + voices[i].updateTuning(tuning); + break; + } + case 0x08: // scale/octave tuning 1-byte form //(Real-Time) - case 0x09: // scale/octave tuning 2-byte form + case 0x09: // scale/octave tuning 2-byte form // (Real-Time) - { - // http://www.midi.org/about-midi/tuning-scale.shtml - SoftTuning tuning = new SoftTuning(data); - int channelmask = (data[5] & 0xFF) * 16384 - + (data[6] & 0xFF) * 128 + (data[7] & 0xFF); - SoftChannel[] channels = synth.channels; - for (int i = 0; i < channels.length; i++) - if ((channelmask & (1 << i)) != 0) - channels[i].tuning = tuning; - SoftVoice[] voices = synth.getVoices(); - for (int i = 0; i < voices.length; i++) - if (voices[i].active) - if ((channelmask & (1 << (voices[i].channel))) != 0) - voices[i].updateTuning(tuning); - break; - } - default: - break; - } - break; - case 0x09: // Control Destination Settings - subid2 = data[4] & 0xFF; - switch (subid2) { - case 0x01: // Channel Pressure - { - int[] destinations = new int[(data.length - 7) / 2]; - int[] ranges = new int[(data.length - 7) / 2]; - int ix = 0; - for (int j = 6; j < data.length - 1; j += 2) { - destinations[ix] = data[j] & 0xFF; - ranges[ix] = data[j + 1] & 0xFF; - ix++; + { + // http://www.midi.org/about-midi/tuning-scale.shtml + if (data.length < 8) { + break; + } + SoftTuning tuning = new SoftTuning(data); + int channelmask = (data[5] & 0xFF) * 16384 + + (data[6] & 0xFF) * 128 + (data[7] & 0xFF); + SoftChannel[] channels = synth.channels; + for (int i = 0; i < channels.length; i++) + if ((channelmask & (1 << i)) != 0) + channels[i].tuning = tuning; + SoftVoice[] voices = synth.getVoices(); + for (int i = 0; i < voices.length; i++) + if (voices[i].active) + if ((channelmask & (1 << (voices[i].channel))) != 0) + voices[i].updateTuning(tuning); + break; + } + default: + break; } - int channel = data[5] & 0xFF; - SoftChannel softchannel = synth.channels[channel]; - softchannel.mapChannelPressureToDestination( - destinations, ranges); break; - } - case 0x02: // Poly Pressure - { - int[] destinations = new int[(data.length - 7) / 2]; - int[] ranges = new int[(data.length - 7) / 2]; - int ix = 0; - for (int j = 6; j < data.length - 1; j += 2) { - destinations[ix] = data[j] & 0xFF; - ranges[ix] = data[j + 1] & 0xFF; - ix++; + case 0x09: // Control Destination Settings + if (data.length < 5) { + break; } - int channel = data[5] & 0xFF; - SoftChannel softchannel = synth.channels[channel]; - softchannel.mapPolyPressureToDestination( - destinations, ranges); - break; - } - case 0x03: // Control Change - { - int[] destinations = new int[(data.length - 7) / 2]; - int[] ranges = new int[(data.length - 7) / 2]; - int ix = 0; - for (int j = 7; j < data.length - 1; j += 2) { - destinations[ix] = data[j] & 0xFF; - ranges[ix] = data[j + 1] & 0xFF; - ix++; + subid2 = data[4] & 0xFF; + switch (subid2) { + case 0x01: // Channel Pressure + { + if (data.length < 8) { + break; + } + int[] destinations = new int[(data.length - 6) / 2]; + int[] ranges = new int[(data.length - 6) / 2]; + int ix = 0; + for (int j = 6; j < data.length - 1; j += 2) { + destinations[ix] = data[j] & 0xFF; + ranges[ix] = data[j + 1] & 0xFF; + ix++; + } + int channel = data[5] & 0xFF; + SoftChannel softchannel = synth.channels[channel]; + softchannel.mapChannelPressureToDestination( + destinations, ranges); + break; + } + case 0x02: // Poly Pressure + { + if (data.length < 8) { + break; + } + int[] destinations = new int[(data.length - 6) / 2]; + int[] ranges = new int[(data.length - 6) / 2]; + int ix = 0; + for (int j = 6; j < data.length - 1; j += 2) { + destinations[ix] = data[j] & 0xFF; + ranges[ix] = data[j + 1] & 0xFF; + ix++; + } + int channel = data[5] & 0xFF; + SoftChannel softchannel = synth.channels[channel]; + softchannel.mapPolyPressureToDestination( + destinations, ranges); + break; + } + case 0x03: // Control Change + { + if (data.length < 8) { + break; + } + int[] destinations = new int[(data.length - 7) / 2]; + int[] ranges = new int[(data.length - 7) / 2]; + int ix = 0; + for (int j = 7; j < data.length - 1; j += 2) { + destinations[ix] = data[j] & 0xFF; + ranges[ix] = data[j + 1] & 0xFF; + ix++; + } + int channel = data[5] & 0xFF; + SoftChannel softchannel = synth.channels[channel]; + int control = data[6] & 0xFF; + softchannel.mapControlToDestination(control, + destinations, ranges); + break; + } + default: + break; } - int channel = data[5] & 0xFF; - SoftChannel softchannel = synth.channels[channel]; - int control = data[6] & 0xFF; - softchannel.mapControlToDestination(control, - destinations, ranges); - break; - } - default: break; - } - break; - case 0x0A: // Key Based Instrument Control - { - subid2 = data[4] & 0xFF; - switch (subid2) { - case 0x01: // Basic Message - int channel = data[5] & 0xFF; - int keynumber = data[6] & 0xFF; - SoftChannel softchannel = synth.channels[channel]; - for (int j = 7; j < data.length - 1; j += 2) { - int controlnumber = data[j] & 0xFF; - int controlvalue = data[j + 1] & 0xFF; - softchannel.controlChangePerNote(keynumber, - controlnumber, controlvalue); + case 0x0A: // Key Based Instrument Control + { + if (data.length < 8 || (data[4] & 0xFF) != 0x01) { + break; + } + subid2 = data[4] & 0xFF; + switch (subid2) { + case 0x01: // Basic Message + int channel = data[5] & 0xFF; + int keynumber = data[6] & 0xFF; + SoftChannel softchannel = synth.channels[channel]; + for (int j = 7; j < data.length - 1; j += 2) { + int controlnumber = data[j] & 0xFF; + int controlvalue = data[j + 1] & 0xFF; + softchannel.controlChangePerNote(keynumber, + controlnumber, controlvalue); + } + break; + default: + break; } break; + } default: break; - } - break; - } - default: - break; } } } - } } diff --git a/src/java.desktop/share/classes/com/sun/media/sound/SoftSynthesizer.java b/src/java.desktop/share/classes/com/sun/media/sound/SoftSynthesizer.java index 70b8b622df9..1c8ff218077 100644 --- a/src/java.desktop/share/classes/com/sun/media/sound/SoftSynthesizer.java +++ b/src/java.desktop/share/classes/com/sun/media/sound/SoftSynthesizer.java @@ -289,12 +289,11 @@ private boolean loadInstruments(List instruments) { c.current_instrument = null; c.current_director = null; } - for (Instrument instrument : instruments) { + for (ModelInstrument instrument : instruments) { String pat = patchToString(instrument.getPatch()); - SoftInstrument softins - = new SoftInstrument((ModelInstrument) instrument); + SoftInstrument softins = new SoftInstrument(instrument); inslist.put(pat, softins); - loadedlist.put(pat, (ModelInstrument) instrument); + loadedlist.put(pat, instrument); } } diff --git a/src/java.desktop/share/classes/com/sun/media/sound/SoftTuning.java b/src/java.desktop/share/classes/com/sun/media/sound/SoftTuning.java index 9ed8871f523..b951ffacc23 100644 --- a/src/java.desktop/share/classes/com/sun/media/sound/SoftTuning.java +++ b/src/java.desktop/share/classes/com/sun/media/sound/SoftTuning.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 2021, Oracle and/or its affiliates. All rights reserved. * 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,11 +25,12 @@ package com.sun.media.sound; -import java.io.UnsupportedEncodingException; import java.util.Arrays; import javax.sound.midi.Patch; +import static java.nio.charset.StandardCharsets.US_ASCII; + /** * A tuning program container, for use with MIDI Tuning. * See: http://www.midi.org @@ -88,10 +89,21 @@ private boolean checksumOK2(byte[] data) { */ public void load(byte[] data) { // Universal Non-Real-Time / Real-Time SysEx + if (data.length < 2) { + return; + } + if ((data[1] & 0xFF) == 0x7E || (data[1] & 0xFF) == 0x7F) { + if (data.length < 4) { + return; + } + int subid1 = data[3] & 0xFF; switch (subid1) { case 0x08: // MIDI Tuning Standard + if (data.length < 5) { + break; + } int subid2 = data[4] & 0xFF; switch (subid2) { case 0x01: // BULK TUNING DUMP (NON-REAL-TIME) @@ -99,12 +111,11 @@ public void load(byte[] data) { // http://www.midi.org/about-midi/tuning.shtml //if (!checksumOK2(data)) // break; - try { - name = new String(data, 6, 16, "ascii"); - } catch (UnsupportedEncodingException e) { - name = null; - } int r = 22; + if (data.length < 128 * 3 + r) { + break; + } + name = new String(data, 6, 16, US_ASCII); for (int i = 0; i < 128; i++) { int xx = data[r++] & 0xFF; int yy = data[r++] & 0xFF; @@ -118,8 +129,14 @@ public void load(byte[] data) { case 0x02: // SINGLE NOTE TUNING CHANGE (REAL-TIME) { // http://www.midi.org/about-midi/tuning.shtml + if (data.length < 7) { + break; + } int ll = data[6] & 0xFF; int r = 7; + if (data.length < ll * 4 + r) { + break; + } for (int i = 0; i < ll; i++) { int kk = data[r++] & 0xFF; int xx = data[r++] & 0xFF; @@ -135,11 +152,10 @@ public void load(byte[] data) { // http://www.midi.org/about-midi/tuning_extens.shtml if (!checksumOK(data)) break; - try { - name = new String(data, 7, 16, "ascii"); - } catch (UnsupportedEncodingException e) { - name = null; + if (data.length < 407) { + break; } + name = new String(data, 7, 16, US_ASCII); int r = 23; for (int i = 0; i < 128; i++) { int xx = data[r++] & 0xFF; @@ -156,11 +172,10 @@ public void load(byte[] data) { // http://www.midi.org/about-midi/tuning_extens.shtml if (!checksumOK(data)) break; - try { - name = new String(data, 7, 16, "ascii"); - } catch (UnsupportedEncodingException e) { - name = null; + if (data.length < 35) { + break; } + name = new String(data, 7, 16, US_ASCII); int[] octave_tuning = new int[12]; for (int i = 0; i < 12; i++) octave_tuning[i] = (data[i + 23] & 0xFF) - 64; @@ -174,11 +189,10 @@ public void load(byte[] data) { // http://www.midi.org/about-midi/tuning_extens.shtml if (!checksumOK(data)) break; - try { - name = new String(data, 7, 16, "ascii"); - } catch (UnsupportedEncodingException e) { - name = null; + if (data.length < 47) { + break; } + name = new String(data, 7, 16, US_ASCII); double[] octave_tuning = new double[12]; for (int i = 0; i < 12; i++) { int v = (data[i * 2 + 23] & 0xFF) * 128 @@ -192,7 +206,13 @@ public void load(byte[] data) { case 0x07: // SINGLE NOTE TUNING CHANGE (NON // REAL-TIME/REAL-TIME) (BANK) // http://www.midi.org/about-midi/tuning_extens.shtml + if (data.length < 8) { + break; + } int ll = data[7] & 0xFF; + if (data.length < ll * 4 + 8) { + break; + } int r = 8; for (int i = 0; i < ll; i++) { int kk = data[r++] & 0xFF; @@ -208,6 +228,9 @@ public void load(byte[] data) { // Real-Time/REAL-TIME) { // http://www.midi.org/about-midi/tuning-scale.shtml + if (data.length < 20) { + break; + } int[] octave_tuning = new int[12]; for (int i = 0; i < 12; i++) octave_tuning[i] = (data[i + 8] & 0xFF) - 64; @@ -219,6 +242,9 @@ public void load(byte[] data) { // Real-Time/REAL-TIME) { // http://www.midi.org/about-midi/tuning-scale.shtml + if (data.length < 32) { + break; + } double[] octave_tuning = new double[12]; for (int i = 0; i < 12; i++) { int v = (data[i * 2 + 8] & 0xFF) * 128 diff --git a/src/java.desktop/share/classes/javax/swing/JFormattedTextField.java b/src/java.desktop/share/classes/javax/swing/JFormattedTextField.java index 9ee465e3744..51516f79c99 100644 --- a/src/java.desktop/share/classes/javax/swing/JFormattedTextField.java +++ b/src/java.desktop/share/classes/javax/swing/JFormattedTextField.java @@ -868,11 +868,11 @@ private AbstractFormatterFactory getDefaultFormatterFactory(Object type) { return new DefaultFormatterFactory(new DateFormatter()); } if (type instanceof Number) { - AbstractFormatter displayFormatter = new NumberFormatter(); - ((NumberFormatter)displayFormatter).setValueClass(type.getClass()); - AbstractFormatter editFormatter = new NumberFormatter( + NumberFormatter displayFormatter = new NumberFormatter(); + displayFormatter.setValueClass(type.getClass()); + NumberFormatter editFormatter = new NumberFormatter( new DecimalFormat("#.#")); - ((NumberFormatter)editFormatter).setValueClass(type.getClass()); + editFormatter.setValueClass(type.getClass()); return new DefaultFormatterFactory(displayFormatter, displayFormatter,editFormatter); diff --git a/src/java.desktop/share/classes/javax/swing/JRootPane.java b/src/java.desktop/share/classes/javax/swing/JRootPane.java index e3eb7ac75a4..dcc6d6bb4ef 100644 --- a/src/java.desktop/share/classes/javax/swing/JRootPane.java +++ b/src/java.desktop/share/classes/javax/swing/JRootPane.java @@ -24,18 +24,13 @@ */ package javax.swing; -import java.applet.Applet; import java.awt.*; -import java.awt.event.*; import java.beans.*; import java.security.AccessController; import javax.accessibility.*; import javax.swing.plaf.RootPaneUI; -import java.util.Vector; import java.io.Serializable; -import javax.swing.border.*; -import sun.awt.AWTAccessor; import sun.security.action.GetBooleanAction; @@ -511,10 +506,10 @@ public void addLayoutComponent(Component comp, Object constraints) { * @return the default glassPane */ protected Component createGlassPane() { - JComponent c = new JPanel(); + JPanel c = new JPanel(); c.setName(this.getName()+".glassPane"); c.setVisible(false); - ((JPanel)c).setOpaque(false); + c.setOpaque(false); return c; } diff --git a/src/java.desktop/share/classes/javax/swing/JTree.java b/src/java.desktop/share/classes/javax/swing/JTree.java index f1ba5b9d3d3..e48c1b29333 100644 --- a/src/java.desktop/share/classes/javax/swing/JTree.java +++ b/src/java.desktop/share/classes/javax/swing/JTree.java @@ -2033,7 +2033,7 @@ public Enumeration getExpandedDescendants(TreePath parent) { Enumeration toggledPaths = expandedState.keys(); Vector elements = null; TreePath path; - Object value; + Boolean value; if(toggledPaths != null) { while(toggledPaths.hasMoreElements()) { @@ -2042,8 +2042,7 @@ public Enumeration getExpandedDescendants(TreePath parent) { // Add the path if it is expanded, a descendant of parent, // and it is visible (all parents expanded). This is rather // expensive! - if(path != parent && value != null && - ((Boolean)value).booleanValue() && + if (path != parent && value != null && value && parent.isDescendant(path) && isVisible(path)) { if (elements == null) { elements = new Vector(); @@ -2081,11 +2080,11 @@ public boolean isExpanded(TreePath path) { if(path == null) return false; - Object value; + Boolean value; do{ value = expandedState.get(path); - if(value == null || !((Boolean)value).booleanValue()) + if (value == null || !value) return false; } while( (path=path.getParentPath())!=null ); @@ -2109,7 +2108,7 @@ public boolean isExpanded(int row) { if(path != null) { Boolean value = expandedState.get(path); - return (value != null && value.booleanValue()); + return (value != null && value); } } return false; @@ -3729,9 +3728,9 @@ protected void setExpandedState(TreePath path, boolean state) { } if(!state) { // collapse last path. - Object cValue = expandedState.get(path); + Boolean cValue = expandedState.get(path); - if(cValue != null && ((Boolean)cValue).booleanValue()) { + if (cValue != null && cValue) { try { fireTreeWillCollapse(path); } @@ -3753,9 +3752,9 @@ protected void setExpandedState(TreePath path, boolean state) { } else { // Expand last path. - Object cValue = expandedState.get(path); + Boolean cValue = expandedState.get(path); - if(cValue == null || !((Boolean)cValue).booleanValue()) { + if (cValue == null || !cValue) { try { fireTreeWillExpand(path); } diff --git a/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicComboPopup.java b/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicComboPopup.java index 050f27e72b4..197f3238bb1 100644 --- a/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicComboPopup.java +++ b/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicComboPopup.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -921,7 +921,7 @@ public void mousePressed(MouseEvent e) { if (e.getSource() == list) { return; } - if (!SwingUtilities.isLeftMouseButton(e) || !comboBox.isEnabled()) + if (!SwingUtilities.isLeftMouseButton(e) || !comboBox.isEnabled() || !comboBox.isShowing()) return; if ( comboBox.isEditable() ) { diff --git a/src/java.desktop/share/classes/javax/swing/plaf/synth/SynthParser.java b/src/java.desktop/share/classes/javax/swing/plaf/synth/SynthParser.java index e053fe3d54c..4c212bc1ad8 100644 --- a/src/java.desktop/share/classes/javax/swing/plaf/synth/SynthParser.java +++ b/src/java.desktop/share/classes/javax/swing/plaf/synth/SynthParser.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -1024,10 +1024,7 @@ private void addPainterOrMerge(List painters, Stri painter, direction); - for (Object infoObject: painters) { - ParsedSynthStyle.PainterInfo info; - info = (ParsedSynthStyle.PainterInfo) infoObject; - + for (ParsedSynthStyle.PainterInfo info: painters) { if (painterInfo.equalsPainter(info)) { info.addPainter(painter); return; diff --git a/src/java.desktop/share/classes/javax/swing/text/html/AccessibleHTML.java b/src/java.desktop/share/classes/javax/swing/text/html/AccessibleHTML.java index cc7f3d9c290..db3fe75136e 100644 --- a/src/java.desktop/share/classes/javax/swing/text/html/AccessibleHTML.java +++ b/src/java.desktop/share/classes/javax/swing/text/html/AccessibleHTML.java @@ -317,14 +317,12 @@ public AccessibleContext getAccessibleContext() { */ public AccessibleStateSet getAccessibleStateSet() { AccessibleStateSet states = new AccessibleStateSet(); - Component comp = getTextComponent(); + JTextComponent comp = getTextComponent(); if (comp.isEnabled()) { states.add(AccessibleState.ENABLED); } - if (comp instanceof JTextComponent && - ((JTextComponent)comp).isEditable()) { - + if (comp.isEditable()) { states.add(AccessibleState.EDITABLE); states.add(AccessibleState.FOCUSABLE); } @@ -742,11 +740,9 @@ private ElementInfo getElementInfoAt(ElementInfo elementInfo, Point p) { * @see AccessibleStateSet */ public boolean isFocusTraversable() { - Component comp = getTextComponent(); - if (comp instanceof JTextComponent) { - if (((JTextComponent)comp).isEditable()) { - return true; - } + JTextComponent comp = getTextComponent(); + if (comp != null && comp.isEditable()) { + return true; } return false; } @@ -763,8 +759,8 @@ public void requestFocus() { return; } - Component comp = getTextComponent(); - if (comp instanceof JTextComponent) { + JTextComponent comp = getTextComponent(); + if (comp != null) { comp.requestFocusInWindow(); @@ -772,7 +768,7 @@ public void requestFocus() { if (elementInfo.validateIfNecessary()) { // set the caret position to the start of this component Element elem = elementInfo.getElement(); - ((JTextComponent)comp).setCaretPosition(elem.getStartOffset()); + comp.setCaretPosition(elem.getStartOffset()); // fire a AccessibleState.FOCUSED property change event AccessibleContext ac = editor.getAccessibleContext(); diff --git a/src/java.desktop/share/classes/javax/swing/text/html/HTMLDocument.java b/src/java.desktop/share/classes/javax/swing/text/html/HTMLDocument.java index 89a335f19ba..c5ae88a9493 100644 --- a/src/java.desktop/share/classes/javax/swing/text/html/HTMLDocument.java +++ b/src/java.desktop/share/classes/javax/swing/text/html/HTMLDocument.java @@ -4225,7 +4225,7 @@ private void foundInsertTag(boolean isBlockTag) { try { if (offset == 0 || !getText(offset - 1, 1).equals("\n")) { // Need to insert a newline. - AttributeSet newAttrs = null; + SimpleAttributeSet newAttrs = null; boolean joinP = true; if (offset != 0) { @@ -4259,9 +4259,8 @@ private void foundInsertTag(boolean isBlockTag) { // sure and set the name (otherwise it will be // inherited). newAttrs = new SimpleAttributeSet(); - ((SimpleAttributeSet)newAttrs).addAttribute - (StyleConstants.NameAttribute, - HTML.Tag.CONTENT); + newAttrs.addAttribute(StyleConstants.NameAttribute, + HTML.Tag.CONTENT); } ElementSpec es = new ElementSpec(newAttrs, ElementSpec.ContentType, NEWLINE, 0, diff --git a/src/java.desktop/share/classes/javax/swing/text/html/HTMLEditorKit.java b/src/java.desktop/share/classes/javax/swing/text/html/HTMLEditorKit.java index 4ceb656a0a3..5e9c49cdd10 100644 --- a/src/java.desktop/share/classes/javax/swing/text/html/HTMLEditorKit.java +++ b/src/java.desktop/share/classes/javax/swing/text/html/HTMLEditorKit.java @@ -22,27 +22,82 @@ * or visit www.oracle.com if you need additional information or have any * questions. */ -package javax.swing.text.html; -import sun.awt.AppContext; +package javax.swing.text.html; -import java.awt.*; -import java.awt.event.*; -import java.io.*; +import java.awt.Color; +import java.awt.Component; +import java.awt.Container; +import java.awt.Cursor; +import java.awt.Graphics; +import java.awt.Insets; +import java.awt.Point; +import java.awt.Rectangle; +import java.awt.Shape; +import java.awt.event.ActionEvent; +import java.awt.event.ComponentEvent; +import java.awt.event.ComponentListener; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; +import java.awt.event.MouseMotionListener; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.Reader; +import java.io.Serializable; +import java.io.StringReader; +import java.io.Writer; +import java.lang.ref.Reference; +import java.lang.ref.WeakReference; import java.net.MalformedURLException; import java.net.URL; -import javax.swing.text.*; -import javax.swing.*; -import javax.swing.event.*; -import javax.swing.plaf.TextUI; -import java.util.*; -import javax.accessibility.*; -import java.lang.ref.*; import java.security.AccessController; import java.security.PrivilegedAction; +import java.util.Enumeration; + +import javax.accessibility.Accessible; +import javax.accessibility.AccessibleAction; +import javax.accessibility.AccessibleContext; +import javax.swing.Action; +import javax.swing.JEditorPane; +import javax.swing.JViewport; +import javax.swing.SizeRequirements; +import javax.swing.SwingUtilities; +import javax.swing.event.CaretEvent; +import javax.swing.event.CaretListener; +import javax.swing.event.HyperlinkEvent; +import javax.swing.plaf.TextUI; +import javax.swing.text.AbstractDocument; +import javax.swing.text.AttributeSet; +import javax.swing.text.BadLocationException; +import javax.swing.text.BoxView; +import javax.swing.text.ComponentView; +import javax.swing.text.DefaultHighlighter; +import javax.swing.text.Document; +import javax.swing.text.EditorKit; +import javax.swing.text.Element; +import javax.swing.text.ElementIterator; +import javax.swing.text.Highlighter; +import javax.swing.text.IconView; +import javax.swing.text.JTextComponent; +import javax.swing.text.LabelView; +import javax.swing.text.MutableAttributeSet; +import javax.swing.text.Position; +import javax.swing.text.StyleConstants; +import javax.swing.text.StyledDocument; +import javax.swing.text.StyledEditorKit; +import javax.swing.text.TextAction; +import javax.swing.text.View; +import javax.swing.text.ViewFactory; import javax.swing.text.html.parser.ParserDelegator; + +import sun.awt.AppContext; import sun.swing.SwingAccessor; +import static java.nio.charset.StandardCharsets.ISO_8859_1; + /** * The Swing JEditorPane text component supports different kinds * of content via a plug-in mechanism called an EditorKit. Because @@ -404,7 +459,7 @@ public StyleSheet getStyleSheet() { try { InputStream is = HTMLEditorKit.getResourceAsStream(DEFAULT_CSS); Reader r = new BufferedReader( - new InputStreamReader(is, "ISO-8859-1")); + new InputStreamReader(is, ISO_8859_1)); defaultStyles.loadRules(r, null); r.close(); } catch (Throwable e) { @@ -793,13 +848,12 @@ private String getMapHREF(JEditorPane html, HTMLDocument hdoc, Rectangle bounds; TextUI ui = html.getUI(); try { - Shape lBounds = ui.modelToView(html, offset, + Rectangle lBounds = ui.modelToView(html, offset, Position.Bias.Forward); - Shape rBounds = ui.modelToView(html, offset + 1, + Rectangle rBounds = ui.modelToView(html, offset + 1, Position.Bias.Backward); - bounds = lBounds.getBounds(); - bounds.add((rBounds instanceof Rectangle) ? - (Rectangle)rBounds : rBounds.getBounds()); + bounds = lBounds; + bounds.add(rBounds); } catch (BadLocationException ble) { bounds = null; } @@ -830,18 +884,14 @@ private boolean doesElementContainLocation(JEditorPane editor, if (e != null && offset > 0 && e.getStartOffset() == offset) { try { TextUI ui = editor.getUI(); - Shape s1 = ui.modelToView(editor, offset, - Position.Bias.Forward); - if (s1 == null) { + Rectangle r1 = ui.modelToView(editor, offset, + Position.Bias.Forward); + if (r1 == null) { return false; } - Rectangle r1 = (s1 instanceof Rectangle) ? (Rectangle)s1 : - s1.getBounds(); - Shape s2 = ui.modelToView(editor, e.getEndOffset(), - Position.Bias.Backward); - if (s2 != null) { - Rectangle r2 = (s2 instanceof Rectangle) ? (Rectangle)s2 : - s2.getBounds(); + Rectangle r2 = ui.modelToView(editor, e.getEndOffset(), + Position.Bias.Backward); + if (r2 != null) { r1.add(r2); } return r1.contains(x, y); @@ -1466,9 +1516,9 @@ public void setParent(View parent) { //if parent == null unregister component listener if (parent == null) { if (cachedViewPort != null) { - Object cachedObject; + JViewport cachedObject; if ((cachedObject = cachedViewPort.get()) != null) { - ((JComponent)cachedObject).removeComponentListener(this); + cachedObject.removeComponentListener(this); } cachedViewPort = null; } diff --git a/src/java.desktop/share/classes/javax/swing/text/html/default.css b/src/java.desktop/share/classes/javax/swing/text/html/default.css index eb37a12b6d8..32f54231f46 100644 --- a/src/java.desktop/share/classes/javax/swing/text/html/default.css +++ b/src/java.desktop/share/classes/javax/swing/text/html/default.css @@ -102,7 +102,7 @@ dd {margin-left-ltr: 40; margin-bottom: 0} dd p {margin-left: 0; - margin-rigth: 0; + margin-right: 0; margin-top: 0; margin-bottom: 0} diff --git a/src/java.desktop/share/classes/javax/swing/text/rtf/RTFGenerator.java b/src/java.desktop/share/classes/javax/swing/text/rtf/RTFGenerator.java index 7a98fd80ef1..f60f4ade3e8 100644 --- a/src/java.desktop/share/classes/javax/swing/text/rtf/RTFGenerator.java +++ b/src/java.desktop/share/classes/javax/swing/text/rtf/RTFGenerator.java @@ -27,7 +27,6 @@ import java.lang.*; import java.util.*; import java.awt.Color; -import java.awt.Font; import java.io.OutputStream; import java.io.IOException; @@ -516,13 +515,13 @@ void updateSectionAttributes(MutableAttributeSet current, { if (emitStyleChanges) { Object oldStyle = current.getAttribute("sectionStyle"); - Object newStyle = findStyleNumber(newAttributes, Constants.STSection); + Integer newStyle = findStyleNumber(newAttributes, Constants.STSection); if (oldStyle != newStyle) { if (oldStyle != null) { resetSectionAttributes(current); } if (newStyle != null) { - writeControlWord("ds", ((Integer)newStyle).intValue()); + writeControlWord("ds", newStyle); current.addAttribute("sectionStyle", newStyle); } else { current.removeAttribute("sectionStyle"); @@ -555,8 +554,8 @@ void updateParagraphAttributes(MutableAttributeSet current, boolean emitStyleChanges) throws IOException { - Object parm; - Object oldStyle, newStyle; + Object oldStyle; + Integer newStyle; /* The only way to get rid of tabs or styles is with the \pard keyword, emitted by resetParagraphAttributes(). Ideally we should avoid @@ -588,7 +587,7 @@ emitted by resetParagraphAttributes(). Ideally we should avoid } if (oldStyle != newStyle && newStyle != null) { - writeControlWord("s", ((Integer)newStyle).intValue()); + writeControlWord("s", newStyle); current.addAttribute("paragraphStyle", newStyle); } @@ -707,14 +706,14 @@ void updateCharacterAttributes(MutableAttributeSet current, if (updateStyleChanges) { Object oldStyle = current.getAttribute("characterStyle"); - Object newStyle = findStyleNumber(newAttributes, + Integer newStyle = findStyleNumber(newAttributes, Constants.STCharacter); if (oldStyle != newStyle) { if (oldStyle != null) { resetCharacterAttributes(current); } if (newStyle != null) { - writeControlWord("cs", ((Integer)newStyle).intValue()); + writeControlWord("cs", newStyle.intValue()); current.addAttribute("characterStyle", newStyle); } else { current.removeAttribute("characterStyle"); diff --git a/src/java.desktop/share/classes/javax/swing/text/rtf/RTFReader.java b/src/java.desktop/share/classes/javax/swing/text/rtf/RTFReader.java index e870bb49b04..7e9d8f17342 100644 --- a/src/java.desktop/share/classes/javax/swing/text/rtf/RTFReader.java +++ b/src/java.desktop/share/classes/javax/swing/text/rtf/RTFReader.java @@ -22,12 +22,16 @@ * or visit www.oracle.com if you need additional information or have any * questions. */ + package javax.swing.text.rtf; -import java.lang.*; -import java.util.*; -import java.io.*; import java.awt.Color; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.io.StreamTokenizer; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.Charset; @@ -35,7 +39,24 @@ import java.nio.charset.CodingErrorAction; import java.security.AccessController; import java.security.PrivilegedAction; -import javax.swing.text.*; +import java.util.Dictionary; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Hashtable; +import java.util.Map; +import java.util.Set; +import java.util.Vector; + +import javax.swing.text.AttributeSet; +import javax.swing.text.BadLocationException; +import javax.swing.text.MutableAttributeSet; +import javax.swing.text.SimpleAttributeSet; +import javax.swing.text.Style; +import javax.swing.text.StyleConstants; +import javax.swing.text.StyleContext; +import javax.swing.text.StyledDocument; +import javax.swing.text.TabStop; import static java.nio.charset.StandardCharsets.ISO_8859_1; @@ -648,7 +669,7 @@ static char[] readCharset(InputStream strm) char[] values = new char[256]; int i; StreamTokenizer in = new StreamTokenizer(new BufferedReader( - new InputStreamReader(strm, "ISO-8859-1"))); + new InputStreamReader(strm, ISO_8859_1))); in.eolIsSignificant(false); in.commentChar('#'); diff --git a/src/java.desktop/share/classes/sun/awt/FontDescriptor.java b/src/java.desktop/share/classes/sun/awt/FontDescriptor.java index e934c27a4c1..046ecce16da 100644 --- a/src/java.desktop/share/classes/sun/awt/FontDescriptor.java +++ b/src/java.desktop/share/classes/sun/awt/FontDescriptor.java @@ -22,14 +22,17 @@ * or visit www.oracle.com if you need additional information or have any * questions. */ + package sun.awt; import java.io.ByteArrayOutputStream; -import java.io.OutputStreamWriter; import java.io.IOException; +import java.io.OutputStreamWriter; import java.nio.charset.Charset; import java.nio.charset.CharsetEncoder; -import java.nio.charset.StandardCharsets; + +import static java.nio.charset.StandardCharsets.UTF_16BE; +import static java.nio.charset.StandardCharsets.UTF_16LE; public class FontDescriptor implements Cloneable { @@ -109,9 +112,8 @@ public String toString() { public boolean useUnicode() { if (useUnicode && unicodeEncoder == null) { try { - this.unicodeEncoder = isLE? - StandardCharsets.UTF_16LE.newEncoder(): - StandardCharsets.UTF_16BE.newEncoder(); + this.unicodeEncoder = isLE ? UTF_16LE.newEncoder(): + UTF_16BE.newEncoder(); } catch (IllegalArgumentException x) {} } return useUnicode; diff --git a/src/java.desktop/share/classes/sun/awt/SunToolkit.java b/src/java.desktop/share/classes/sun/awt/SunToolkit.java index 6f501acc346..b6c8a7183ce 100644 --- a/src/java.desktop/share/classes/sun/awt/SunToolkit.java +++ b/src/java.desktop/share/classes/sun/awt/SunToolkit.java @@ -1805,8 +1805,8 @@ public static RenderingHints getDesktopFontHints() { if (useSystemAAFontSettings()) { Toolkit tk = Toolkit.getDefaultToolkit(); if (tk instanceof SunToolkit) { - Object map = ((SunToolkit)tk).getDesktopAAHints(); - return (RenderingHints)map; + RenderingHints map = ((SunToolkit)tk).getDesktopAAHints(); + return map; } else { /* Headless Toolkit */ return null; } diff --git a/src/java.desktop/share/classes/sun/awt/datatransfer/DataTransferer.java b/src/java.desktop/share/classes/sun/awt/datatransfer/DataTransferer.java index 84677785cc6..0898a3ddcec 100644 --- a/src/java.desktop/share/classes/sun/awt/datatransfer/DataTransferer.java +++ b/src/java.desktop/share/classes/sun/awt/datatransfer/DataTransferer.java @@ -29,77 +29,78 @@ import java.awt.Graphics; import java.awt.Image; import java.awt.Toolkit; - import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.FlavorMap; import java.awt.datatransfer.FlavorTable; import java.awt.datatransfer.Transferable; import java.awt.datatransfer.UnsupportedFlavorException; - +import java.awt.image.BufferedImage; +import java.awt.image.ColorModel; +import java.awt.image.ImageObserver; +import java.awt.image.RenderedImage; +import java.awt.image.WritableRaster; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; +import java.io.FilePermission; +import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; -import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Reader; import java.io.SequenceInputStream; import java.io.StringReader; - +import java.lang.reflect.Constructor; +import java.lang.reflect.Modifier; import java.net.URI; import java.net.URISyntaxException; - import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.Charset; import java.nio.charset.CharsetEncoder; import java.nio.charset.IllegalCharsetNameException; -import java.nio.charset.StandardCharsets; import java.nio.charset.UnsupportedCharsetException; - -import java.lang.reflect.Constructor; -import java.lang.reflect.Modifier; - import java.security.AccessController; import java.security.PrivilegedAction; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import java.security.ProtectionDomain; - -import java.util.*; - -import sun.datatransfer.DataFlavorUtil; - -import sun.awt.AppContext; -import sun.awt.ComponentFactory; -import sun.awt.SunToolkit; - -import java.awt.image.BufferedImage; -import java.awt.image.ImageObserver; -import java.awt.image.RenderedImage; -import java.awt.image.WritableRaster; -import java.awt.image.ColorModel; +import java.util.AbstractMap; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.SortedMap; +import java.util.Stack; +import java.util.TreeMap; +import java.util.stream.Stream; import javax.imageio.ImageIO; -import javax.imageio.ImageReader; import javax.imageio.ImageReadParam; -import javax.imageio.ImageWriter; +import javax.imageio.ImageReader; import javax.imageio.ImageTypeSpecifier; - +import javax.imageio.ImageWriter; import javax.imageio.spi.ImageWriterSpi; - import javax.imageio.stream.ImageInputStream; import javax.imageio.stream.ImageOutputStream; +import sun.awt.AppContext; +import sun.awt.ComponentFactory; +import sun.awt.SunToolkit; import sun.awt.image.ImageRepresentation; import sun.awt.image.ToolkitImage; +import sun.datatransfer.DataFlavorUtil; -import java.io.FilePermission; -import java.util.stream.Stream; - +import static java.nio.charset.StandardCharsets.UTF_8; /** * Provides a set of functions to be shared among the DataFlavor class and @@ -550,7 +551,7 @@ protected String getBestCharsetForTextFormat(Long lFormat, try { byte[] charsetNameBytes = (byte[])localeTransferable .getTransferData(javaTextEncodingFlavor); - charset = new String(charsetNameBytes, StandardCharsets.UTF_8); + charset = new String(charsetNameBytes, UTF_8); } catch (UnsupportedFlavorException cannotHappen) { } } else { diff --git a/src/java.desktop/share/classes/sun/font/Type1Font.java b/src/java.desktop/share/classes/sun/font/Type1Font.java index f640c6f09a9..1c9cf9f8e88 100644 --- a/src/java.desktop/share/classes/sun/font/Type1Font.java +++ b/src/java.desktop/share/classes/sun/font/Type1Font.java @@ -25,23 +25,23 @@ package sun.font; -import java.lang.ref.WeakReference; import java.awt.FontFormatException; import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; -import java.io.UnsupportedEncodingException; import java.lang.ref.WeakReference; +import java.nio.BufferUnderflowException; import java.nio.ByteBuffer; import java.nio.ByteOrder; -import java.nio.BufferUnderflowException; import java.nio.channels.ClosedChannelException; import java.nio.channels.FileChannel; +import java.util.HashMap; +import java.util.HashSet; + import sun.java2d.Disposer; import sun.java2d.DisposerRecord; -import java.util.HashSet; -import java.util.HashMap; -import java.awt.Font; + +import static java.nio.charset.StandardCharsets.US_ASCII; /* * Adobe Technical Note 5040 details the format of PFB files. @@ -609,11 +609,7 @@ private String getSimpleToken(ByteBuffer bb) { byte[] nameBytes = new byte[pos2-pos1-1]; bb.position(pos1); bb.get(nameBytes); - try { - return new String(nameBytes, "US-ASCII"); - } catch (UnsupportedEncodingException e) { - return new String(nameBytes); - } + return new String(nameBytes, US_ASCII); } private String getString(ByteBuffer bb) { @@ -623,11 +619,7 @@ private String getString(ByteBuffer bb) { byte[] nameBytes = new byte[pos2-pos1-1]; bb.position(pos1); bb.get(nameBytes); - try { - return new String(nameBytes, "US-ASCII"); - } catch (UnsupportedEncodingException e) { - return new String(nameBytes); - } + return new String(nameBytes, US_ASCII); } diff --git a/src/java.desktop/share/classes/sun/java2d/Disposer.java b/src/java.desktop/share/classes/sun/java2d/Disposer.java index 1581364331f..6f359f7f87a 100644 --- a/src/java.desktop/share/classes/sun/java2d/Disposer.java +++ b/src/java.desktop/share/classes/sun/java2d/Disposer.java @@ -142,8 +142,8 @@ synchronized void add(Object target, DisposerRecord rec) { public void run() { while (true) { try { - Object obj = queue.remove(); - ((Reference)obj).clear(); + Reference obj = queue.remove(); + obj.clear(); DisposerRecord rec = records.remove(obj); rec.dispose(); obj = null; @@ -200,7 +200,7 @@ public static void pollRemove() { if (pollingQueue) { return; } - Object obj; + Reference obj; pollingQueue = true; int freed = 0; int deferred = 0; @@ -208,7 +208,7 @@ public static void pollRemove() { while ( freed < 10000 && deferred < 100 && (obj = queue.poll()) != null ) { freed++; - ((Reference)obj).clear(); + obj.clear(); DisposerRecord rec = records.remove(obj); if (rec instanceof PollDisposable) { rec.dispose(); diff --git a/src/java.desktop/share/classes/sun/print/PageableDoc.java b/src/java.desktop/share/classes/sun/print/PageableDoc.java index 859f40e853e..ef829d5bfbb 100644 --- a/src/java.desktop/share/classes/sun/print/PageableDoc.java +++ b/src/java.desktop/share/classes/sun/print/PageableDoc.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2021, Oracle and/or its affiliates. All rights reserved. * 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,12 +25,10 @@ package sun.print; +import java.awt.print.Pageable; import java.io.IOException; import java.io.InputStream; import java.io.Reader; -import java.io.UnsupportedEncodingException; - -import java.awt.print.Pageable; import javax.print.Doc; import javax.print.DocFlavor; @@ -57,9 +55,7 @@ public Object getPrintData() throws IOException { return pageable; } - public Reader getReaderForText() - throws UnsupportedEncodingException, IOException { - + public Reader getReaderForText() throws IOException { return null; } diff --git a/src/java.desktop/share/native/libjavajpeg/imageioJPEG.c b/src/java.desktop/share/native/libjavajpeg/imageioJPEG.c index 8a74a6d711e..5cf8d13a91d 100644 --- a/src/java.desktop/share/native/libjavajpeg/imageioJPEG.c +++ b/src/java.desktop/share/native/libjavajpeg/imageioJPEG.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -666,8 +666,6 @@ static void imageio_reset(JNIEnv *env, static void imageio_dispose(j_common_ptr info) { if (info != NULL) { - free(info->err); - info->err = NULL; if (info->is_decompressor) { j_decompress_ptr dinfo = (j_decompress_ptr) info; free(dinfo->src); @@ -678,6 +676,8 @@ static void imageio_dispose(j_common_ptr info) { cinfo->dest = NULL; } jpeg_destroy(info); + free(info->err); + info->err = NULL; free(info); } } diff --git a/src/java.desktop/unix/classes/sun/awt/X11/XAtom.java b/src/java.desktop/unix/classes/sun/awt/X11/XAtom.java index 117e3865241..78b8844f061 100644 --- a/src/java.desktop/unix/classes/sun/awt/X11/XAtom.java +++ b/src/java.desktop/unix/classes/sun/awt/X11/XAtom.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 2021, Oracle and/or its affiliates. All rights reserved. * 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,9 +58,13 @@ * @since 1.5 */ -import jdk.internal.misc.Unsafe; import java.util.HashMap; +import jdk.internal.misc.Unsafe; + +import static java.nio.charset.StandardCharsets.ISO_8859_1; +import static java.nio.charset.StandardCharsets.UTF_8; + public final class XAtom { // Order of lock: XAWTLock -> XAtom.class @@ -308,12 +312,7 @@ public void setPropertyUTF8(long window, String str) { throw new IllegalStateException("Atom should be initialized"); } checkWindow(window); - byte[] bdata = null; - try { - bdata = str.getBytes("UTF-8"); - } catch (java.io.UnsupportedEncodingException uee) { - uee.printStackTrace(); - } + byte[] bdata = str.getBytes(UTF_8); if (bdata != null) { setAtomData(window, XA_UTF8_STRING.atom, bdata); } @@ -327,12 +326,7 @@ public void setProperty8(long window, String str) { throw new IllegalStateException("Atom should be initialized"); } checkWindow(window); - byte[] bdata = null; - try { - bdata = str.getBytes("ISO-8859-1"); - } catch (java.io.UnsupportedEncodingException uee) { - uee.printStackTrace(); - } + byte[] bdata = str.getBytes(ISO_8859_1); if (bdata != null) { setAtomData(window, XA_STRING, bdata); } diff --git a/src/java.desktop/unix/classes/sun/awt/X11/XNETProtocol.java b/src/java.desktop/unix/classes/sun/awt/X11/XNETProtocol.java index 2d82ace9845..81c31b277fb 100644 --- a/src/java.desktop/unix/classes/sun/awt/X11/XNETProtocol.java +++ b/src/java.desktop/unix/classes/sun/awt/X11/XNETProtocol.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,14 +23,17 @@ * questions. */ - package sun.awt.X11; import java.awt.Frame; +import java.nio.charset.Charset; import sun.awt.IconInfo; import sun.util.logging.PlatformLogger; +import static java.nio.charset.StandardCharsets.US_ASCII; +import static java.nio.charset.StandardCharsets.UTF_8; + final class XNETProtocol extends XProtocol implements XStateProtocol, XLayerProtocol { private static final PlatformLogger log = PlatformLogger.getLogger("sun.awt.X11.XNETProtocol"); @@ -382,22 +385,18 @@ public String getWMName() { * mandates UTF8_STRING for _NET_WM_NAME but at least sawfish-1.0 * still uses STRING. (mmm, moving targets...). */ - String charSet = "UTF8"; + Charset charSet = UTF_8; byte[] net_wm_name = XA_NET_WM_NAME.getByteArrayProperty(NetWindow, XA_UTF8_STRING.getAtom()); if (net_wm_name == null) { net_wm_name = XA_NET_WM_NAME.getByteArrayProperty(NetWindow, XAtom.XA_STRING); - charSet = "ASCII"; + charSet = US_ASCII; } if (net_wm_name == null) { return null; } - try { - net_wm_name_cache = new String(net_wm_name, charSet); - return net_wm_name_cache; - } catch (java.io.UnsupportedEncodingException uex) { - return null; - } + net_wm_name_cache = new String(net_wm_name, charSet); + return net_wm_name_cache; } /** diff --git a/src/java.desktop/unix/classes/sun/awt/X11/XWindowPeer.java b/src/java.desktop/unix/classes/sun/awt/X11/XWindowPeer.java index 2587db4459a..f44084af6e3 100644 --- a/src/java.desktop/unix/classes/sun/awt/X11/XWindowPeer.java +++ b/src/java.desktop/unix/classes/sun/awt/X11/XWindowPeer.java @@ -47,7 +47,6 @@ import java.awt.event.WindowEvent; import java.awt.peer.ComponentPeer; import java.awt.peer.WindowPeer; -import java.io.UnsupportedEncodingException; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.ArrayList; @@ -67,6 +66,8 @@ import sun.java2d.pipe.Region; import sun.util.logging.PlatformLogger; +import static java.nio.charset.StandardCharsets.UTF_8; + class XWindowPeer extends XPanelPeer implements WindowPeer, DisplayChangedListener { @@ -1358,12 +1359,7 @@ public String run() { } messageBuilder.append('"'); messageBuilder.append('\0'); - final byte[] message; - try { - message = messageBuilder.toString().getBytes("UTF-8"); - } catch (UnsupportedEncodingException cannotHappen) { - return; - } + final byte[] message = messageBuilder.toString().getBytes(UTF_8); XClientMessageEvent req = null; diff --git a/src/java.desktop/unix/classes/sun/awt/XSettings.java b/src/java.desktop/unix/classes/sun/awt/XSettings.java index 812255ea850..4136a350172 100644 --- a/src/java.desktop/unix/classes/sun/awt/XSettings.java +++ b/src/java.desktop/unix/classes/sun/awt/XSettings.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2004, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2021, Oracle and/or its affiliates. All rights reserved. * 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,12 +26,10 @@ package sun.awt; import java.awt.Color; - -import java.io.UnsupportedEncodingException; - import java.util.HashMap; import java.util.Map; +import static java.nio.charset.StandardCharsets.UTF_8; /** * Per-screen XSETTINGS. @@ -198,12 +196,7 @@ private String getString(int len) { needBytes(len); - String str = null; - try { - str = new String(data, idx, len, "UTF-8"); - } catch (UnsupportedEncodingException e) { - // XXX: cannot happen, "UTF-8" is always supported - } + String str = new String(data, idx, len, UTF_8); idx = (idx + len + 3) & ~0x3; return str; diff --git a/src/java.desktop/unix/classes/sun/awt/screencast/TokenStorage.java b/src/java.desktop/unix/classes/sun/awt/screencast/TokenStorage.java index 3daf9b2a8b8..b05ff7f8c4a 100644 --- a/src/java.desktop/unix/classes/sun/awt/screencast/TokenStorage.java +++ b/src/java.desktop/unix/classes/sun/awt/screencast/TokenStorage.java @@ -60,35 +60,33 @@ * The restore token allows the ScreenCast session to be restored * with previously granted screen access permissions. */ -@SuppressWarnings("removal") final class TokenStorage { private TokenStorage() {} private static final String REL_NAME = + ".java/robot/screencast-tokens.properties"; + private static final String REL_NAME_SECONDARY = ".awt/robot/screencast-tokens.properties"; private static final Properties PROPS = new Properties(); private static final Path PROPS_PATH; private static final Path PROP_FILENAME; + @SuppressWarnings("removal") private static void doPrivilegedRunnable(Runnable runnable) { - AccessController.doPrivileged(new PrivilegedAction() { - @Override - public Void run() { - runnable.run(); - return null; - } + AccessController.doPrivileged((PrivilegedAction) () -> { + runnable.run(); + return null; }); } static { - PROPS_PATH = AccessController.doPrivileged(new PrivilegedAction() { - @Override - public Path run() { - return setupPath(); - } - }); + @SuppressWarnings("removal") + Path propsPath = AccessController + .doPrivileged((PrivilegedAction) () -> setupPath()); + + PROPS_PATH = propsPath; if (PROPS_PATH != null) { PROP_FILENAME = PROPS_PATH.getFileName(); @@ -110,25 +108,32 @@ private static Path setupPath() { } Path path = Path.of(userHome, REL_NAME); + Path secondaryPath = Path.of(userHome, REL_NAME_SECONDARY); + + boolean copyFromSecondary = !Files.isWritable(path) + && Files.isWritable(secondaryPath); + Path workdir = path.getParent(); - if (!Files.exists(workdir)) { - try { - Files.createDirectories(workdir); - } catch (Exception e) { - if (SCREENCAST_DEBUG) { - System.err.printf("Token storage: cannot create" + - " directory %s %s\n", workdir, e); + if (!Files.isWritable(path)) { + if (!Files.exists(workdir)) { + try { + Files.createDirectories(workdir); + } catch (Exception e) { + if (SCREENCAST_DEBUG) { + System.err.printf("Token storage: cannot create" + + " directory %s %s\n", workdir, e); + } + return null; } - return null; } - } - if (!Files.isWritable(workdir)) { - if (SCREENCAST_DEBUG) { - System.err.printf("Token storage: %s is not writable\n", workdir); + if (!Files.isWritable(workdir)) { + if (SCREENCAST_DEBUG) { + System.err.printf("Token storage: %s is not writable\n", workdir); + } + return null; } - return null; } try { @@ -145,7 +150,17 @@ private static Path setupPath() { } } - if (Files.exists(path)) { + if (copyFromSecondary) { + if (SCREENCAST_DEBUG) { + System.out.println("Token storage: copying from the secondary location " + + secondaryPath); + } + synchronized (PROPS) { + if (readTokens(secondaryPath)) { + store(path, "copy from the secondary location"); + } + } + } else if (Files.exists(path)) { if (!setFilePermission(path)) { return null; } @@ -302,7 +317,7 @@ private static void storeTokenFromNative(String oldToken, } if (changed) { - doPrivilegedRunnable(() -> store("save tokens")); + doPrivilegedRunnable(() -> store(PROPS_PATH, "save tokens")); } } } @@ -315,7 +330,7 @@ private static boolean readTokens(Path path) { PROPS.clear(); PROPS.load(reader); } - } catch (IOException e) { + } catch (IOException | IllegalArgumentException e) { if (SCREENCAST_DEBUG) { System.err.printf(""" Token storage: failed to load property file %s @@ -410,7 +425,7 @@ static Set getTokens(List affectedScreenBounds) { } private static void removeMalformedRecords(Set malformedRecords) { - if (!isWritable() + if (!isWritable(PROPS_PATH) || malformedRecords == null || malformedRecords.isEmpty()) { return; @@ -424,17 +439,17 @@ private static void removeMalformedRecords(Set malformedRecords) { } } - store("remove malformed records"); + store(PROPS_PATH, "remove malformed records"); } } - private static void store(String failMsg) { - if (!isWritable()) { + private static void store(Path path, String failMsg) { + if (!isWritable(path)) { return; } synchronized (PROPS) { - try (BufferedWriter writer = Files.newBufferedWriter(PROPS_PATH)) { + try (BufferedWriter writer = Files.newBufferedWriter(path)) { PROPS.store(writer, null); } catch (IOException e) { if (SCREENCAST_DEBUG) { @@ -445,13 +460,13 @@ private static void store(String failMsg) { } } - private static boolean isWritable() { - if (PROPS_PATH == null - || (Files.exists(PROPS_PATH) && !Files.isWritable(PROPS_PATH))) { + private static boolean isWritable(Path path) { + if (path == null + || (Files.exists(path) && !Files.isWritable(path))) { if (SCREENCAST_DEBUG) { System.err.printf( - "Token storage: %s is not writable\n", PROPS_PATH); + "Token storage: %s is not writable\n", path); } return false; } else { diff --git a/src/java.desktop/unix/classes/sun/font/FcFontConfiguration.java b/src/java.desktop/unix/classes/sun/font/FcFontConfiguration.java index 0ea741c1ccf..39970e29ca4 100644 --- a/src/java.desktop/unix/classes/sun/font/FcFontConfiguration.java +++ b/src/java.desktop/unix/classes/sun/font/FcFontConfiguration.java @@ -32,23 +32,24 @@ import java.net.InetAddress; import java.net.UnknownHostException; import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.util.HashMap; import java.util.HashSet; import java.util.Locale; import java.util.Properties; import java.util.Scanner; + import sun.awt.FcFontManager; import sun.awt.FontConfiguration; import sun.awt.FontDescriptor; import sun.awt.SunToolkit; -import sun.font.CompositeFontDescriptor; -import sun.font.FontConfigManager.FontConfigInfo; import sun.font.FontConfigManager.FcCompFont; import sun.font.FontConfigManager.FontConfigFont; +import sun.font.FontConfigManager.FontConfigInfo; import sun.util.logging.PlatformLogger; +import static java.nio.charset.StandardCharsets.ISO_8859_1; + public class FcFontConfiguration extends FontConfiguration { /** Version of the cache file format understood by this code. @@ -178,7 +179,7 @@ protected FontDescriptor[] buildFontDescriptors(int fontIndex, int styleIndex) { String[] componentFaceNames = cfi[idx].getComponentFaceNames(); FontDescriptor[] ret = new FontDescriptor[componentFaceNames.length]; for (int i = 0; i < componentFaceNames.length; i++) { - ret[i] = new FontDescriptor(componentFaceNames[i], StandardCharsets.ISO_8859_1.newEncoder(), new int[0]); + ret[i] = new FontDescriptor(componentFaceNames[i], ISO_8859_1.newEncoder(), new int[0]); } return ret; diff --git a/src/java.desktop/unix/classes/sun/font/NativeFont.java b/src/java.desktop/unix/classes/sun/font/NativeFont.java index b30b6459c3b..3bd212b2525 100644 --- a/src/java.desktop/unix/classes/sun/font/NativeFont.java +++ b/src/java.desktop/unix/classes/sun/font/NativeFont.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2021, Oracle and/or its affiliates. All rights reserved. * 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,10 +32,10 @@ import java.awt.geom.GeneralPath; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; -import java.io.UnsupportedEncodingException; -import java.lang.ref.WeakReference; import java.util.Locale; +import static java.nio.charset.StandardCharsets.UTF_8; + /* * Ideally there would be no native fonts used, and this class would be * unneeded and removed. Presently it is still needed until such time @@ -213,23 +213,11 @@ static boolean hasExternalBitmaps(String platName) { pos = sb.indexOf("-0-", pos); }; String xlfd = sb.toString(); - byte[] bytes = null; - try { - bytes = xlfd.getBytes("UTF-8"); - } catch (UnsupportedEncodingException e) { - bytes = xlfd.getBytes(); - } - return haveBitmapFonts(bytes); + return haveBitmapFonts(xlfd.getBytes(UTF_8)); } public static boolean fontExists(String xlfd) { - byte[] bytes = null; - try { - bytes = xlfd.getBytes("UTF-8"); - } catch (UnsupportedEncodingException e) { - bytes = xlfd.getBytes(); - } - return fontExists(bytes); + return fontExists(xlfd.getBytes(UTF_8)); } private static native boolean haveBitmapFonts(byte[] xlfd); @@ -380,13 +368,7 @@ byte[] getPlatformNameBytes(int ptSize) { } String xlfd = sb.toString(); - byte[] bytes = null; - try { - bytes = xlfd.getBytes("UTF-8"); - } catch (UnsupportedEncodingException e) { - bytes = xlfd.getBytes(); - } - return bytes; + return xlfd.getBytes(UTF_8); } public String toString() { diff --git a/src/java.desktop/unix/classes/sun/print/AttributeClass.java b/src/java.desktop/unix/classes/sun/print/AttributeClass.java index 76a652b2a93..0fb27909a26 100644 --- a/src/java.desktop/unix/classes/sun/print/AttributeClass.java +++ b/src/java.desktop/unix/classes/sun/print/AttributeClass.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -22,10 +22,13 @@ * or visit www.oracle.com if you need additional information or have any * questions. */ + package sun.print; -import java.util.Objects; import java.io.ByteArrayInputStream; +import java.util.Objects; + +import static java.nio.charset.StandardCharsets.UTF_8; public class AttributeClass { private String myName; @@ -187,10 +190,7 @@ public String getStringValue() { byte[] strBytes = new byte[valLength]; bufStream.read(strBytes, 0, valLength); - try { - strVal = new String(strBytes, "UTF-8"); - } catch (java.io.UnsupportedEncodingException uee) { - } + strVal = new String(strBytes, UTF_8); } return strVal; } @@ -219,10 +219,7 @@ public String[] getArrayOfStringValues() { int valLength = bufStream.read(); byte[] bufBytes = new byte[valLength]; bufStream.read(bufBytes, 0, valLength); - try { - valueArray[i] = new String(bufBytes, "UTF-8"); - } catch (java.io.UnsupportedEncodingException uee) { - } + valueArray[i] = new String(bufBytes, UTF_8); } return valueArray; } diff --git a/src/java.desktop/unix/classes/sun/print/IPPPrintService.java b/src/java.desktop/unix/classes/sun/print/IPPPrintService.java index fee8bc3d3cd..7ef37b116ab 100644 --- a/src/java.desktop/unix/classes/sun/print/IPPPrintService.java +++ b/src/java.desktop/unix/classes/sun/print/IPPPrintService.java @@ -27,42 +27,82 @@ import java.awt.GraphicsEnvironment; import java.awt.Toolkit; -import javax.print.attribute.*; -import javax.print.attribute.standard.*; -import javax.print.DocFlavor; -import javax.print.DocPrintJob; -import javax.print.PrintService; -import javax.print.ServiceUIFactory; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Locale; -import java.util.Date; -import java.util.Arrays; -import java.security.AccessController; -import java.security.PrivilegedActionException; -import java.security.PrivilegedExceptionAction; -import javax.print.event.PrintServiceAttributeListener; - -import java.net.URI; -import java.net.URISyntaxException; -import java.net.URL; -import java.net.URLConnection; -import java.net.HttpURLConnection; +import java.io.BufferedReader; +import java.io.ByteArrayOutputStream; +import java.io.DataInputStream; import java.io.File; import java.io.InputStream; +import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; -import java.io.DataInputStream; -import java.io.ByteArrayOutputStream; -import java.io.ByteArrayInputStream; -import java.io.BufferedReader; -import java.io.InputStreamReader; -import java.nio.charset.Charset; - -import java.util.Iterator; +import java.net.HttpURLConnection; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URL; +import java.net.URLConnection; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; import java.util.HashSet; +import java.util.Locale; import java.util.Map; +import javax.print.DocFlavor; +import javax.print.DocPrintJob; +import javax.print.PrintService; +import javax.print.ServiceUIFactory; +import javax.print.attribute.Attribute; +import javax.print.attribute.AttributeSet; +import javax.print.attribute.AttributeSetUtilities; +import javax.print.attribute.EnumSyntax; +import javax.print.attribute.HashAttributeSet; +import javax.print.attribute.HashPrintServiceAttributeSet; +import javax.print.attribute.PrintRequestAttribute; +import javax.print.attribute.PrintServiceAttribute; +import javax.print.attribute.PrintServiceAttributeSet; +import javax.print.attribute.Size2DSyntax; +import javax.print.attribute.standard.Chromaticity; +import javax.print.attribute.standard.ColorSupported; +import javax.print.attribute.standard.Copies; +import javax.print.attribute.standard.CopiesSupported; +import javax.print.attribute.standard.Destination; +import javax.print.attribute.standard.DialogOwner; +import javax.print.attribute.standard.DialogTypeSelection; +import javax.print.attribute.standard.Fidelity; +import javax.print.attribute.standard.Finishings; +import javax.print.attribute.standard.JobName; +import javax.print.attribute.standard.JobSheets; +import javax.print.attribute.standard.Media; +import javax.print.attribute.standard.MediaPrintableArea; +import javax.print.attribute.standard.MediaSize; +import javax.print.attribute.standard.MediaSizeName; +import javax.print.attribute.standard.MediaTray; +import javax.print.attribute.standard.NumberUp; +import javax.print.attribute.standard.OrientationRequested; +import javax.print.attribute.standard.PDLOverrideSupported; +import javax.print.attribute.standard.PageRanges; +import javax.print.attribute.standard.PagesPerMinute; +import javax.print.attribute.standard.PagesPerMinuteColor; +import javax.print.attribute.standard.PrinterInfo; +import javax.print.attribute.standard.PrinterIsAcceptingJobs; +import javax.print.attribute.standard.PrinterLocation; +import javax.print.attribute.standard.PrinterMakeAndModel; +import javax.print.attribute.standard.PrinterMessageFromOperator; +import javax.print.attribute.standard.PrinterMoreInfo; +import javax.print.attribute.standard.PrinterMoreInfoManufacturer; +import javax.print.attribute.standard.PrinterName; +import javax.print.attribute.standard.PrinterResolution; +import javax.print.attribute.standard.PrinterState; +import javax.print.attribute.standard.PrinterStateReasons; +import javax.print.attribute.standard.PrinterURI; +import javax.print.attribute.standard.QueuedJobCount; +import javax.print.attribute.standard.RequestingUserName; +import javax.print.attribute.standard.SheetCollate; +import javax.print.attribute.standard.Sides; +import javax.print.event.PrintServiceAttributeListener; + +import static java.nio.charset.StandardCharsets.ISO_8859_1; +import static java.nio.charset.StandardCharsets.UTF_8; public class IPPPrintService implements PrintService, SunPrinterJobService { @@ -325,11 +365,7 @@ protected static void debug_println(String str) { if ((name == null) || (url == null)){ throw new IllegalArgumentException("null uri or printer name"); } - try { - printer = java.net.URLDecoder.decode(name, "UTF-8"); - } catch (java.io.UnsupportedEncodingException e) { - printer = name; - } + printer = java.net.URLDecoder.decode(name, UTF_8); supportedDocFlavors = null; supportedCats = null; mediaSizeNames = null; @@ -359,11 +395,7 @@ protected static void debug_println(String str) { if ((name == null) || (uriStr == null)){ throw new IllegalArgumentException("null uri or printer name"); } - try { - printer = java.net.URLDecoder.decode(name, "UTF-8"); - } catch (java.io.UnsupportedEncodingException e) { - printer = name; - } + printer = java.net.URLDecoder.decode(name, UTF_8); supportedDocFlavors = null; supportedCats = null; mediaSizeNames = null; @@ -1735,9 +1767,8 @@ public synchronized boolean isPostscript() { InputStream is = urlConnection.getInputStream(); if (is != null) { - BufferedReader d = - new BufferedReader(new InputStreamReader(is, - Charset.forName("ISO-8859-1"))); + BufferedReader d = new BufferedReader( + new InputStreamReader(is, ISO_8859_1)); String lineStr; while ((lineStr = d.readLine()) != null) { if (lineStr.startsWith("*cupsFilter:")) { @@ -1829,13 +1860,7 @@ public OutputStream run() { public static boolean writeIPPRequest(OutputStream os, String operCode, AttributeClass[] attCl) { - OutputStreamWriter osw; - try { - osw = new OutputStreamWriter(os, "UTF-8"); - } catch (java.io.UnsupportedEncodingException exc) { - debug_println(debugPrefix+"writeIPPRequest, UTF-8 not supported? Exception: "+exc); - return false; - } + OutputStreamWriter osw = new OutputStreamWriter(os, UTF_8); debug_println(debugPrefix+"writeIPPRequest, op code= "+operCode); char[] opCode = new char[2]; opCode[0] = (char)Byte.parseByte(operCode.substring(0,2), 16); diff --git a/src/java.desktop/unix/native/libawt_xawt/awt/gtk2_interface.h b/src/java.desktop/unix/native/libawt_xawt/awt/gtk2_interface.h index 4a9773d333a..8075d4f419f 100644 --- a/src/java.desktop/unix/native/libawt_xawt/awt/gtk2_interface.h +++ b/src/java.desktop/unix/native/libawt_xawt/awt/gtk2_interface.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2024, Oracle and/or its affiliates. All rights reserved. * 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,13 +55,11 @@ typedef enum } GParamFlags; /* We define all structure pointers to be void* */ -typedef void GMainContext; typedef void GVfs; typedef void GdkColormap; typedef void GdkDrawable; typedef void GdkGC; -typedef void GdkPixbuf; typedef void GdkPixmap; typedef void GtkFixed; diff --git a/src/java.desktop/unix/native/libawt_xawt/awt/gtk3_interface.h b/src/java.desktop/unix/native/libawt_xawt/awt/gtk3_interface.h index ed5997cb0cd..054510d488b 100644 --- a/src/java.desktop/unix/native/libawt_xawt/awt/gtk3_interface.h +++ b/src/java.desktop/unix/native/libawt_xawt/awt/gtk3_interface.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -180,8 +180,6 @@ typedef enum _cairo_status { } cairo_status_t; /* We define all structure pointers to be void* */ -typedef void GdkPixbuf; -typedef void GMainContext; typedef void GVfs; typedef void GdkColormap; diff --git a/src/java.desktop/windows/classes/sun/awt/windows/WDataTransferer.java b/src/java.desktop/windows/classes/sun/awt/windows/WDataTransferer.java index 16b6faf7ee7..c82fc91a4e1 100644 --- a/src/java.desktop/windows/classes/sun/awt/windows/WDataTransferer.java +++ b/src/java.desktop/windows/classes/sun/awt/windows/WDataTransferer.java @@ -25,19 +25,15 @@ package sun.awt.windows; -import java.awt.Image; import java.awt.Graphics2D; +import java.awt.Image; import java.awt.Transparency; - import java.awt.color.ColorSpace; - import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.FlavorTable; import java.awt.datatransfer.Transferable; import java.awt.datatransfer.UnsupportedFlavorException; - import java.awt.geom.AffineTransform; - import java.awt.image.BufferedImage; import java.awt.image.ColorModel; import java.awt.image.ComponentColorModel; @@ -48,18 +44,16 @@ import java.awt.image.ImageObserver; import java.awt.image.Raster; import java.awt.image.WritableRaster; - import java.io.BufferedInputStream; import java.io.BufferedReader; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.io.File; - import java.net.URL; - import java.nio.charset.Charset; +import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; @@ -69,13 +63,11 @@ import sun.awt.Mutex; import sun.awt.datatransfer.DataTransferer; import sun.awt.datatransfer.ToolkitThreadBlockedHandler; - import sun.awt.image.ImageRepresentation; import sun.awt.image.ToolkitImage; -import java.util.ArrayList; - -import java.io.ByteArrayOutputStream; +import static java.nio.charset.StandardCharsets.UTF_16LE; +import static java.nio.charset.StandardCharsets.UTF_8; /** * Platform-specific support for the data transfer subsystem. @@ -249,7 +241,7 @@ public Object translateBytes(byte[] bytes, DataFlavor flavor, long format, if (bytes == null || !DataFlavor.javaFileListFlavor.equals(flavor)) { throw new IOException("data translation failed"); } - String st = new String(bytes, 0, bytes.length, "UTF-16LE"); + String st = new String(bytes, 0, bytes.length, UTF_16LE); String[] filenames = st.split("\0"); if( 0 == filenames.length ){ return null; @@ -275,7 +267,7 @@ public Object translateBytes(byte[] bytes, DataFlavor flavor, long format, { try { charset = new String((byte[])localeTransferable. - getTransferData(javaTextEncodingFlavor), "UTF-8"); + getTransferData(javaTextEncodingFlavor), UTF_8); } catch (UnsupportedFlavorException cannotHappen) { } } @@ -548,8 +540,6 @@ public static EHTMLReadMode getEHTMLReadMode (DataFlavor df) { * on encode: static convertToHTMLFormat is responsible for HTML clipboard header creation */ class HTMLCodec extends InputStream { - //static section - public static final String ENCODING = "UTF-8"; public static final String VERSION = "Version:"; public static final String START_HTML = "StartHTML:"; @@ -671,13 +661,8 @@ public static byte[] convertToHTMLFormat(byte[] bytes) { //HTML header.append(htmlPrefix); - byte[] headerBytes = null, trailerBytes = null; - - try { - headerBytes = header.toString().getBytes(ENCODING); - trailerBytes = htmlSuffix.getBytes(ENCODING); - } catch (UnsupportedEncodingException cannotHappen) { - } + byte[] headerBytes = header.toString().getBytes(UTF_8); + byte[] trailerBytes = htmlSuffix.getBytes(UTF_8); byte[] retval = new byte[headerBytes.length + bytes.length + trailerBytes.length]; @@ -786,7 +771,7 @@ private void parseDescription() throws IOException BufferedReader bufferedReader = new BufferedReader( new InputStreamReader( bufferedStream, - ENCODING + UTF_8 ), CHAR_BUFFER_LEN ); diff --git a/src/java.naming/share/classes/com/sun/jndi/ldap/sasl/SaslInputStream.java b/src/java.naming/share/classes/com/sun/jndi/ldap/sasl/SaslInputStream.java index f0746c103bc..534f7dac766 100644 --- a/src/java.naming/share/classes/com/sun/jndi/ldap/sasl/SaslInputStream.java +++ b/src/java.naming/share/classes/com/sun/jndi/ldap/sasl/SaslInputStream.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2003, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 2024, Oracle and/or its affiliates. All rights reserved. * 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,7 +78,7 @@ public int read() throws IOException { byte[] inBuf = new byte[1]; int count = read(inBuf, 0, 1); if (count > 0) { - return inBuf[0]; + return inBuf[0] & 0xff; } else { return -1; } diff --git a/src/jdk.compiler/share/classes/com/sun/tools/javac/jvm/StringConcat.java b/src/jdk.compiler/share/classes/com/sun/tools/javac/jvm/StringConcat.java index f11054d7302..8ccbe716b78 100644 --- a/src/jdk.compiler/share/classes/com/sun/tools/javac/jvm/StringConcat.java +++ b/src/jdk.compiler/share/classes/com/sun/tools/javac/jvm/StringConcat.java @@ -142,25 +142,6 @@ private List collect(JCTree tree, List res) { return res.append(tree); } - /** - * If the type is not accessible from current context, try to figure out the - * sharpest accessible supertype. - * - * @param originalType type to sharpen - * @return sharped type - */ - Type sharpestAccessible(Type originalType) { - if (originalType.hasTag(ARRAY)) { - return types.makeArrayType(sharpestAccessible(types.elemtype(originalType))); - } - - Type type = originalType; - while (!rs.isAccessible(gen.getAttrEnv(), type.asElement())) { - type = types.supertype(type); - } - return type; - } - /** * "Legacy" bytecode flavor: emit the StringBuilder.append chains for string * concatenation. @@ -305,6 +286,14 @@ protected List> split(List args) { return splits.toList(); } + + /** + * Returns true if the argument should be converted to a string eagerly, to preserve + * possible side-effects. + */ + protected boolean shouldConvertToStringEagerly(Type argType) { + return !types.unboxedTypeOrType(argType).isPrimitive() && argType.tsym != syms.stringType.tsym; + } } /** @@ -333,14 +322,18 @@ protected void emit(JCDiagnostic.DiagnosticPosition pos, List args, bool for (JCTree arg : t) { Object constVal = arg.type.constValue(); if ("".equals(constVal)) continue; - if (arg.type == syms.botType) { - dynamicArgs.add(types.boxedClass(syms.voidType).type); - } else { - dynamicArgs.add(sharpestAccessible(arg.type)); + Type argType = arg.type; + if (argType == syms.botType) { + argType = types.boxedClass(syms.voidType).type; } if (!first || generateFirstArg) { gen.genExpr(arg, arg.type).load(); } + if (shouldConvertToStringEagerly(argType)) { + gen.callMethod(pos, syms.stringType, names.valueOf, List.of(syms.objectType), true); + argType = syms.stringType; + } + dynamicArgs.add(argType); first = false; } doCall(type, pos, dynamicArgs.toList()); @@ -439,10 +432,15 @@ protected void emit(JCDiagnostic.DiagnosticPosition pos, List args, bool } else { // Ordinary arguments come through the dynamic arguments. recipe.append(TAG_ARG); - dynamicArgs.add(sharpestAccessible(arg.type)); + Type argType = arg.type; if (!first || generateFirstArg) { gen.genExpr(arg, arg.type).load(); } + if (shouldConvertToStringEagerly(argType)) { + gen.callMethod(pos, syms.stringType, names.valueOf, List.of(syms.objectType), true); + argType = syms.stringType; + } + dynamicArgs.add(argType); first = false; } } diff --git a/src/jdk.jdi/share/classes/com/sun/tools/jdi/TargetVM.java b/src/jdk.jdi/share/classes/com/sun/tools/jdi/TargetVM.java index 8a33c23a70c..4946b8dedac 100644 --- a/src/jdk.jdi/share/classes/com/sun/tools/jdi/TargetVM.java +++ b/src/jdk.jdi/share/classes/com/sun/tools/jdi/TargetVM.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -124,8 +124,9 @@ public void run() { byte b[] = connection.readPacket(); if (b.length == 0) { done = true; + } else { + p = Packet.fromByteArray(b); } - p = Packet.fromByteArray(b); } catch (IOException e) { done = true; } diff --git a/src/jdk.jdwp.agent/share/native/libjdwp/util.c b/src/jdk.jdwp.agent/share/native/libjdwp/util.c index c37ed79cdf7..bba5127294e 100644 --- a/src/jdk.jdwp.agent/share/native/libjdwp/util.c +++ b/src/jdk.jdwp.agent/share/native/libjdwp/util.c @@ -287,12 +287,12 @@ util_initialize(JNIEnv *env) localAgentProperties = JNI_FUNC_PTR(env,CallStaticObjectMethod) (env, localVMSupportClass, getAgentProperties); - saveGlobalRef(env, localAgentProperties, &(gdata->agent_properties)); if (JNI_FUNC_PTR(env,ExceptionOccurred)(env)) { JNI_FUNC_PTR(env,ExceptionClear)(env); EXIT_ERROR(AGENT_ERROR_INTERNAL, "Exception occurred calling VMSupport.getAgentProperties"); } + saveGlobalRef(env, localAgentProperties, &(gdata->agent_properties)); } } END_WITH_LOCAL_REFS(env); diff --git a/src/jdk.jfr/share/conf/jfr/default.jfc b/src/jdk.jfr/share/conf/jfr/default.jfc index aeab7991701..6faba56991c 100644 --- a/src/jdk.jfr/share/conf/jfr/default.jfc +++ b/src/jdk.jfr/share/conf/jfr/default.jfc @@ -777,6 +777,7 @@ true + true 0 ms diff --git a/src/jdk.jfr/share/conf/jfr/profile.jfc b/src/jdk.jfr/share/conf/jfr/profile.jfc index b4943a3f435..f70633bfe74 100644 --- a/src/jdk.jfr/share/conf/jfr/profile.jfc +++ b/src/jdk.jfr/share/conf/jfr/profile.jfc @@ -777,6 +777,7 @@ true + true 0 ms diff --git a/test/hotspot/jtreg/ProblemList-zgc.txt b/test/hotspot/jtreg/ProblemList-zgc.txt index d641e2ddcbd..204aa651d89 100644 --- a/test/hotspot/jtreg/ProblemList-zgc.txt +++ b/test/hotspot/jtreg/ProblemList-zgc.txt @@ -32,6 +32,7 @@ vmTestbase/jit/escape/AdaptiveBlocking/AdaptiveBlocking001/AdaptiveBlocking001.j resourcehogs/serviceability/sa/TestHeapDumpForLargeArray.java 8220624 generic-all serviceability/sa/CDSJMapClstats.java 8220624 generic-all serviceability/sa/ClhsdbJhisto.java 8220624 generic-all +serviceability/sa/jmap-hprof/JMapHProfLargeHeapTest.java 8276539 generic-all serviceability/sa/ClhsdbCDSCore.java 8268722 macosx-x64 serviceability/sa/ClhsdbFindPC.java#id1 8268722 macosx-x64 diff --git a/test/hotspot/jtreg/ProblemList.txt b/test/hotspot/jtreg/ProblemList.txt index da75003ef67..a9b6e4c0288 100644 --- a/test/hotspot/jtreg/ProblemList.txt +++ b/test/hotspot/jtreg/ProblemList.txt @@ -50,13 +50,13 @@ compiler/cpuflags/TestAESIntrinsicsOnSupportedConfig.java 8190680 generic-all compiler/runtime/Test8168712.java 8211769,8211771 generic-ppc64,generic-ppc64le,linux-s390x compiler/rtm/locking/TestRTMAbortRatio.java 8183263 generic-x64,generic-i586 -compiler/rtm/locking/TestRTMAbortThreshold.java 8183263 generic-x64,generic-i586 +compiler/rtm/locking/TestRTMAbortThreshold.java 8183263,8313877 generic-x64,generic-i586,generic-ppc64le compiler/rtm/locking/TestRTMAfterNonRTMDeopt.java 8183263 generic-x64,generic-i586 compiler/rtm/locking/TestRTMDeoptOnHighAbortRatio.java 8183263 generic-x64,generic-i586 compiler/rtm/locking/TestRTMDeoptOnLowAbortRatio.java 8183263 generic-x64,generic-i586 compiler/rtm/locking/TestRTMLockingCalculationDelay.java 8183263 generic-x64,generic-i586 compiler/rtm/locking/TestRTMLockingThreshold.java 8183263 generic-x64,generic-i586 -compiler/rtm/locking/TestRTMSpinLoopCount.java 8183263 generic-x64,generic-i586 +compiler/rtm/locking/TestRTMSpinLoopCount.java 8183263,8313877 generic-x64,generic-i586,generic-ppc64le compiler/rtm/locking/TestUseRTMDeopt.java 8183263 generic-x64,generic-i586 compiler/rtm/locking/TestUseRTMXendForLockBusy.java 8183263 generic-x64,generic-i586 compiler/rtm/print/TestPrintPreciseRTMLockingStatistics.java 8183263 generic-x64,generic-i586 diff --git a/test/hotspot/jtreg/TEST.groups b/test/hotspot/jtreg/TEST.groups index 8a5f7a44919..97b4300a2b1 100644 --- a/test/hotspot/jtreg/TEST.groups +++ b/test/hotspot/jtreg/TEST.groups @@ -397,7 +397,8 @@ tier1_runtime = \ -runtime/Unsafe/RangeCheck.java \ sanity/ \ -:tier1_runtime_appcds_exclude \ - -runtime/signal + -runtime/signal \ + -runtime/stack hotspot_cds = \ runtime/cds/ \ diff --git a/test/hotspot/jtreg/applications/jcstress/JcstressRunner.java b/test/hotspot/jtreg/applications/jcstress/JcstressRunner.java index 37ce9e7df70..992cf6956c5 100644 --- a/test/hotspot/jtreg/applications/jcstress/JcstressRunner.java +++ b/test/hotspot/jtreg/applications/jcstress/JcstressRunner.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2024, Oracle and/or its affiliates. All rights reserved. * 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,14 +42,14 @@ * jcstress tests wrapper */ @Artifact(organization = "org.openjdk.jcstress", name = "jcstress-tests-all", - revision = "0.16", extension = "jar", unpack = false) + revision = JcstressRunner.VERSION, extension = "jar", unpack = false) public class JcstressRunner { + public static final String VERSION = "0.17-SNAPSHOT-20240328"; public static final String MAIN_CLASS = "org.openjdk.jcstress.Main"; - // Allow to configure jcstress mode parameter. - // Test mode preset: sanity, quick, default, tough, stress. - public static final String MODE_PROPERTY = "jcstress.mode"; + public static final String TIME_BUDGET_PROPERTY = "jcstress.time_budget"; + public static String timeBudget = "6m"; public static Path pathToArtifact() { Map artifacts; @@ -59,7 +59,7 @@ public static Path pathToArtifact() { throw new Error("TESTBUG: Can not resolve artifacts for " + JcstressRunner.class.getName(), e); } - return artifacts.get("org.openjdk.jcstress.jcstress-tests-all-0.16") + return artifacts.get("org.openjdk.jcstress.jcstress-tests-all-" + VERSION) .toAbsolutePath(); } @@ -69,7 +69,7 @@ public static void main(String[] args) throws Throwable { } Path out = Paths.get("jcstress.out").toAbsolutePath(); - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(getCmd(args)) + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(getCmd(args)) .redirectErrorStream(true) .redirectOutput(out.toFile()); OutputAnalyzer oa = ProcessTools.executeProcess(pb); @@ -109,21 +109,17 @@ private static String[] getCmd(String[] args) { extraFlags.add("--jvmArgs"); extraFlags.add("-Djava.io.tmpdir=" + System.getProperty("user.dir")); - // The "default" preset might take days for some tests - // so use quick testing by default. - String mode = "quick"; for (String jvmArg : Utils.getTestJavaOpts()) { - if(jvmArg.startsWith("-D" + MODE_PROPERTY)) { - String[] pair = jvmArg.split("=", 2); - mode = pair[1]; - continue; + if (jvmArg.startsWith("-D" + TIME_BUDGET_PROPERTY)) { + timeBudget = jvmArg.split("=", 2)[1]; + } else { + extraFlags.add("--jvmArgs"); + extraFlags.add(jvmArg); } - extraFlags.add("--jvmArgs"); - extraFlags.add(jvmArg); } - extraFlags.add("-m"); - extraFlags.add(mode); + extraFlags.add("-tb"); + extraFlags.add(timeBudget); extraFlags.add("-sc"); extraFlags.add("false"); diff --git a/test/hotspot/jtreg/applications/jcstress/TestGenerator.java b/test/hotspot/jtreg/applications/jcstress/TestGenerator.java index 0f5bccfad7e..5252ba2a75b 100644 --- a/test/hotspot/jtreg/applications/jcstress/TestGenerator.java +++ b/test/hotspot/jtreg/applications/jcstress/TestGenerator.java @@ -110,7 +110,7 @@ public static void main(String[] args) throws IOException { Path output; try { output = Files.createTempFile("jcstress", ".out"); - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-jar", path.toAbsolutePath().toString(), "-l"); diff --git a/test/hotspot/jtreg/applications/scimark/Scimark.java b/test/hotspot/jtreg/applications/scimark/Scimark.java index 24691939dd6..c17fad0ac54 100644 --- a/test/hotspot/jtreg/applications/scimark/Scimark.java +++ b/test/hotspot/jtreg/applications/scimark/Scimark.java @@ -49,7 +49,7 @@ public static void main(String... args) throws Exception { System.setProperty("test.noclasspath", "true"); - OutputAnalyzer output = new OutputAnalyzer(ProcessTools.createTestJvm( + OutputAnalyzer output = new OutputAnalyzer(ProcessTools.createTestJavaProcessBuilder( "-cp", artifacts.get("gov.nist.math.scimark-2.0").toString(), "jnt.scimark2.commandline", "-large") .start()); diff --git a/test/hotspot/jtreg/compiler/arguments/CheckCICompilerCount.java b/test/hotspot/jtreg/compiler/arguments/CheckCICompilerCount.java index da007dd0da9..6f137e20261 100644 --- a/test/hotspot/jtreg/compiler/arguments/CheckCICompilerCount.java +++ b/test/hotspot/jtreg/compiler/arguments/CheckCICompilerCount.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -190,7 +190,7 @@ private static void verifyValidOption(String[] arguments, String expected_output ProcessBuilder pb; OutputAnalyzer out; - pb = ProcessTools.createJavaProcessBuilder(arguments); + pb = ProcessTools.createLimitedTestJavaProcessBuilder(arguments); out = new OutputAnalyzer(pb.start()); try { diff --git a/test/hotspot/jtreg/compiler/arguments/CheckCompileThresholdScaling.java b/test/hotspot/jtreg/compiler/arguments/CheckCompileThresholdScaling.java index fb9fe26179f..d03aced702e 100644 --- a/test/hotspot/jtreg/compiler/arguments/CheckCompileThresholdScaling.java +++ b/test/hotspot/jtreg/compiler/arguments/CheckCompileThresholdScaling.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -338,7 +338,7 @@ private static void verifyValidOption(String[] arguments, String[] expected_outp ProcessBuilder pb; OutputAnalyzer out; - pb = ProcessTools.createJavaProcessBuilder(arguments); + pb = ProcessTools.createLimitedTestJavaProcessBuilder(arguments); out = new OutputAnalyzer(pb.start()); try { diff --git a/test/hotspot/jtreg/compiler/arguments/TestPrintOptoAssemblyLineNumbers.java b/test/hotspot/jtreg/compiler/arguments/TestPrintOptoAssemblyLineNumbers.java index 1d029aabc0f..1fddeeb50e8 100644 --- a/test/hotspot/jtreg/compiler/arguments/TestPrintOptoAssemblyLineNumbers.java +++ b/test/hotspot/jtreg/compiler/arguments/TestPrintOptoAssemblyLineNumbers.java @@ -1,6 +1,6 @@ /* * Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. - * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2021, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -51,7 +51,7 @@ public static void main(String[] args) throws Throwable { CheckC2OptoAssembly.class.getName() }; - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(procArgs); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(procArgs); OutputAnalyzer oa = new OutputAnalyzer(pb.start()); oa.shouldHaveExitValue(0); diff --git a/test/hotspot/jtreg/compiler/arraycopy/stress/TestStressArrayCopy.java b/test/hotspot/jtreg/compiler/arraycopy/stress/TestStressArrayCopy.java index 5153f85c9d7..55dfb0460a2 100644 --- a/test/hotspot/jtreg/compiler/arraycopy/stress/TestStressArrayCopy.java +++ b/test/hotspot/jtreg/compiler/arraycopy/stress/TestStressArrayCopy.java @@ -173,7 +173,7 @@ public static void main(String... args) throws Exception { for (String className : classNames) { // Start a new job { - ProcessBuilder pb = ProcessTools.createTestJvm(mix(c, "-Xmx256m", className)); + ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder(mix(c, "-Xmx256m", className)); Process p = pb.start(); OutputAnalyzer oa = new OutputAnalyzer(p); forks.add(new Fork(p, oa)); diff --git a/test/hotspot/jtreg/compiler/blackhole/BlackholeExistingIntrinsicWarningTest.java b/test/hotspot/jtreg/compiler/blackhole/BlackholeExistingIntrinsicWarningTest.java index 8d43b1e85a3..104e7661e7e 100644 --- a/test/hotspot/jtreg/compiler/blackhole/BlackholeExistingIntrinsicWarningTest.java +++ b/test/hotspot/jtreg/compiler/blackhole/BlackholeExistingIntrinsicWarningTest.java @@ -65,14 +65,14 @@ private static List cmdline(String[] args) { } public static void shouldFail(String... args) throws IOException { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(cmdline(args)); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(cmdline(args)); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldHaveExitValue(0); output.shouldContain(MSG); } public static void shouldPass(String... args) throws IOException { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(cmdline(args)); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(cmdline(args)); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldHaveExitValue(0); output.shouldNotContain(MSG); diff --git a/test/hotspot/jtreg/compiler/blackhole/BlackholeExperimentalUnlockTest.java b/test/hotspot/jtreg/compiler/blackhole/BlackholeExperimentalUnlockTest.java index 226c28251f2..6597b2186f2 100644 --- a/test/hotspot/jtreg/compiler/blackhole/BlackholeExperimentalUnlockTest.java +++ b/test/hotspot/jtreg/compiler/blackhole/BlackholeExperimentalUnlockTest.java @@ -65,14 +65,14 @@ private static List cmdline(String[] args) { } public static void shouldFail(String... args) throws IOException { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(cmdline(args)); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(cmdline(args)); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldHaveExitValue(0); output.shouldContain(MSG); } public static void shouldPass(String... args) throws IOException { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(cmdline(args)); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(cmdline(args)); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldHaveExitValue(0); output.shouldNotContain(MSG); diff --git a/test/hotspot/jtreg/compiler/blackhole/BlackholeIntrinsicTest.java b/test/hotspot/jtreg/compiler/blackhole/BlackholeIntrinsicTest.java index a7a72a56ff1..8c8cbc5e88d 100644 --- a/test/hotspot/jtreg/compiler/blackhole/BlackholeIntrinsicTest.java +++ b/test/hotspot/jtreg/compiler/blackhole/BlackholeIntrinsicTest.java @@ -134,7 +134,7 @@ public static void check(String test, String... args) throws IOException { cmdline.add("compiler.blackhole.BlackholeIntrinsicTest"); cmdline.add(test); - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(cmdline); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(cmdline); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldHaveExitValue(0); output.stderrShouldBeEmpty(); diff --git a/test/hotspot/jtreg/compiler/blackhole/BlackholeNonEmptyWarningTest.java b/test/hotspot/jtreg/compiler/blackhole/BlackholeNonEmptyWarningTest.java index 43cbdfd773b..c07754b37ea 100644 --- a/test/hotspot/jtreg/compiler/blackhole/BlackholeNonEmptyWarningTest.java +++ b/test/hotspot/jtreg/compiler/blackhole/BlackholeNonEmptyWarningTest.java @@ -64,14 +64,14 @@ private static List cmdline(String[] args) { } public static void shouldFail(String... args) throws IOException { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(cmdline(args)); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(cmdline(args)); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldHaveExitValue(0); output.shouldContain(MSG); } public static void shouldPass(String... args) throws IOException { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(cmdline(args)); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(cmdline(args)); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldHaveExitValue(0); output.shouldNotContain(MSG); diff --git a/test/hotspot/jtreg/compiler/blackhole/BlackholeNonStaticWarningTest.java b/test/hotspot/jtreg/compiler/blackhole/BlackholeNonStaticWarningTest.java index f9e12ba3f9d..ff84070b4e1 100644 --- a/test/hotspot/jtreg/compiler/blackhole/BlackholeNonStaticWarningTest.java +++ b/test/hotspot/jtreg/compiler/blackhole/BlackholeNonStaticWarningTest.java @@ -64,14 +64,14 @@ private static List cmdline(String[] args) { } public static void shouldFail(String... args) throws IOException { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(cmdline(args)); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(cmdline(args)); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldHaveExitValue(0); output.shouldContain(MSG); } public static void shouldPass(String... args) throws IOException { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(cmdline(args)); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(cmdline(args)); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldHaveExitValue(0); output.shouldNotContain(MSG); diff --git a/test/hotspot/jtreg/compiler/blackhole/BlackholeNonVoidWarningTest.java b/test/hotspot/jtreg/compiler/blackhole/BlackholeNonVoidWarningTest.java index 555f6779124..c3a780576fe 100644 --- a/test/hotspot/jtreg/compiler/blackhole/BlackholeNonVoidWarningTest.java +++ b/test/hotspot/jtreg/compiler/blackhole/BlackholeNonVoidWarningTest.java @@ -64,14 +64,14 @@ private static List cmdline(String[] args) { } public static void shouldFail(String... args) throws IOException { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(cmdline(args)); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(cmdline(args)); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldHaveExitValue(0); output.shouldContain(MSG); } public static void shouldPass(String... args) throws IOException { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(cmdline(args)); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(cmdline(args)); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldHaveExitValue(0); output.shouldNotContain(MSG); diff --git a/test/hotspot/jtreg/compiler/c1/TestRangeCheckEliminated.java b/test/hotspot/jtreg/compiler/c1/TestRangeCheckEliminated.java index 7d4dd350e03..9da8a5390da 100644 --- a/test/hotspot/jtreg/compiler/c1/TestRangeCheckEliminated.java +++ b/test/hotspot/jtreg/compiler/c1/TestRangeCheckEliminated.java @@ -1,6 +1,6 @@ /* * Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved. - * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2021, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -54,7 +54,7 @@ public static void main(String[] args) throws Throwable { test_constant_array.class.getName() }; - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(procArgs); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(procArgs); String output = new OutputAnalyzer(pb.start()).getOutput(); // should have 2 "can be fully eliminated" System.out.println(output); @@ -74,7 +74,7 @@ public static void main(String[] args) throws Throwable { test_multi_constant_array.class.getName() }; - pb = ProcessTools.createJavaProcessBuilder(procArgs); + pb = ProcessTools.createLimitedTestJavaProcessBuilder(procArgs); output = new OutputAnalyzer(pb.start()).getOutput(); // should have 1 "can be fully eliminated" System.out.println(output); @@ -94,7 +94,7 @@ public static void main(String[] args) throws Throwable { test_multi_new_array.class.getName() }; - pb = ProcessTools.createJavaProcessBuilder(procArgs); + pb = ProcessTools.createLimitedTestJavaProcessBuilder(procArgs); output = new OutputAnalyzer(pb.start()).getOutput(); // should have 2 "can be fully eliminated" System.out.println(output); diff --git a/test/hotspot/jtreg/compiler/c2/Test7068051.java b/test/hotspot/jtreg/compiler/c2/Test7068051.java index 6e8b9361084..f9cb813aa75 100644 --- a/test/hotspot/jtreg/compiler/c2/Test7068051.java +++ b/test/hotspot/jtreg/compiler/c2/Test7068051.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -36,6 +36,7 @@ import jdk.test.lib.JDKToolLauncher; import jdk.test.lib.process.OutputAnalyzer; +import jdk.test.lib.process.ProcessTools; import java.io.IOException; import java.io.InputStream; @@ -133,11 +134,10 @@ private static void runJar(List params) { for (String p : params) { jar.addToolArg(p); } - ProcessBuilder pb = new ProcessBuilder(jar.getCommand()); try { - OutputAnalyzer output = new OutputAnalyzer(pb.start()); + OutputAnalyzer output = ProcessTools.executeProcess(jar.getCommand()); output.shouldHaveExitValue(0); - } catch (IOException ex) { + } catch (Exception ex) { throw new AssertionError("TESTBUG: jar failed.", ex); } } diff --git a/test/hotspot/jtreg/compiler/c2/TestBit.java b/test/hotspot/jtreg/compiler/c2/TestBit.java index 02596b7ee55..a3c9421a3f9 100644 --- a/test/hotspot/jtreg/compiler/c2/TestBit.java +++ b/test/hotspot/jtreg/compiler/c2/TestBit.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2020, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -49,7 +49,7 @@ static void runTest(String testName) throws Exception { "-XX:CompileCommand=compileonly," + className + "::tst*", className, testName}; - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(procArgs); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(procArgs); OutputAnalyzer output = new OutputAnalyzer(pb.start()); String expectedTestBitInstruction = diff --git a/test/hotspot/jtreg/compiler/c2/aarch64/TestFarJump.java b/test/hotspot/jtreg/compiler/c2/aarch64/TestFarJump.java index e2b7605a5d8..3fe213122bd 100644 --- a/test/hotspot/jtreg/compiler/c2/aarch64/TestFarJump.java +++ b/test/hotspot/jtreg/compiler/c2/aarch64/TestFarJump.java @@ -94,7 +94,7 @@ static void runVM(boolean bigCodeHeap) throws Exception { "-XX:CompileCommand=option," + className + "::main,bool,PrintAssembly,true", className}; - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(procArgs); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(procArgs); OutputAnalyzer output = new OutputAnalyzer(pb.start()); List lines = output.asLines(); diff --git a/test/hotspot/jtreg/compiler/c2/aarch64/TestSVEWithJNI.java b/test/hotspot/jtreg/compiler/c2/aarch64/TestSVEWithJNI.java index eeb10e99547..81abcd27959 100644 --- a/test/hotspot/jtreg/compiler/c2/aarch64/TestSVEWithJNI.java +++ b/test/hotspot/jtreg/compiler/c2/aarch64/TestSVEWithJNI.java @@ -1,27 +1,27 @@ /* -* Copyright (c) 2020, 2021, Oracle and/or its affiliates. All rights reserved. -* Copyright (c) 2020, Arm Limited. All rights reserved. -* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. -* -* This code is free software; you can redistribute 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. -* -*/ + * Copyright (c) 2020, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2020, Arm Limited. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute 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 @@ -79,7 +79,7 @@ public static ProcessBuilder createProcessBuilder(String [] args, String mode) { Collections.addAll(vmopts, "-Dtest.jdk=" + testjdkPath); Collections.addAll(vmopts, args); Collections.addAll(vmopts, TestSVEWithJNI.class.getName(), mode); - return ProcessTools.createJavaProcessBuilder(vmopts.toArray(new String[vmopts.size()])); + return ProcessTools.createLimitedTestJavaProcessBuilder(vmopts.toArray(new String[vmopts.size()])); } public static void main(String [] args) throws Exception { diff --git a/test/hotspot/jtreg/compiler/c2/aarch64/TestVolatiles.java b/test/hotspot/jtreg/compiler/c2/aarch64/TestVolatiles.java index 055d54ccb4f..10bc237f2be 100644 --- a/test/hotspot/jtreg/compiler/c2/aarch64/TestVolatiles.java +++ b/test/hotspot/jtreg/compiler/c2/aarch64/TestVolatiles.java @@ -1,6 +1,6 @@ /* * Copyright (c) 2018, 2020, Red Hat, Inc. All rights reserved. - * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2021, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -132,7 +132,7 @@ public void runtest(String classname, String testType) throws Throwable { public void runtest(String classname, String testType, boolean useCompressedOops, String[] procArgs) throws Throwable { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(procArgs); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(procArgs); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.stderrShouldBeEmptyIgnoreVMWarnings(); diff --git a/test/hotspot/jtreg/compiler/calls/TestManyArgs.java b/test/hotspot/jtreg/compiler/calls/TestManyArgs.java new file mode 100644 index 00000000000..fbd9c13d7c9 --- /dev/null +++ b/test/hotspot/jtreg/compiler/calls/TestManyArgs.java @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2024, Rivos Inc. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* @test + * @summary Pass values on stack. + * @requires os.arch == "riscv64" + * @run main/native compiler.calls.TestManyArgs + */ + +package compiler.calls; + +public class TestManyArgs { + static { + System.loadLibrary("TestManyArgs"); + } + + native static void scramblestack(); + + native static int checkargs(int arg0, short arg1, byte arg2, + int arg3, short arg4, byte arg5, + int arg6, short arg7, byte arg8, + int arg9, short arg10, byte arg11); + + static int compiledbridge(int arg0, short arg1, byte arg2, + int arg3, short arg4, byte arg5, + int arg6, short arg7, byte arg8, + int arg9, short arg10, byte arg11) { + return checkargs(arg0, arg1, arg2, arg3, arg4, arg5, + arg6, arg7, arg8, arg9, arg10, arg11); + } + + static public void main(String[] args) { + scramblestack(); + for (int i = 0; i < 20000; i++) { + int res = compiledbridge((int)0xf, (short)0xf, (byte)0xf, + (int)0xf, (short)0xf, (byte)0xf, + (int)0xf, (short)0xf, (byte)0xf, + (int)0xf, (short)0xf, (byte)0xf); + if (res != 0) { + throw new RuntimeException("Test failed"); + } + } + } +} diff --git a/test/hotspot/jtreg/compiler/calls/libTestManyArgs.c b/test/hotspot/jtreg/compiler/calls/libTestManyArgs.c new file mode 100644 index 00000000000..8836c79e43e --- /dev/null +++ b/test/hotspot/jtreg/compiler/calls/libTestManyArgs.c @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2024, Rivos Inc. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +#include "jni.h" + +#ifdef riscv64 +/* RV64 ABI pass all integers as 64-bit, in registers or on stack + * As compiler may choose to load smaller width than 64-bit if passed on stack, + * this test may not find any bugs. + * Therefore we trick the compiler todo 64-bit loads, + * by saying these args are jlongs. + */ +JNIEXPORT jint JNICALL Java_compiler_calls_TestManyArgs_checkargs(JNIEnv* env, jclass jclazz, + jlong arg0, jlong arg1, jlong arg2, + jlong arg3, jlong arg4, jlong arg5, + jlong arg6, jlong arg7, jlong arg8, + jlong arg9, jlong arg10, jlong arg11) +#else +JNIEXPORT jint JNICALL Java_compiler_calls_TestManyArgs_checkargs(JNIEnv* env, jclass jclazz, + jint arg0, jshort arg1, jbyte arg2, + jint arg3, jshort arg4, jbyte arg5, + jint arg6, jshort arg7, jbyte arg8, + jint arg9, jshort arg10, jbyte arg11) +#endif +{ + if (arg0 != 0xf) return 1; + if (arg1 != 0xf) return 1; + if (arg2 != 0xf) return 1; + if (arg3 != 0xf) return 1; + if (arg4 != 0xf) return 1; + if (arg5 != 0xf) return 1; + if (arg6 != 0xf) return 1; + if (arg7 != 0xf) return 1; + if (arg8 != 0xf) return 1; + if (arg9 != 0xf) return 1; + if (arg10 != 0xf) return 1; + if (arg11 != 0xf) return 1; + return 0; +} + +JNIEXPORT +void JNICALL Java_compiler_calls_TestManyArgs_scramblestack(JNIEnv* env, jclass jclazz) +{ + volatile char stack[12*8]; + for (unsigned int i = 0; i < sizeof(stack); i++) { + stack[i] = (char)0xff; + } +} diff --git a/test/hotspot/jtreg/compiler/ciReplay/CiReplayBase.java b/test/hotspot/jtreg/compiler/ciReplay/CiReplayBase.java index 260c8ddcc3e..356f549d231 100644 --- a/test/hotspot/jtreg/compiler/ciReplay/CiReplayBase.java +++ b/test/hotspot/jtreg/compiler/ciReplay/CiReplayBase.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -164,11 +164,11 @@ public boolean generateReplay(boolean needCoreDump, String... vmopts) { options.add("'" + TestMain.class.getName() + "'"); crashOut = ProcessTools.executeProcess( CoreUtils.addCoreUlimitCommand( - ProcessTools.createTestJvm(options.toArray(new String[0])))); + ProcessTools.createTestJavaProcessBuilder(options.toArray(new String[0])))); } else { options.add("-XX:CompileOnly=" + TestMain.class.getName() + "::" + getTestMethod()); options.add(TestMain.class.getName()); - crashOut = ProcessTools.executeProcess(ProcessTools.createTestJvm(options)); + crashOut = ProcessTools.executeProcess(ProcessTools.createTestJavaProcessBuilder(options)); } crashOutputString = crashOut.getOutput(); Asserts.assertNotEquals(crashOut.getExitValue(), 0, "Crash JVM exits gracefully"); @@ -271,7 +271,7 @@ public void nonTieredTests(int compLevel) { private String[] getTestJvmCommandlineWithPrefix(String prefix, String... args) { try { - String cmd = ProcessTools.getCommandLine(ProcessTools.createTestJvm(args)); + String cmd = ProcessTools.getCommandLine(ProcessTools.createTestJavaProcessBuilder(args)); return new String[]{"sh", "-c", prefix + (Platform.isWindows() ? cmd.replace('\\', '/').replace(";", "\\;").replace("|", "\\|") : cmd)}; } catch(Throwable t) { diff --git a/test/hotspot/jtreg/compiler/ciReplay/DumpReplayBase.java b/test/hotspot/jtreg/compiler/ciReplay/DumpReplayBase.java index 4d783993578..3597c0729a1 100644 --- a/test/hotspot/jtreg/compiler/ciReplay/DumpReplayBase.java +++ b/test/hotspot/jtreg/compiler/ciReplay/DumpReplayBase.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2021, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -79,7 +79,7 @@ public boolean generateReplay(String... vmopts) { options.add("-XX:CompileCommand=compileonly," + getTestClass() + "::" + getTestMethod()); options.add("-Xbatch"); options.add(getTestClass()); - oa = ProcessTools.executeProcess(ProcessTools.createTestJvm(options)); + oa = ProcessTools.executeProcess(ProcessTools.createTestJavaProcessBuilder(options)); Asserts.assertEquals(oa.getExitValue(), 0, "Crash JVM exits gracefully"); replayFiles = Files.list(Paths.get(".")) .map(Path::toFile) diff --git a/test/hotspot/jtreg/compiler/ciReplay/SABase.java b/test/hotspot/jtreg/compiler/ciReplay/SABase.java index db576d73631..66f2eb1106f 100644 --- a/test/hotspot/jtreg/compiler/ciReplay/SABase.java +++ b/test/hotspot/jtreg/compiler/ciReplay/SABase.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -71,7 +71,7 @@ public void testAction() { } ProcessBuilder pb; try { - pb = ProcessTools.createTestJvm("--add-modules", "jdk.hotspot.agent", + pb = ProcessTools.createTestJavaProcessBuilder("--add-modules", "jdk.hotspot.agent", "--add-exports=jdk.hotspot.agent/sun.jvm.hotspot=ALL-UNNAMED", "sun.jvm.hotspot.CLHSDB", JDKToolFinder.getTestJDKTool("java"), TEST_CORE_FILE_NAME); diff --git a/test/hotspot/jtreg/compiler/codecache/CheckCodeCacheInfo.java b/test/hotspot/jtreg/compiler/codecache/CheckCodeCacheInfo.java index 03fae1c3890..a9dd4b0b128 100644 --- a/test/hotspot/jtreg/compiler/codecache/CheckCodeCacheInfo.java +++ b/test/hotspot/jtreg/compiler/codecache/CheckCodeCacheInfo.java @@ -67,9 +67,9 @@ public class CheckCodeCacheInfo { public static void main(String[] args) throws Exception { ProcessBuilder pb; - pb = ProcessTools.createTestJvm("-XX:+PrintCodeCache", - "-XX:+Verbose", - "-version"); + pb = ProcessTools.createTestJavaProcessBuilder("-XX:+PrintCodeCache", + "-XX:+Verbose", + "-version"); OutputAnalyzer out = new OutputAnalyzer(pb.start()); out.shouldHaveExitValue(0); out.stdoutShouldMatch(VERBOSE_REGEXP); diff --git a/test/hotspot/jtreg/compiler/codecache/CheckLargePages.java b/test/hotspot/jtreg/compiler/codecache/CheckLargePages.java index 152ccb33cf0..5b6274681f7 100644 --- a/test/hotspot/jtreg/compiler/codecache/CheckLargePages.java +++ b/test/hotspot/jtreg/compiler/codecache/CheckLargePages.java @@ -50,7 +50,7 @@ public static void main(String[] args) throws Exception { final boolean largePages = WHITE_BOX.getBooleanVMFlag("UseLargePages"); final long largePageSize = WHITE_BOX.getVMLargePageSize(); if (largePages && (largePageSize == 1024 * 1024 * 1024)) { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:+UseLargePages", "-XX:+SegmentedCodeCache", "-XX:InitialCodeCacheSize=2g", diff --git a/test/hotspot/jtreg/compiler/codecache/CheckReservedInitialCodeCacheSizeArgOrder.java b/test/hotspot/jtreg/compiler/codecache/CheckReservedInitialCodeCacheSizeArgOrder.java index 63e7f83a303..f4a1cc3f0e7 100644 --- a/test/hotspot/jtreg/compiler/codecache/CheckReservedInitialCodeCacheSizeArgOrder.java +++ b/test/hotspot/jtreg/compiler/codecache/CheckReservedInitialCodeCacheSizeArgOrder.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2023, Oracle and/or its affiliates. All rights reserved. * 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,8 +42,8 @@ public static void main(String[] args) throws Exception { ProcessBuilder pb1, pb2; OutputAnalyzer out1, out2; - pb1 = ProcessTools.createJavaProcessBuilder("-XX:InitialCodeCacheSize=4m", "-XX:ReservedCodeCacheSize=8m", "-version"); - pb2 = ProcessTools.createJavaProcessBuilder("-XX:ReservedCodeCacheSize=8m", "-XX:InitialCodeCacheSize=4m", "-version"); + pb1 = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:InitialCodeCacheSize=4m", "-XX:ReservedCodeCacheSize=8m", "-version"); + pb2 = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:ReservedCodeCacheSize=8m", "-XX:InitialCodeCacheSize=4m", "-version"); out1 = new OutputAnalyzer(pb1.start()); out2 = new OutputAnalyzer(pb2.start()); diff --git a/test/hotspot/jtreg/compiler/codecache/CheckSegmentedCodeCache.java b/test/hotspot/jtreg/compiler/codecache/CheckSegmentedCodeCache.java index ae884a1fa8c..f79d7da7695 100644 --- a/test/hotspot/jtreg/compiler/codecache/CheckSegmentedCodeCache.java +++ b/test/hotspot/jtreg/compiler/codecache/CheckSegmentedCodeCache.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -89,80 +89,80 @@ public static void main(String[] args) throws Exception { ProcessBuilder pb; // Disabled with ReservedCodeCacheSize < 240MB - pb = ProcessTools.createJavaProcessBuilder("-XX:ReservedCodeCacheSize=239m", - "-XX:+PrintCodeCache", - "-version"); + pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:ReservedCodeCacheSize=239m", + "-XX:+PrintCodeCache", + "-version"); verifySegmentedCodeCache(pb, false); // Disabled without TieredCompilation - pb = ProcessTools.createJavaProcessBuilder("-XX:-TieredCompilation", - "-XX:+PrintCodeCache", - "-version"); + pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:-TieredCompilation", + "-XX:+PrintCodeCache", + "-version"); verifySegmentedCodeCache(pb, false); // Enabled with TieredCompilation and ReservedCodeCacheSize >= 240MB - pb = ProcessTools.createJavaProcessBuilder("-XX:+TieredCompilation", - "-XX:ReservedCodeCacheSize=240m", - "-XX:+PrintCodeCache", - "-version"); + pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:+TieredCompilation", + "-XX:ReservedCodeCacheSize=240m", + "-XX:+PrintCodeCache", + "-version"); verifySegmentedCodeCache(pb, true); - pb = ProcessTools.createJavaProcessBuilder("-XX:+TieredCompilation", - "-XX:ReservedCodeCacheSize=400m", - "-XX:+PrintCodeCache", - "-version"); + pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:+TieredCompilation", + "-XX:ReservedCodeCacheSize=400m", + "-XX:+PrintCodeCache", + "-version"); verifySegmentedCodeCache(pb, true); // Always enabled if SegmentedCodeCache is set - pb = ProcessTools.createJavaProcessBuilder("-XX:+SegmentedCodeCache", - "-XX:-TieredCompilation", - "-XX:ReservedCodeCacheSize=239m", - "-XX:+PrintCodeCache", - "-version"); + pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:+SegmentedCodeCache", + "-XX:-TieredCompilation", + "-XX:ReservedCodeCacheSize=239m", + "-XX:+PrintCodeCache", + "-version"); verifySegmentedCodeCache(pb, true); // The profiled and non-profiled code heaps should not be available in // interpreter-only mode - pb = ProcessTools.createJavaProcessBuilder("-XX:+SegmentedCodeCache", - "-Xint", - "-XX:+PrintCodeCache", - "-version"); + pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:+SegmentedCodeCache", + "-Xint", + "-XX:+PrintCodeCache", + "-version"); verifyCodeHeapNotExists(pb, PROFILED, NON_PROFILED); // If we stop compilation at CompLevel_none or CompLevel_simple we // don't need a profiled code heap. - pb = ProcessTools.createJavaProcessBuilder("-XX:+SegmentedCodeCache", - "-XX:TieredStopAtLevel=0", - "-XX:+PrintCodeCache", - "-version"); + pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:+SegmentedCodeCache", + "-XX:TieredStopAtLevel=0", + "-XX:+PrintCodeCache", + "-version"); verifyCodeHeapNotExists(pb, PROFILED); - pb = ProcessTools.createJavaProcessBuilder("-XX:+SegmentedCodeCache", - "-XX:TieredStopAtLevel=1", - "-XX:+PrintCodeCache", - "-version"); + pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:+SegmentedCodeCache", + "-XX:TieredStopAtLevel=1", + "-XX:+PrintCodeCache", + "-version"); verifyCodeHeapNotExists(pb, PROFILED); // Fails with too small non-nmethod code heap size - pb = ProcessTools.createJavaProcessBuilder("-XX:NonNMethodCodeHeapSize=100K", - "-version"); + pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:NonNMethodCodeHeapSize=100K", + "-version"); failsWith(pb, "Invalid NonNMethodCodeHeapSize"); // Fails if code heap sizes do not add up - pb = ProcessTools.createJavaProcessBuilder("-XX:+SegmentedCodeCache", - "-XX:ReservedCodeCacheSize=10M", - "-XX:NonNMethodCodeHeapSize=5M", - "-XX:ProfiledCodeHeapSize=5M", - "-XX:NonProfiledCodeHeapSize=5M", - "-version"); + pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:+SegmentedCodeCache", + "-XX:ReservedCodeCacheSize=10M", + "-XX:NonNMethodCodeHeapSize=5M", + "-XX:ProfiledCodeHeapSize=5M", + "-XX:NonProfiledCodeHeapSize=5M", + "-version"); failsWith(pb, "Invalid code heap sizes"); // Fails if not enough space for VM internal code long minUseSpace = WHITE_BOX.getUintxVMFlag("CodeCacheMinimumUseSpace"); // minimum size: CodeCacheMinimumUseSpace DEBUG_ONLY(* 3) long minSize = (Platform.isDebugBuild() ? 3 : 1) * minUseSpace; - pb = ProcessTools.createJavaProcessBuilder("-XX:+SegmentedCodeCache", - "-XX:ReservedCodeCacheSize=" + minSize, - "-XX:InitialCodeCacheSize=100K", - "-version"); + pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:+SegmentedCodeCache", + "-XX:ReservedCodeCacheSize=" + minSize, + "-XX:InitialCodeCacheSize=100K", + "-version"); failsWith(pb, "Not enough space in non-nmethod code heap to run VM"); } } diff --git a/test/hotspot/jtreg/compiler/codecache/CheckUpperLimit.java b/test/hotspot/jtreg/compiler/codecache/CheckUpperLimit.java index 9509da6cf32..7ec5e744dd6 100644 --- a/test/hotspot/jtreg/compiler/codecache/CheckUpperLimit.java +++ b/test/hotspot/jtreg/compiler/codecache/CheckUpperLimit.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2023, Oracle and/or its affiliates. All rights reserved. * 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,7 +41,7 @@ public static void main(String[] args) throws Exception { ProcessBuilder pb; OutputAnalyzer out; - pb = ProcessTools.createJavaProcessBuilder("-XX:ReservedCodeCacheSize=2049m", "-version"); + pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:ReservedCodeCacheSize=2049m", "-version"); out = new OutputAnalyzer(pb.start()); out.shouldContain("Invalid ReservedCodeCacheSize="); out.shouldHaveExitValue(1); diff --git a/test/hotspot/jtreg/compiler/codecache/CodeCacheFullCountTest.java b/test/hotspot/jtreg/compiler/codecache/CodeCacheFullCountTest.java index ff28c588b4c..dc1afa7b7c0 100644 --- a/test/hotspot/jtreg/compiler/codecache/CodeCacheFullCountTest.java +++ b/test/hotspot/jtreg/compiler/codecache/CodeCacheFullCountTest.java @@ -63,7 +63,7 @@ public static void wasteCodeCache() throws Throwable { } public static void runTest() throws Throwable { - ProcessBuilder pb = ProcessTools.createTestJvm( + ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder( "-XX:ReservedCodeCacheSize=2496k", "-XX:-UseCodeCacheFlushing", "CodeCacheFullCountTest", "WasteCodeCache"); OutputAnalyzer oa = ProcessTools.executeProcess(pb); // Ignore adapter creation failures diff --git a/test/hotspot/jtreg/compiler/cpuflags/RestoreMXCSR.java b/test/hotspot/jtreg/compiler/cpuflags/RestoreMXCSR.java index 176d23409af..fa748cb21ac 100644 --- a/test/hotspot/jtreg/compiler/cpuflags/RestoreMXCSR.java +++ b/test/hotspot/jtreg/compiler/cpuflags/RestoreMXCSR.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2023, Oracle and/or its affiliates. All rights reserved. * 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,7 +41,7 @@ public static void main(String[] args) throws Exception { ProcessBuilder pb; OutputAnalyzer out; - pb = ProcessTools.createJavaProcessBuilder("-XX:+RestoreMXCSROnJNICalls", "-version"); + pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:+RestoreMXCSROnJNICalls", "-version"); out = new OutputAnalyzer(pb.start()); out.shouldHaveExitValue(0); } diff --git a/test/hotspot/jtreg/compiler/debug/TestGenerateStressSeed.java b/test/hotspot/jtreg/compiler/debug/TestGenerateStressSeed.java index 3020bf1df34..f03667a55ce 100644 --- a/test/hotspot/jtreg/compiler/debug/TestGenerateStressSeed.java +++ b/test/hotspot/jtreg/compiler/debug/TestGenerateStressSeed.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2020, 2023, Oracle and/or its affiliates. All rights reserved. * 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,7 +58,7 @@ public static void main(String[] args) throws Exception { "-Xcomp", "-XX:-TieredCompilation", "-XX:+UnlockDiagnosticVMOptions", "-XX:CompileOnly=" + className + "::sum", "-XX:+" + stressOpt, "-XX:+LogCompilation", "-XX:LogFile=" + log, className, "10"}; - new OutputAnalyzer(ProcessTools.createJavaProcessBuilder(procArgs).start()) + new OutputAnalyzer(ProcessTools.createLimitedTestJavaProcessBuilder(procArgs).start()) .shouldHaveExitValue(0); new OutputAnalyzer(Paths.get(log)) .shouldContain("stress_test seed"); diff --git a/test/hotspot/jtreg/compiler/debug/TestStressCM.java b/test/hotspot/jtreg/compiler/debug/TestStressCM.java index 4b3bd786595..0fb624bc16f 100644 --- a/test/hotspot/jtreg/compiler/debug/TestStressCM.java +++ b/test/hotspot/jtreg/compiler/debug/TestStressCM.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2020, 2023, Oracle and/or its affiliates. All rights reserved. * 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,7 +48,7 @@ static String cmTrace(String stressOpt, int stressSeed) throws Exception { "-XX:CompileOnly=" + className + "::sum", "-XX:+TraceOptoPipelining", "-XX:+" + stressOpt, "-XX:StressSeed=" + stressSeed, className, "10"}; - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(procArgs); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(procArgs); OutputAnalyzer out = new OutputAnalyzer(pb.start()); out.shouldHaveExitValue(0); // Extract the trace of our method (the last one after those of all diff --git a/test/hotspot/jtreg/compiler/debug/TestStressIGVNAndCCP.java b/test/hotspot/jtreg/compiler/debug/TestStressIGVNAndCCP.java index e1f7e1fa447..0f820de47de 100644 --- a/test/hotspot/jtreg/compiler/debug/TestStressIGVNAndCCP.java +++ b/test/hotspot/jtreg/compiler/debug/TestStressIGVNAndCCP.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2020, 2023, Oracle and/or its affiliates. All rights reserved. * 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,7 +48,7 @@ static String phaseTrace(String stressOption, String traceOption, "-XX:CompileOnly=" + className + "::sum", "-XX:+" + traceOption, "-XX:+" + stressOption, "-XX:StressSeed=" + stressSeed, className, "10"}; - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(procArgs); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(procArgs); OutputAnalyzer out = new OutputAnalyzer(pb.start()); out.shouldHaveExitValue(0); return out.getStdout(); diff --git a/test/hotspot/jtreg/compiler/debug/VerifyAdapterSharing.java b/test/hotspot/jtreg/compiler/debug/VerifyAdapterSharing.java index 00ec0291131..89da61a5763 100644 --- a/test/hotspot/jtreg/compiler/debug/VerifyAdapterSharing.java +++ b/test/hotspot/jtreg/compiler/debug/VerifyAdapterSharing.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -42,7 +42,7 @@ public static void main(String[] args) throws Exception { ProcessBuilder pb; OutputAnalyzer out; - pb = ProcessTools.createJavaProcessBuilder("-Xcomp", "-XX:+IgnoreUnrecognizedVMOptions", + pb = ProcessTools.createLimitedTestJavaProcessBuilder("-Xcomp", "-XX:+IgnoreUnrecognizedVMOptions", "-XX:+VerifyAdapterSharing", "-version"); out = new OutputAnalyzer(pb.start()); out.shouldHaveExitValue(0); diff --git a/test/hotspot/jtreg/compiler/eliminateAutobox/TestEliminateBoxInDebugInfo.java b/test/hotspot/jtreg/compiler/eliminateAutobox/TestEliminateBoxInDebugInfo.java index 46e50f5365a..f35e026cb60 100644 --- a/test/hotspot/jtreg/compiler/eliminateAutobox/TestEliminateBoxInDebugInfo.java +++ b/test/hotspot/jtreg/compiler/eliminateAutobox/TestEliminateBoxInDebugInfo.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2021, 2024, Huawei Technologies Co., Ltd. All rights reserved. * 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 @@ public static void runTest() throws Exception { "-XX:+PrintEliminateAllocations", Test.class.getName() }; - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(arguments); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(arguments); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldHaveExitValue(0) .stdoutShouldContain("++++ Eliminated: "); diff --git a/test/hotspot/jtreg/compiler/inlining/InlineAccessors.java b/test/hotspot/jtreg/compiler/inlining/InlineAccessors.java index 0d4da50cfc5..934a13c97aa 100644 --- a/test/hotspot/jtreg/compiler/inlining/InlineAccessors.java +++ b/test/hotspot/jtreg/compiler/inlining/InlineAccessors.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2023, Oracle and/or its affiliates. All rights reserved. * 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,7 +38,7 @@ public class InlineAccessors { public static void main(String[] args) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:+IgnoreUnrecognizedVMOptions", "-showversion", "-server", "-XX:-TieredCompilation", "-Xbatch", "-XX:+PrintCompilation", "-XX:+UnlockDiagnosticVMOptions", "-XX:+PrintInlining", diff --git a/test/hotspot/jtreg/compiler/inlining/PrintInlining.java b/test/hotspot/jtreg/compiler/inlining/PrintInlining.java index a0975dee673..768fa90965d 100644 --- a/test/hotspot/jtreg/compiler/inlining/PrintInlining.java +++ b/test/hotspot/jtreg/compiler/inlining/PrintInlining.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2020, 2023, Oracle and/or its affiliates. All rights reserved. * 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,7 +40,7 @@ public class PrintInlining { static void test(String option) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:+IgnoreUnrecognizedVMOptions", "-showversion", "-server", "-XX:-TieredCompilation", "-Xbatch", "-XX:-UseOnStackReplacement", "-XX:CompileCommand=dontinline,*::bar", diff --git a/test/hotspot/jtreg/compiler/inlining/ResolvedClassTest.java b/test/hotspot/jtreg/compiler/inlining/ResolvedClassTest.java index 92263bf10cf..50711d9da6f 100644 --- a/test/hotspot/jtreg/compiler/inlining/ResolvedClassTest.java +++ b/test/hotspot/jtreg/compiler/inlining/ResolvedClassTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -42,7 +42,7 @@ public class ResolvedClassTest { /* ======================================================================== */ static void testStatic() throws IOException { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:+IgnoreUnrecognizedVMOptions", "-showversion", "-XX:+PrintCompilation", "-XX:+UnlockDiagnosticVMOptions", "-XX:+PrintInlining", "-Xbatch", "-XX:CompileCommand=quiet", "-XX:CompileCommand=compileonly," + TestStatic.class.getName() + "::test", @@ -78,7 +78,7 @@ public static void main(String[] args) { /* ======================================================================== */ static void testStaticInit() throws IOException { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:+IgnoreUnrecognizedVMOptions", "-showversion", "-XX:+PrintCompilation", "-XX:+UnlockDiagnosticVMOptions", "-XX:+PrintInlining", "-Xbatch", "-XX:CompileCommand=quiet", "-XX:CompileCommand=compileonly," + TestStaticInit.class.getName() + "::test", @@ -115,7 +115,7 @@ public static void main(String[] args) { /* ======================================================================== */ static void testIndy() throws IOException { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:+IgnoreUnrecognizedVMOptions", "-showversion", "-XX:+PrintCompilation", "-XX:+UnlockDiagnosticVMOptions", "-XX:+PrintInlining", "-Xbatch", "-XX:CompileCommand=quiet", "-XX:CompileCommand=compileonly," + TestIndy.class.getName() + "::test", diff --git a/test/hotspot/jtreg/compiler/intrinsics/sha/cli/TestUseSHA3IntrinsicsOptionOnSupportedCPU.java b/test/hotspot/jtreg/compiler/intrinsics/sha/cli/TestUseSHA3IntrinsicsOptionOnSupportedCPU.java index a5789896aff..3706f3abfd8 100644 --- a/test/hotspot/jtreg/compiler/intrinsics/sha/cli/TestUseSHA3IntrinsicsOptionOnSupportedCPU.java +++ b/test/hotspot/jtreg/compiler/intrinsics/sha/cli/TestUseSHA3IntrinsicsOptionOnSupportedCPU.java @@ -28,6 +28,10 @@ * @summary Verify UseSHA3Intrinsics option processing on supported CPU. * @library /test/lib / * @requires vm.flagless + * @requires os.arch == "aarch64" & os.family == "mac" + * @comment sha3 is only implemented on AArch64 for now. + * UseSHA3Intrinsics is only auto-enabled on Apple silicon, because it + * may introduce performance regression on others. See JDK-8297092. * * @build jdk.test.whitebox.WhiteBox * @run driver jdk.test.lib.helpers.ClassFileInstaller jdk.test.whitebox.WhiteBox diff --git a/test/hotspot/jtreg/compiler/jsr292/ContinuousCallSiteTargetChange.java b/test/hotspot/jtreg/compiler/jsr292/ContinuousCallSiteTargetChange.java index b0c05f8a371..db7e211ece2 100644 --- a/test/hotspot/jtreg/compiler/jsr292/ContinuousCallSiteTargetChange.java +++ b/test/hotspot/jtreg/compiler/jsr292/ContinuousCallSiteTargetChange.java @@ -61,7 +61,7 @@ static void runTest(Class test, String... extraArgs) throws Exception { argsList.add(test.getName()); argsList.add(Integer.toString(ITERATIONS)); - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(argsList); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(argsList); OutputAnalyzer analyzer = new OutputAnalyzer(pb.start()); diff --git a/test/hotspot/jtreg/compiler/jsr292/MHInlineTest.java b/test/hotspot/jtreg/compiler/jsr292/MHInlineTest.java index a2358cb6edc..a8e76f5797d 100644 --- a/test/hotspot/jtreg/compiler/jsr292/MHInlineTest.java +++ b/test/hotspot/jtreg/compiler/jsr292/MHInlineTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2023, Oracle and/or its affiliates. All rights reserved. * 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 MHInlineTest { public static void main(String[] args) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:+IgnoreUnrecognizedVMOptions", "-showversion", "-XX:-TieredCompilation", "-Xbatch", "-XX:+PrintCompilation", "-XX:+UnlockDiagnosticVMOptions", "-XX:+PrintInlining", diff --git a/test/hotspot/jtreg/compiler/jsr292/NonInlinedCall/Agent.java b/test/hotspot/jtreg/compiler/jsr292/NonInlinedCall/Agent.java index 32f29dff973..76b66f9bc1e 100644 --- a/test/hotspot/jtreg/compiler/jsr292/NonInlinedCall/Agent.java +++ b/test/hotspot/jtreg/compiler/jsr292/NonInlinedCall/Agent.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2024, Oracle and/or its affiliates. All rights reserved. * 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,6 +25,7 @@ import jdk.test.lib.JDKToolLauncher; import jdk.test.lib.process.OutputAnalyzer; +import jdk.test.lib.process.ProcessTools; import java.io.File; import java.io.PrintStream; @@ -51,8 +52,7 @@ public static void main(String[] args) throws Exception { System.out.println("Running jar " + Arrays.toString(jar.getCommand())); - ProcessBuilder pb = new ProcessBuilder(jar.getCommand()); - OutputAnalyzer output = new OutputAnalyzer(pb.start()); + OutputAnalyzer output = ProcessTools.executeProcess(jar.getCommand()); output.shouldHaveExitValue(0); } } diff --git a/test/hotspot/jtreg/compiler/jsr292/PollutedTrapCounts.java b/test/hotspot/jtreg/compiler/jsr292/PollutedTrapCounts.java index 6e060c5a375..b43a6f33a1e 100644 --- a/test/hotspot/jtreg/compiler/jsr292/PollutedTrapCounts.java +++ b/test/hotspot/jtreg/compiler/jsr292/PollutedTrapCounts.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -43,7 +43,7 @@ public class PollutedTrapCounts { public static void main(String[] args) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:+IgnoreUnrecognizedVMOptions", "-XX:-TieredCompilation", "-Xbatch", "-XX:PerBytecodeRecompilationCutoff=10", "-XX:PerMethodRecompilationCutoff=10", diff --git a/test/hotspot/jtreg/compiler/jvmci/TestEnableJVMCIProduct.java b/test/hotspot/jtreg/compiler/jvmci/TestEnableJVMCIProduct.java index 85471c120b8..b5eb78ca9b4 100644 --- a/test/hotspot/jtreg/compiler/jvmci/TestEnableJVMCIProduct.java +++ b/test/hotspot/jtreg/compiler/jvmci/TestEnableJVMCIProduct.java @@ -73,7 +73,7 @@ public static void main(String[] args) throws Exception { } static void test(String explicitFlag, Expectation... expectations) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:+UnlockExperimentalVMOptions", "-XX:+EnableJVMCIProduct", "-XX:-UnlockExperimentalVMOptions", explicitFlag, "-XX:+PrintFlagsFinal", "-version"); diff --git a/test/hotspot/jtreg/compiler/jvmci/TestInvalidJVMCIOption.java b/test/hotspot/jtreg/compiler/jvmci/TestInvalidJVMCIOption.java index 0cffca55dc4..1fec1eeb278 100644 --- a/test/hotspot/jtreg/compiler/jvmci/TestInvalidJVMCIOption.java +++ b/test/hotspot/jtreg/compiler/jvmci/TestInvalidJVMCIOption.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2020, 2023, Oracle and/or its affiliates. All rights reserved. * 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,7 +38,7 @@ public class TestInvalidJVMCIOption { public static void main(String[] args) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:+UnlockExperimentalVMOptions", "-XX:+EagerJVMCI", "-XX:+UseJVMCICompiler", diff --git a/test/hotspot/jtreg/compiler/jvmci/TestJVMCIPrintProperties.java b/test/hotspot/jtreg/compiler/jvmci/TestJVMCIPrintProperties.java index 16eb6dfb8f9..4e4a013db40 100644 --- a/test/hotspot/jtreg/compiler/jvmci/TestJVMCIPrintProperties.java +++ b/test/hotspot/jtreg/compiler/jvmci/TestJVMCIPrintProperties.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -42,7 +42,7 @@ public static void main(String[] args) throws Exception { } static void test(String enableFlag) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:+UnlockExperimentalVMOptions", enableFlag, "-Djvmci.Compiler=null", "-XX:+JVMCIPrintProperties"); diff --git a/test/hotspot/jtreg/compiler/jvmci/compilerToVM/GetFlagValueTest.java b/test/hotspot/jtreg/compiler/jvmci/compilerToVM/GetFlagValueTest.java index dba434d6d84..aa9252d4665 100644 --- a/test/hotspot/jtreg/compiler/jvmci/compilerToVM/GetFlagValueTest.java +++ b/test/hotspot/jtreg/compiler/jvmci/compilerToVM/GetFlagValueTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2023, Oracle and/or its affiliates. All rights reserved. * 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,7 +63,7 @@ public static void main(String[] args) throws Exception { ProcessBuilder pb; OutputAnalyzer out; - pb = ProcessTools.createJavaProcessBuilder( + pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:+UnlockExperimentalVMOptions", "-XX:+EnableJVMCI", "-XX:+PrintFlagsFinal", diff --git a/test/hotspot/jtreg/compiler/lib/ir_framework/driver/TestVMProcess.java b/test/hotspot/jtreg/compiler/lib/ir_framework/driver/TestVMProcess.java index fa3686dad1e..771f18d6b96 100644 --- a/test/hotspot/jtreg/compiler/lib/ir_framework/driver/TestVMProcess.java +++ b/test/hotspot/jtreg/compiler/lib/ir_framework/driver/TestVMProcess.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2021, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -146,7 +146,7 @@ private static String[] getVerifyFlags() { } private void start() { - ProcessBuilder process = ProcessTools.createJavaProcessBuilder(cmds); + ProcessBuilder process = ProcessTools.createLimitedTestJavaProcessBuilder(cmds); try { // Calls 'main' of TestVM to run all specified tests with commands 'cmds'. // Use executeProcess instead of executeTestJvm as we have already added the JTreg VM and diff --git a/test/hotspot/jtreg/compiler/linkage/TestLinkageErrorInGenerateOopMap.java b/test/hotspot/jtreg/compiler/linkage/TestLinkageErrorInGenerateOopMap.java index d61fc44dad4..ad02dd617a7 100644 --- a/test/hotspot/jtreg/compiler/linkage/TestLinkageErrorInGenerateOopMap.java +++ b/test/hotspot/jtreg/compiler/linkage/TestLinkageErrorInGenerateOopMap.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2023, Oracle and/or its affiliates. All rights reserved. * 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,7 +41,7 @@ public class TestLinkageErrorInGenerateOopMap { public static void main(String args[]) throws Exception { if (args.length == 0) { // Spawn new VM instance to execute test - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:+UnlockDiagnosticVMOptions", "-XX:-BytecodeVerificationRemote", "-XX:-BytecodeVerificationLocal", diff --git a/test/hotspot/jtreg/compiler/loopstripmining/CheckLoopStripMiningIterShortLoop.java b/test/hotspot/jtreg/compiler/loopstripmining/CheckLoopStripMiningIterShortLoop.java index ecceaa4c4b7..80c046e7a36 100644 --- a/test/hotspot/jtreg/compiler/loopstripmining/CheckLoopStripMiningIterShortLoop.java +++ b/test/hotspot/jtreg/compiler/loopstripmining/CheckLoopStripMiningIterShortLoop.java @@ -37,7 +37,7 @@ public class CheckLoopStripMiningIterShortLoop { public static void main(String[] args) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-XX:+UseG1GC", "-XX:+PrintFlagsFinal", "-version"); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:+UseG1GC", "-XX:+PrintFlagsFinal", "-version"); OutputAnalyzer out = new OutputAnalyzer(pb.start()); out.shouldHaveExitValue(0); diff --git a/test/hotspot/jtreg/compiler/loopstripmining/TestNoWarningLoopStripMiningIterSet.java b/test/hotspot/jtreg/compiler/loopstripmining/TestNoWarningLoopStripMiningIterSet.java index b4ce601be11..c7fedf8982e 100644 --- a/test/hotspot/jtreg/compiler/loopstripmining/TestNoWarningLoopStripMiningIterSet.java +++ b/test/hotspot/jtreg/compiler/loopstripmining/TestNoWarningLoopStripMiningIterSet.java @@ -83,7 +83,7 @@ public static void testWith(Consumer check, String msg, boolean System.arraycopy(args, 0, cmds, 1, args.length); cmds[args.length + 1] = "-XX:+PrintFlagsFinal"; cmds[args.length + 2] = "-version"; - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(cmds); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(cmds); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldHaveExitValue(0); diff --git a/test/hotspot/jtreg/compiler/onSpinWait/TestOnSpinWait.java b/test/hotspot/jtreg/compiler/onSpinWait/TestOnSpinWait.java index 66cf04fd62f..d5318a7bba4 100644 --- a/test/hotspot/jtreg/compiler/onSpinWait/TestOnSpinWait.java +++ b/test/hotspot/jtreg/compiler/onSpinWait/TestOnSpinWait.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2023, Oracle and/or its affiliates. All rights reserved. * Copyright 2016 Azul Systems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -43,7 +43,7 @@ public class TestOnSpinWait { public static void main(String[] args) throws Exception { // Test C2 compiler - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:+IgnoreUnrecognizedVMOptions", "-showversion", "-XX:-TieredCompilation", "-Xbatch", "-XX:+PrintCompilation", "-XX:+UnlockDiagnosticVMOptions", diff --git a/test/hotspot/jtreg/compiler/onSpinWait/TestOnSpinWaitAArch64.java b/test/hotspot/jtreg/compiler/onSpinWait/TestOnSpinWaitAArch64.java index 4a66246abe7..dd5be3ffb3a 100644 --- a/test/hotspot/jtreg/compiler/onSpinWait/TestOnSpinWaitAArch64.java +++ b/test/hotspot/jtreg/compiler/onSpinWait/TestOnSpinWaitAArch64.java @@ -71,7 +71,7 @@ public static void main(String[] args) throws Exception { command.add("-XX:CompileCommand=compileonly," + Launcher.class.getName() + "::" + "test"); command.add(Launcher.class.getName()); - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(command); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(command); OutputAnalyzer analyzer = new OutputAnalyzer(pb.start()); diff --git a/test/hotspot/jtreg/compiler/onSpinWait/TestOnSpinWaitAArch64DefaultFlags.java b/test/hotspot/jtreg/compiler/onSpinWait/TestOnSpinWaitAArch64DefaultFlags.java index f722bf50de1..09cb2bf0cf8 100644 --- a/test/hotspot/jtreg/compiler/onSpinWait/TestOnSpinWaitAArch64DefaultFlags.java +++ b/test/hotspot/jtreg/compiler/onSpinWait/TestOnSpinWaitAArch64DefaultFlags.java @@ -87,9 +87,9 @@ public static void main(String[] args) throws Exception { final String cpuModel = cpuFeatures.get(0); if (isCPUModelNeoverseN1(cpuModel)) { - checkFinalFlagsEqualTo(ProcessTools.createJavaProcessBuilder("-XX:+UnlockDiagnosticVMOptions", "-XX:+PrintFlagsFinal", "-version"), + checkFinalFlagsEqualTo(ProcessTools.createLimitedTestJavaProcessBuilder("-XX:+UnlockDiagnosticVMOptions", "-XX:+PrintFlagsFinal", "-version"), "isb", "1"); - checkFinalFlagsEqualTo(ProcessTools.createJavaProcessBuilder("-XX:+UnlockDiagnosticVMOptions", "-XX:OnSpinWaitInstCount=2", "-XX:+PrintFlagsFinal", "-version"), + checkFinalFlagsEqualTo(ProcessTools.createLimitedTestJavaProcessBuilder("-XX:+UnlockDiagnosticVMOptions", "-XX:OnSpinWaitInstCount=2", "-XX:+PrintFlagsFinal", "-version"), "isb", "2"); } else { System.out.println("Skip because no defaults for CPU model: " + cpuModel); diff --git a/test/hotspot/jtreg/compiler/onSpinWait/TestOnSpinWaitC1.java b/test/hotspot/jtreg/compiler/onSpinWait/TestOnSpinWaitC1.java index fde38cf858e..380a8185084 100644 --- a/test/hotspot/jtreg/compiler/onSpinWait/TestOnSpinWaitC1.java +++ b/test/hotspot/jtreg/compiler/onSpinWait/TestOnSpinWaitC1.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2023, Oracle and/or its affiliates. All rights reserved. * Copyright 2016 Azul Systems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -45,7 +45,7 @@ public class TestOnSpinWaitC1 { public static void main(String[] args) throws Exception { // Test C1 compiler - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:+IgnoreUnrecognizedVMOptions", "-showversion", "-XX:+TieredCompilation", "-XX:TieredStopAtLevel=1", "-Xbatch", "-XX:+PrintCompilation", "-XX:+UnlockDiagnosticVMOptions", diff --git a/test/hotspot/jtreg/compiler/onSpinWait/TestOnSpinWaitNoneAArch64.java b/test/hotspot/jtreg/compiler/onSpinWait/TestOnSpinWaitNoneAArch64.java index 7b759f605a8..73565eb96b1 100644 --- a/test/hotspot/jtreg/compiler/onSpinWait/TestOnSpinWaitNoneAArch64.java +++ b/test/hotspot/jtreg/compiler/onSpinWait/TestOnSpinWaitNoneAArch64.java @@ -54,7 +54,7 @@ public static void main(String[] args) throws Exception { command.add(Launcher.class.getName()); // Test C2 compiler - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(command); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(command); OutputAnalyzer analyzer = new OutputAnalyzer(pb.start()); diff --git a/test/hotspot/jtreg/compiler/oracle/CheckCompileCommandOption.java b/test/hotspot/jtreg/compiler/oracle/CheckCompileCommandOption.java index 91ae4880527..02043d19001 100644 --- a/test/hotspot/jtreg/compiler/oracle/CheckCompileCommandOption.java +++ b/test/hotspot/jtreg/compiler/oracle/CheckCompileCommandOption.java @@ -251,7 +251,7 @@ private static void verifyValidOption(String[] arguments, String[] expected_outp ProcessBuilder pb; OutputAnalyzer out; - pb = ProcessTools.createJavaProcessBuilder(arguments); + pb = ProcessTools.createLimitedTestJavaProcessBuilder(arguments); out = new OutputAnalyzer(pb.start()); for (String expected_output : expected_outputs) { @@ -266,7 +266,7 @@ private static void verifyInvalidOption(String[] arguments) throws Exception { ProcessBuilder pb; OutputAnalyzer out; - pb = ProcessTools.createJavaProcessBuilder(arguments); + pb = ProcessTools.createLimitedTestJavaProcessBuilder(arguments); out = new OutputAnalyzer(pb.start()); out.shouldContain("CompileCommand: An error occurred during parsing"); @@ -277,7 +277,7 @@ private static void verifyInvalidOption(String[] arguments, String[] expected_ou ProcessBuilder pb; OutputAnalyzer out; - pb = ProcessTools.createJavaProcessBuilder(arguments); + pb = ProcessTools.createLimitedTestJavaProcessBuilder(arguments); out = new OutputAnalyzer(pb.start()); for (String expected_output : expected_outputs) { diff --git a/test/hotspot/jtreg/compiler/oracle/TestCompileCommand.java b/test/hotspot/jtreg/compiler/oracle/TestCompileCommand.java index 0279843b590..6cb80d0a0e3 100644 --- a/test/hotspot/jtreg/compiler/oracle/TestCompileCommand.java +++ b/test/hotspot/jtreg/compiler/oracle/TestCompileCommand.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -56,7 +56,7 @@ private static void verifyValidOption(String[] arguments, String[] expected_outp ProcessBuilder pb; OutputAnalyzer out; - pb = ProcessTools.createJavaProcessBuilder(arguments); + pb = ProcessTools.createLimitedTestJavaProcessBuilder(arguments); out = new OutputAnalyzer(pb.start()); for (String expected_output : expected_outputs) { diff --git a/test/hotspot/jtreg/compiler/oracle/TestInvalidCompileCommand.java b/test/hotspot/jtreg/compiler/oracle/TestInvalidCompileCommand.java index 43a7e2aefd9..9d306908766 100644 --- a/test/hotspot/jtreg/compiler/oracle/TestInvalidCompileCommand.java +++ b/test/hotspot/jtreg/compiler/oracle/TestInvalidCompileCommand.java @@ -82,7 +82,7 @@ private static void verifyInvalidOption(String[] arguments, String[] expected_ou ProcessBuilder pb; OutputAnalyzer out; - pb = ProcessTools.createJavaProcessBuilder(arguments); + pb = ProcessTools.createLimitedTestJavaProcessBuilder(arguments); out = new OutputAnalyzer(pb.start()); for (String expected_output : expected_outputs) { diff --git a/test/hotspot/jtreg/compiler/profiling/spectrapredefineclass/Launcher.java b/test/hotspot/jtreg/compiler/profiling/spectrapredefineclass/Launcher.java index 85d5f2b96d5..1a8ed4c7893 100644 --- a/test/hotspot/jtreg/compiler/profiling/spectrapredefineclass/Launcher.java +++ b/test/hotspot/jtreg/compiler/profiling/spectrapredefineclass/Launcher.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2024, Oracle and/or its affiliates. All rights reserved. * 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,6 +41,7 @@ import jdk.test.lib.JDKToolLauncher; import jdk.test.lib.process.OutputAnalyzer; +import jdk.test.lib.process.ProcessTools; import java.io.File; import java.io.IOException; @@ -60,11 +61,10 @@ public static void main(String[] args) throws Exception { .addToolArg(Agent.AGENT_JAR) .addToolArg(Agent.class.getName().replace('.', File.separatorChar) + ".class"); - ProcessBuilder pb = new ProcessBuilder(jar.getCommand()); try { - OutputAnalyzer output = new OutputAnalyzer(pb.start()); + OutputAnalyzer output = ProcessTools.executeProcess(jar.getCommand()); output.shouldHaveExitValue(0); - } catch (IOException ex) { + } catch (Exception ex) { throw new Error("TESTBUG: jar failed.", ex); } } diff --git a/test/hotspot/jtreg/compiler/profiling/spectrapredefineclass_classloaders/Launcher.java b/test/hotspot/jtreg/compiler/profiling/spectrapredefineclass_classloaders/Launcher.java index 2489e62bdb1..08765e911c0 100644 --- a/test/hotspot/jtreg/compiler/profiling/spectrapredefineclass_classloaders/Launcher.java +++ b/test/hotspot/jtreg/compiler/profiling/spectrapredefineclass_classloaders/Launcher.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -44,6 +44,7 @@ import jdk.test.lib.JDKToolLauncher; import jdk.test.lib.process.OutputAnalyzer; +import jdk.test.lib.process.ProcessTools; import java.io.File; import java.io.IOException; @@ -63,11 +64,10 @@ public static void main(String[] args) throws Exception { .addToolArg(Agent.AGENT_JAR) .addToolArg(Agent.class.getName().replace('.', File.separatorChar) + ".class"); - ProcessBuilder pb = new ProcessBuilder(jar.getCommand()); try { - OutputAnalyzer output = new OutputAnalyzer(pb.start()); + OutputAnalyzer output = ProcessTools.executeProcess(jar.getCommand()); output.shouldHaveExitValue(0); - } catch (IOException ex) { + } catch (Exception ex) { throw new Error("TESTBUG: jar failed.", ex); } } diff --git a/test/hotspot/jtreg/compiler/runtime/cr8015436/Driver8015436.java b/test/hotspot/jtreg/compiler/runtime/cr8015436/Driver8015436.java index 36f4266c7d5..bdf221b84c6 100644 --- a/test/hotspot/jtreg/compiler/runtime/cr8015436/Driver8015436.java +++ b/test/hotspot/jtreg/compiler/runtime/cr8015436/Driver8015436.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -30,7 +30,7 @@ public class Driver8015436 { public static void main(String args[]) { OutputAnalyzer oa; try { - oa = ProcessTools.executeProcess(ProcessTools.createTestJvm( + oa = ProcessTools.executeProcess(ProcessTools.createTestJavaProcessBuilder( Test8015436.class.getName())); } catch (Exception ex) { throw new Error("TESTBUG: exception while running child process: " + ex, ex); diff --git a/test/hotspot/jtreg/compiler/startup/NumCompilerThreadsCheck.java b/test/hotspot/jtreg/compiler/startup/NumCompilerThreadsCheck.java index 9761002c051..679f7ff8d0b 100644 --- a/test/hotspot/jtreg/compiler/startup/NumCompilerThreadsCheck.java +++ b/test/hotspot/jtreg/compiler/startup/NumCompilerThreadsCheck.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -42,7 +42,7 @@ public class NumCompilerThreadsCheck { public static void main(String[] args) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-XX:CICompilerCount=-1"); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:CICompilerCount=-1"); OutputAnalyzer out = new OutputAnalyzer(pb.start()); String expectedOutput = "outside the allowed range"; diff --git a/test/hotspot/jtreg/compiler/startup/SmallCodeCacheStartup.java b/test/hotspot/jtreg/compiler/startup/SmallCodeCacheStartup.java index b32c4d48f8a..b3b92afa0d1 100644 --- a/test/hotspot/jtreg/compiler/startup/SmallCodeCacheStartup.java +++ b/test/hotspot/jtreg/compiler/startup/SmallCodeCacheStartup.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -44,10 +44,10 @@ public class SmallCodeCacheStartup { public static void main(String[] args) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-XX:ReservedCodeCacheSize=3m", - "-XX:CICompilerCount=64", - "-Xcomp", - "-version"); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:ReservedCodeCacheSize=3m", + "-XX:CICompilerCount=64", + "-Xcomp", + "-version"); OutputAnalyzer analyzer = new OutputAnalyzer(pb.start()); try { analyzer.shouldHaveExitValue(0); diff --git a/test/hotspot/jtreg/compiler/startup/StartupOutput.java b/test/hotspot/jtreg/compiler/startup/StartupOutput.java index 0f9ab3b1f96..d97bcd0019a 100644 --- a/test/hotspot/jtreg/compiler/startup/StartupOutput.java +++ b/test/hotspot/jtreg/compiler/startup/StartupOutput.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -43,12 +43,12 @@ public static void main(String[] args) throws Exception { ProcessBuilder pb; OutputAnalyzer out; - pb = ProcessTools.createJavaProcessBuilder("-Xint", "-XX:+DisplayVMOutputToStdout", "-version"); + pb = ProcessTools.createLimitedTestJavaProcessBuilder("-Xint", "-XX:+DisplayVMOutputToStdout", "-version"); out = new OutputAnalyzer(pb.start()); out.shouldNotContain("no space to run compilers"); out.shouldHaveExitValue(0); - pb = ProcessTools.createJavaProcessBuilder("-Xint", "-XX:ReservedCodeCacheSize=1770K", "-XX:InitialCodeCacheSize=4K", "-version"); + pb = ProcessTools.createLimitedTestJavaProcessBuilder("-Xint", "-XX:ReservedCodeCacheSize=1770K", "-XX:InitialCodeCacheSize=4K", "-version"); out = new OutputAnalyzer(pb.start()); // The VM should not crash but may return an error message because we don't have enough space for adapters int exitCode = out.getExitValue(); diff --git a/test/hotspot/jtreg/compiler/testlibrary/rtm/RTMTestBase.java b/test/hotspot/jtreg/compiler/testlibrary/rtm/RTMTestBase.java index 40369000036..b6535e65428 100644 --- a/test/hotspot/jtreg/compiler/testlibrary/rtm/RTMTestBase.java +++ b/test/hotspot/jtreg/compiler/testlibrary/rtm/RTMTestBase.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2023, Oracle and/or its affiliates. All rights reserved. * 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,7 +63,7 @@ public class RTMTestBase { public static OutputAnalyzer executeRTMTest(CompilableTest test, String... options) throws Exception { ProcessBuilder processBuilder - = ProcessTools.createJavaProcessBuilder( + = ProcessTools.createLimitedTestJavaProcessBuilder( RTMTestBase.prepareTestOptions(test, options)); OutputAnalyzer outputAnalyzer = new OutputAnalyzer(processBuilder.start()); @@ -83,7 +83,7 @@ public static OutputAnalyzer executeRTMTest(CompilableTest test, public static OutputAnalyzer executeRTMTest(String logFileName, CompilableTest test, String... options) throws Exception { ProcessBuilder processBuilder - = ProcessTools.createJavaProcessBuilder( + = ProcessTools.createLimitedTestJavaProcessBuilder( RTMTestBase.prepareTestOptions(logFileName, test, options)); OutputAnalyzer outputAnalyzer = new OutputAnalyzer(processBuilder.start()); diff --git a/test/hotspot/jtreg/compiler/types/correctness/OffTest.java b/test/hotspot/jtreg/compiler/types/correctness/OffTest.java index 73574447eaf..6f2354cf895 100644 --- a/test/hotspot/jtreg/compiler/types/correctness/OffTest.java +++ b/test/hotspot/jtreg/compiler/types/correctness/OffTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2023, Oracle and/or its affiliates. All rights reserved. * 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,7 +86,7 @@ private static void runTest() throws Exception { OPTIONS[TYPE_PROFILE_INDEX] = typeProfileLevel; OPTIONS[USE_TYPE_SPECULATION_INDEX] = useTypeSpeculation; OPTIONS[PROFILING_TYPE_INDEX] = type.name(); - ProcessBuilder processBuilder = ProcessTools.createTestJvm(OPTIONS); + ProcessBuilder processBuilder = ProcessTools.createTestJavaProcessBuilder(OPTIONS); OutputAnalyzer outputAnalyzer = new OutputAnalyzer(processBuilder.start()); outputAnalyzer.shouldHaveExitValue(0); } diff --git a/test/hotspot/jtreg/compiler/vectorization/TestBufferVectorization.java b/test/hotspot/jtreg/compiler/vectorization/TestBufferVectorization.java index bb2bb994bc9..95970256c48 100644 --- a/test/hotspot/jtreg/compiler/vectorization/TestBufferVectorization.java +++ b/test/hotspot/jtreg/compiler/vectorization/TestBufferVectorization.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2020, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -224,11 +224,11 @@ static void verify_vectors(String testName) { ProcessBuilder pb; OutputAnalyzer out; try { - pb = ProcessTools.createJavaProcessBuilder("-XX:-BackgroundCompilation", - "-XX:+TraceNewVectors", - "compiler.vectorization.TestBufferVectorization", - testName, - "run"); + pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:-BackgroundCompilation", + "-XX:+TraceNewVectors", + "compiler.vectorization.TestBufferVectorization", + testName, + "run"); out = new OutputAnalyzer(pb.start()); } catch (Exception e) { throw new RuntimeException(" Exception launching Java process: " + e); diff --git a/test/hotspot/jtreg/containers/cgroup/PlainRead.java b/test/hotspot/jtreg/containers/cgroup/PlainRead.java index 5e092e663c0..21eccd79835 100644 --- a/test/hotspot/jtreg/containers/cgroup/PlainRead.java +++ b/test/hotspot/jtreg/containers/cgroup/PlainRead.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -67,7 +67,7 @@ static public void isNotContainer(OutputAnalyzer oa) { public static void main(String[] args) throws Exception { WhiteBox wb = WhiteBox.getWhiteBox(); - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-Xlog:os+container=trace", "-version"); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-Xlog:os+container=trace", "-version"); OutputAnalyzer output = new OutputAnalyzer(pb.start()); if (wb.isContainerized()) { diff --git a/test/hotspot/jtreg/gc/TestAgeOutput.java b/test/hotspot/jtreg/gc/TestAgeOutput.java index 298569fa6a5..084279bcda9 100644 --- a/test/hotspot/jtreg/gc/TestAgeOutput.java +++ b/test/hotspot/jtreg/gc/TestAgeOutput.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2023, Oracle and/or its affiliates. All rights reserved. * 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,7 +66,7 @@ public static void checkPattern(String pattern, String what) throws Exception { } public static void runTest(String gcArg) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-Xbootclasspath/a:.", "-XX:+UnlockExperimentalVMOptions", "-XX:+UnlockDiagnosticVMOptions", diff --git a/test/hotspot/jtreg/gc/TestAllocateHeapAt.java b/test/hotspot/jtreg/gc/TestAllocateHeapAt.java index 0c80e14635d..8daf0bbcdc7 100644 --- a/test/hotspot/jtreg/gc/TestAllocateHeapAt.java +++ b/test/hotspot/jtreg/gc/TestAllocateHeapAt.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2023, Oracle and/or its affiliates. All rights reserved. * 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,7 +36,7 @@ public class TestAllocateHeapAt { public static void main(String args[]) throws Exception { - ProcessBuilder pb = ProcessTools.createTestJvm( + ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder( "-XX:AllocateHeapAt=" + System.getProperty("test.dir", "."), "-Xlog:gc+heap=info", "-Xmx32m", diff --git a/test/hotspot/jtreg/gc/TestAllocateHeapAtError.java b/test/hotspot/jtreg/gc/TestAllocateHeapAtError.java index 748ddd2f1f9..372437b8898 100644 --- a/test/hotspot/jtreg/gc/TestAllocateHeapAtError.java +++ b/test/hotspot/jtreg/gc/TestAllocateHeapAtError.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2023, Oracle and/or its affiliates. All rights reserved. * 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 @@ public static void main(String args[]) throws Exception { f = new File(test_dir, UUID.randomUUID().toString()); } while(f.exists()); - ProcessBuilder pb = ProcessTools.createTestJvm( + ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder( "-XX:AllocateHeapAt=" + f.getName(), "-Xlog:gc+heap=info", "-Xmx32m", diff --git a/test/hotspot/jtreg/gc/TestAllocateHeapAtMultiple.java b/test/hotspot/jtreg/gc/TestAllocateHeapAtMultiple.java index ddb2d9568e2..b2d2f1e429d 100644 --- a/test/hotspot/jtreg/gc/TestAllocateHeapAtMultiple.java +++ b/test/hotspot/jtreg/gc/TestAllocateHeapAtMultiple.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2023, Oracle and/or its affiliates. All rights reserved. * 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,7 +60,7 @@ public static void main(String args[]) throws Exception { "-Xlog:gc+heap=info", "-version"}); - ProcessBuilder pb = ProcessTools.createTestJvm(flags); + ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder(flags); OutputAnalyzer output = new OutputAnalyzer(pb.start()); System.out.println("Output:\n" + output.getOutput()); diff --git a/test/hotspot/jtreg/gc/TestCardTablePageCommits.java b/test/hotspot/jtreg/gc/TestCardTablePageCommits.java index ca14cfd71be..c468a771076 100644 --- a/test/hotspot/jtreg/gc/TestCardTablePageCommits.java +++ b/test/hotspot/jtreg/gc/TestCardTablePageCommits.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -42,7 +42,7 @@ public static void main(String args[]) throws Exception { // because of 8kB pages, assume 4 KB pages for all other CPUs. String Xmx = "-Xmx4m"; - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( Xmx, "-XX:NativeMemoryTracking=detail", "-XX:+UseParallelGC", diff --git a/test/hotspot/jtreg/gc/TestNumWorkerOutput.java b/test/hotspot/jtreg/gc/TestNumWorkerOutput.java index d8bc4a1f6fe..81209f73929 100644 --- a/test/hotspot/jtreg/gc/TestNumWorkerOutput.java +++ b/test/hotspot/jtreg/gc/TestNumWorkerOutput.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2023, Oracle and/or its affiliates. All rights reserved. * 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,7 +58,7 @@ public static void checkPatternOnce(String pattern, String what) throws Exceptio } public static void runTest(String gcArg) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-Xbootclasspath/a:.", "-XX:+UnlockExperimentalVMOptions", "-XX:+UnlockDiagnosticVMOptions", diff --git a/test/hotspot/jtreg/gc/TestObjectAlignment.java b/test/hotspot/jtreg/gc/TestObjectAlignment.java index 28ae58429d5..8879d59de82 100644 --- a/test/hotspot/jtreg/gc/TestObjectAlignment.java +++ b/test/hotspot/jtreg/gc/TestObjectAlignment.java @@ -26,36 +26,29 @@ /** * @test TestObjectAlignment * @bug 8021823 + * @requires vm.bits == "64" * @summary G1: Concurrent marking crashes with -XX:ObjectAlignmentInBytes>=32 in 64bit VMs * @library /test/lib * @modules java.base/jdk.internal.misc - * @run main/othervm gc.TestObjectAlignment -Xmx20M -XX:+ExplicitGCInvokesConcurrent -XX:+IgnoreUnrecognizedVMOptions -XX:ObjectAlignmentInBytes=8 - * @run main/othervm gc.TestObjectAlignment -Xmx20M -XX:+ExplicitGCInvokesConcurrent -XX:+IgnoreUnrecognizedVMOptions -XX:ObjectAlignmentInBytes=16 - * @run main/othervm gc.TestObjectAlignment -Xmx20M -XX:+ExplicitGCInvokesConcurrent -XX:+IgnoreUnrecognizedVMOptions -XX:ObjectAlignmentInBytes=32 - * @run main/othervm gc.TestObjectAlignment -Xmx20M -XX:+ExplicitGCInvokesConcurrent -XX:+IgnoreUnrecognizedVMOptions -XX:ObjectAlignmentInBytes=64 - * @run main/othervm gc.TestObjectAlignment -Xmx20M -XX:+ExplicitGCInvokesConcurrent -XX:+IgnoreUnrecognizedVMOptions -XX:ObjectAlignmentInBytes=128 - * @run main/othervm gc.TestObjectAlignment -Xmx20M -XX:+ExplicitGCInvokesConcurrent -XX:+IgnoreUnrecognizedVMOptions -XX:ObjectAlignmentInBytes=256 - * @run main/othervm gc.TestObjectAlignment -Xmx20M -XX:-ExplicitGCInvokesConcurrent -XX:+IgnoreUnrecognizedVMOptions -XX:ObjectAlignmentInBytes=8 - * @run main/othervm gc.TestObjectAlignment -Xmx20M -XX:-ExplicitGCInvokesConcurrent -XX:+IgnoreUnrecognizedVMOptions -XX:ObjectAlignmentInBytes=16 - * @run main/othervm gc.TestObjectAlignment -Xmx20M -XX:-ExplicitGCInvokesConcurrent -XX:+IgnoreUnrecognizedVMOptions -XX:ObjectAlignmentInBytes=32 - * @run main/othervm gc.TestObjectAlignment -Xmx20M -XX:-ExplicitGCInvokesConcurrent -XX:+IgnoreUnrecognizedVMOptions -XX:ObjectAlignmentInBytes=64 - * @run main/othervm gc.TestObjectAlignment -Xmx20M -XX:-ExplicitGCInvokesConcurrent -XX:+IgnoreUnrecognizedVMOptions -XX:ObjectAlignmentInBytes=128 - * @run main/othervm gc.TestObjectAlignment -Xmx20M -XX:-ExplicitGCInvokesConcurrent -XX:+IgnoreUnrecognizedVMOptions -XX:ObjectAlignmentInBytes=256 + * @run main/othervm gc.TestObjectAlignment -Xmx20M -XX:+ExplicitGCInvokesConcurrent -XX:ObjectAlignmentInBytes=8 + * @run main/othervm gc.TestObjectAlignment -Xmx20M -XX:+ExplicitGCInvokesConcurrent -XX:ObjectAlignmentInBytes=16 + * @run main/othervm gc.TestObjectAlignment -Xmx20M -XX:+ExplicitGCInvokesConcurrent -XX:ObjectAlignmentInBytes=32 + * @run main/othervm gc.TestObjectAlignment -Xmx20M -XX:+ExplicitGCInvokesConcurrent -XX:ObjectAlignmentInBytes=64 + * @run main/othervm gc.TestObjectAlignment -Xmx20M -XX:+ExplicitGCInvokesConcurrent -XX:ObjectAlignmentInBytes=128 + * @run main/othervm gc.TestObjectAlignment -Xmx20M -XX:+ExplicitGCInvokesConcurrent -XX:ObjectAlignmentInBytes=256 + * @run main/othervm gc.TestObjectAlignment -Xmx20M -XX:-ExplicitGCInvokesConcurrent -XX:ObjectAlignmentInBytes=8 + * @run main/othervm gc.TestObjectAlignment -Xmx20M -XX:-ExplicitGCInvokesConcurrent -XX:ObjectAlignmentInBytes=16 + * @run main/othervm gc.TestObjectAlignment -Xmx20M -XX:-ExplicitGCInvokesConcurrent -XX:ObjectAlignmentInBytes=32 + * @run main/othervm gc.TestObjectAlignment -Xmx20M -XX:-ExplicitGCInvokesConcurrent -XX:ObjectAlignmentInBytes=64 + * @run main/othervm gc.TestObjectAlignment -Xmx20M -XX:-ExplicitGCInvokesConcurrent -XX:ObjectAlignmentInBytes=128 + * @run main/othervm gc.TestObjectAlignment -Xmx20M -XX:-ExplicitGCInvokesConcurrent -XX:ObjectAlignmentInBytes=256 */ public class TestObjectAlignment { public static byte[] garbage; - private static boolean runsOn32bit() { - return System.getProperty("sun.arch.data.model").equals("32"); - } - public static void main(String[] args) throws Exception { - if (runsOn32bit()) { - // 32 bit VMs do not allow setting ObjectAlignmentInBytes, so there is nothing to test. We still get called. - return; - } for (int i = 0; i < 10; i++) { garbage = new byte[1000]; System.gc(); diff --git a/test/hotspot/jtreg/gc/TestSmallHeap.java b/test/hotspot/jtreg/gc/TestSmallHeap.java index f4d44862ed6..a9b32eb81c8 100644 --- a/test/hotspot/jtreg/gc/TestSmallHeap.java +++ b/test/hotspot/jtreg/gc/TestSmallHeap.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -96,7 +96,7 @@ public static void main(String[] args) throws Exception { private static void verifySmallHeapSize(String gc, long expectedMaxHeap) throws Exception { long minMaxHeap = 4 * 1024 * 1024; - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( gc, "-Xmx" + minMaxHeap, "-XX:+PrintFlagsFinal", diff --git a/test/hotspot/jtreg/gc/TestVerifyDuringStartup.java b/test/hotspot/jtreg/gc/TestVerifyDuringStartup.java index e2134798722..4ad9f9675d9 100644 --- a/test/hotspot/jtreg/gc/TestVerifyDuringStartup.java +++ b/test/hotspot/jtreg/gc/TestVerifyDuringStartup.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2023, Oracle and/or its affiliates. All rights reserved. * 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,7 +37,7 @@ public class TestVerifyDuringStartup { public static void main(String args[]) throws Exception { - ProcessBuilder pb = ProcessTools.createTestJvm( + ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder( "-XX:-UseTLAB", "-XX:+UnlockDiagnosticVMOptions", "-XX:+VerifyDuringStartup", diff --git a/test/hotspot/jtreg/gc/TestVerifySilently.java b/test/hotspot/jtreg/gc/TestVerifySilently.java index c4dd4dd779b..b7b07a1eb8e 100644 --- a/test/hotspot/jtreg/gc/TestVerifySilently.java +++ b/test/hotspot/jtreg/gc/TestVerifySilently.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2023, Oracle and/or its affiliates. All rights reserved. * 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,7 +57,7 @@ private static OutputAnalyzer runTest(boolean verifySilently) throws Exception { "-XX:+VerifyAfterGC", (verifySilently ? "-Xlog:gc":"-Xlog:gc+verify=debug"), TestVerifySilentlyRunSystemGC.class.getName()}); - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(vmOpts); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(vmOpts); OutputAnalyzer output = new OutputAnalyzer(pb.start()); System.out.println("Output:\n" + output.getOutput()); diff --git a/test/hotspot/jtreg/gc/TestVerifySubSet.java b/test/hotspot/jtreg/gc/TestVerifySubSet.java index d15d8fefccd..cae39085048 100644 --- a/test/hotspot/jtreg/gc/TestVerifySubSet.java +++ b/test/hotspot/jtreg/gc/TestVerifySubSet.java @@ -55,7 +55,7 @@ private static OutputAnalyzer runTest(String subset) throws Exception { "-Xlog:gc+verify=debug", "-XX:VerifySubSet="+subset, TestVerifySubSetRunSystemGC.class.getName()}); - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(vmOpts); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(vmOpts); OutputAnalyzer output = new OutputAnalyzer(pb.start()); System.out.println("Output:\n" + output.getOutput()); diff --git a/test/hotspot/jtreg/gc/arguments/GCArguments.java b/test/hotspot/jtreg/gc/arguments/GCArguments.java index b2610da0c4e..c59a14954bf 100644 --- a/test/hotspot/jtreg/gc/arguments/GCArguments.java +++ b/test/hotspot/jtreg/gc/arguments/GCArguments.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 2023, Oracle and/or its affiliates. All rights reserved. * 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,19 +66,19 @@ static private String[] withDefaults(String[] arguments) { return augmented.toArray(new String[augmented.size()]); } - static public ProcessBuilder createJavaProcessBuilder(List arguments) { - return createJavaProcessBuilder(arguments.toArray(String[]::new)); + static public ProcessBuilder createLimitedTestJavaProcessBuilder(List arguments) { + return createLimitedTestJavaProcessBuilder(arguments.toArray(String[]::new)); } - static public ProcessBuilder createJavaProcessBuilder(String... arguments) { - return ProcessTools.createJavaProcessBuilder(withDefaults(arguments)); + static public ProcessBuilder createLimitedTestJavaProcessBuilder(String... arguments) { + return ProcessTools.createLimitedTestJavaProcessBuilder(withDefaults(arguments)); } - static public ProcessBuilder createTestJvm(List arguments) { - return createTestJvm(arguments.toArray(String[]::new)); + static public ProcessBuilder createTestJavaProcessBuilder(List arguments) { + return createTestJavaProcessBuilder(arguments.toArray(String[]::new)); } - static public ProcessBuilder createTestJvm(String... arguments) { - return ProcessTools.createTestJvm(withDefaults(arguments)); + static public ProcessBuilder createTestJavaProcessBuilder(String... arguments) { + return ProcessTools.createTestJavaProcessBuilder(withDefaults(arguments)); } } diff --git a/test/hotspot/jtreg/gc/arguments/TestAggressiveHeap.java b/test/hotspot/jtreg/gc/arguments/TestAggressiveHeap.java index 8eda52a20b3..2ce13fbbfd4 100644 --- a/test/hotspot/jtreg/gc/arguments/TestAggressiveHeap.java +++ b/test/hotspot/jtreg/gc/arguments/TestAggressiveHeap.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2023, Oracle and/or its affiliates. All rights reserved. * 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,7 +65,7 @@ public static void main(String args[]) throws Exception { " *bool +UseParallelGC *= *true +\\{product\\} *\\{command line\\}"; private static void testFlag() throws Exception { - ProcessBuilder pb = GCArguments.createJavaProcessBuilder( + ProcessBuilder pb = GCArguments.createTestJavaProcessBuilder( option, heapSizeOption, "-XX:+PrintFlagsFinal", "-version"); OutputAnalyzer output = new OutputAnalyzer(pb.start()); diff --git a/test/hotspot/jtreg/gc/arguments/TestArrayAllocatorMallocLimit.java b/test/hotspot/jtreg/gc/arguments/TestArrayAllocatorMallocLimit.java index 80f0ec4f0cc..a8de7428d22 100644 --- a/test/hotspot/jtreg/gc/arguments/TestArrayAllocatorMallocLimit.java +++ b/test/hotspot/jtreg/gc/arguments/TestArrayAllocatorMallocLimit.java @@ -51,7 +51,7 @@ public static void main(String [] args) throws Exception { private static final String printFlagsFinalPattern = " *size_t *" + flagName + " *:?= *(\\d+) *\\{experimental\\} *"; public static void testDefaultValue() throws Exception { - ProcessBuilder pb = GCArguments.createTestJvm( + ProcessBuilder pb = GCArguments.createTestJavaProcessBuilder( "-XX:+UnlockExperimentalVMOptions", "-XX:+PrintFlagsFinal", "-version"); OutputAnalyzer output = new OutputAnalyzer(pb.start()); @@ -77,7 +77,7 @@ public static void testDefaultValue() throws Exception { public static void testSetValue() throws Exception { long flagValue = 2048; - ProcessBuilder pb = GCArguments.createJavaProcessBuilder( + ProcessBuilder pb = GCArguments.createLimitedTestJavaProcessBuilder( "-XX:+UnlockExperimentalVMOptions", "-XX:" + flagName + "=" + flagValue, "-XX:+PrintFlagsFinal", "-version"); OutputAnalyzer output = new OutputAnalyzer(pb.start()); diff --git a/test/hotspot/jtreg/gc/arguments/TestCompressedClassFlags.java b/test/hotspot/jtreg/gc/arguments/TestCompressedClassFlags.java index 5e5bf97b7cf..0b6dce0fc0e 100644 --- a/test/hotspot/jtreg/gc/arguments/TestCompressedClassFlags.java +++ b/test/hotspot/jtreg/gc/arguments/TestCompressedClassFlags.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2023, Oracle and/or its affiliates. All rights reserved. * 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,7 @@ * @library / * @modules java.base/jdk.internal.misc * java.management + * @requires vm.opt.CompressedClassSpaceSize == null & vm.opt.UseCompressedClassPointers == null * @run driver gc.arguments.TestCompressedClassFlags */ public class TestCompressedClassFlags { @@ -50,7 +51,7 @@ public static void main(String[] args) throws Exception { } private static OutputAnalyzer runJava(String ... args) throws Exception { - ProcessBuilder pb = GCArguments.createJavaProcessBuilder(args); + ProcessBuilder pb = GCArguments.createTestJavaProcessBuilder(args); return new OutputAnalyzer(pb.start()); } } diff --git a/test/hotspot/jtreg/gc/arguments/TestDisableDefaultGC.java b/test/hotspot/jtreg/gc/arguments/TestDisableDefaultGC.java index c282a784203..e8e4552da01 100644 --- a/test/hotspot/jtreg/gc/arguments/TestDisableDefaultGC.java +++ b/test/hotspot/jtreg/gc/arguments/TestDisableDefaultGC.java @@ -40,13 +40,13 @@ public class TestDisableDefaultGC { public static void main(String[] args) throws Exception { // Start VM, disabling all possible default GCs - ProcessBuilder pb = GCArguments.createTestJvm("-XX:-UseSerialGC", - "-XX:-UseParallelGC", - "-XX:-UseG1GC", - "-XX:-UseZGC", - "-XX:+UnlockExperimentalVMOptions", - "-XX:-UseShenandoahGC", - "-version"); + ProcessBuilder pb = GCArguments.createTestJavaProcessBuilder("-XX:-UseSerialGC", + "-XX:-UseParallelGC", + "-XX:-UseG1GC", + "-XX:-UseZGC", + "-XX:+UnlockExperimentalVMOptions", + "-XX:-UseShenandoahGC", + "-version"); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldMatch("Garbage collector not selected"); output.shouldHaveExitValue(1); diff --git a/test/hotspot/jtreg/gc/arguments/TestG1ConcMarkStepDurationMillis.java b/test/hotspot/jtreg/gc/arguments/TestG1ConcMarkStepDurationMillis.java index d5a273b3d01..21a4eddb410 100644 --- a/test/hotspot/jtreg/gc/arguments/TestG1ConcMarkStepDurationMillis.java +++ b/test/hotspot/jtreg/gc/arguments/TestG1ConcMarkStepDurationMillis.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2023, Oracle and/or its affiliates. All rights reserved. * 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,7 +25,7 @@ /* * @test TestG1ConcMarkStepDurationMillis - * @requires vm.gc.G1 + * @requires vm.gc.G1 & vm.opt.G1ConcMarkStepDurationMillis == null * @summary Tests argument processing for double type flag, G1ConcMarkStepDurationMillis * @library /test/lib * @library / @@ -78,7 +78,7 @@ private static void runG1ConcMarkStepDurationMillisTest(String expectedValue, in Collections.addAll(vmOpts, "-XX:+UseG1GC", "-XX:G1ConcMarkStepDurationMillis="+expectedValue, "-XX:+PrintFlagsFinal", "-version"); - ProcessBuilder pb = GCArguments.createJavaProcessBuilder(vmOpts); + ProcessBuilder pb = GCArguments.createTestJavaProcessBuilder(vmOpts); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldHaveExitValue(expectedResult == PASS ? 0 : 1); diff --git a/test/hotspot/jtreg/gc/arguments/TestG1ConcRefinementThreads.java b/test/hotspot/jtreg/gc/arguments/TestG1ConcRefinementThreads.java index 750dfefd6c6..91be97782f5 100644 --- a/test/hotspot/jtreg/gc/arguments/TestG1ConcRefinementThreads.java +++ b/test/hotspot/jtreg/gc/arguments/TestG1ConcRefinementThreads.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2023, Oracle and/or its affiliates. All rights reserved. * 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 @@ /* * @test TestG1ConcRefinementThreads * @bug 8047976 - * @requires vm.gc.G1 + * @requires vm.gc.G1 & vm.opt.G1ConcRefinementThreads == null * @summary Tests argument processing for G1ConcRefinementThreads * @library /test/lib * @library / @@ -69,7 +69,7 @@ private static void runG1ConcRefinementThreadsTest(String[] passedOpts, } Collections.addAll(vmOpts, "-XX:+UseG1GC", "-XX:+PrintFlagsFinal", "-version"); - ProcessBuilder pb = GCArguments.createJavaProcessBuilder(vmOpts); + ProcessBuilder pb = GCArguments.createTestJavaProcessBuilder(vmOpts); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldHaveExitValue(0); diff --git a/test/hotspot/jtreg/gc/arguments/TestG1HeapRegionSize.java b/test/hotspot/jtreg/gc/arguments/TestG1HeapRegionSize.java index 9dadf413485..231c0e5c830 100644 --- a/test/hotspot/jtreg/gc/arguments/TestG1HeapRegionSize.java +++ b/test/hotspot/jtreg/gc/arguments/TestG1HeapRegionSize.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2023, Oracle and/or its affiliates. All rights reserved. * 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 @@ /* * @test TestG1HeapRegionSize * @bug 8021879 - * @requires vm.gc.G1 + * @requires vm.gc.G1 & vm.opt.G1HeapRegionSize == null * @summary Verify that the flag G1HeapRegionSize is updated properly * @modules java.base/jdk.internal.misc * @modules java.management/sun.management @@ -52,7 +52,7 @@ private static void checkG1HeapRegionSize(String[] flags, int expectedValue, int flagList.add("-XX:+PrintFlagsFinal"); flagList.add("-version"); - ProcessBuilder pb = GCArguments.createJavaProcessBuilder(flagList); + ProcessBuilder pb = GCArguments.createTestJavaProcessBuilder(flagList); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldHaveExitValue(exitValue); diff --git a/test/hotspot/jtreg/gc/arguments/TestG1PercentageOptions.java b/test/hotspot/jtreg/gc/arguments/TestG1PercentageOptions.java index abf7926f966..875e995374a 100644 --- a/test/hotspot/jtreg/gc/arguments/TestG1PercentageOptions.java +++ b/test/hotspot/jtreg/gc/arguments/TestG1PercentageOptions.java @@ -63,7 +63,7 @@ private static final class OptionDescription { }; private static void check(String flag, boolean is_valid) throws Exception { - ProcessBuilder pb = GCArguments.createTestJvm("-XX:+UseG1GC", flag, "-version"); + ProcessBuilder pb = GCArguments.createTestJavaProcessBuilder("-XX:+UseG1GC", flag, "-version"); OutputAnalyzer output = new OutputAnalyzer(pb.start()); if (is_valid) { output.shouldHaveExitValue(0); diff --git a/test/hotspot/jtreg/gc/arguments/TestHeapFreeRatio.java b/test/hotspot/jtreg/gc/arguments/TestHeapFreeRatio.java index 24528c923ed..19ecb181418 100644 --- a/test/hotspot/jtreg/gc/arguments/TestHeapFreeRatio.java +++ b/test/hotspot/jtreg/gc/arguments/TestHeapFreeRatio.java @@ -48,7 +48,7 @@ enum Validation { } private static void testMinMaxFreeRatio(String min, String max, Validation type) throws Exception { - ProcessBuilder pb = GCArguments.createTestJvm( + ProcessBuilder pb = GCArguments.createTestJavaProcessBuilder( "-Xminf" + min, "-Xmaxf" + max, "-version"); diff --git a/test/hotspot/jtreg/gc/arguments/TestInitialTenuringThreshold.java b/test/hotspot/jtreg/gc/arguments/TestInitialTenuringThreshold.java index 784a69cd9ae..7bf78a001bf 100644 --- a/test/hotspot/jtreg/gc/arguments/TestInitialTenuringThreshold.java +++ b/test/hotspot/jtreg/gc/arguments/TestInitialTenuringThreshold.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2023, Oracle and/or its affiliates. All rights reserved. * 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 @@ /* * @test TestInitialTenuringThreshold * @bug 8014765 - * @requires vm.gc.Parallel + * @requires vm.gc.Parallel & vm.opt.InitialTenuringThreshold == null & vm.opt.MaxTenuringThreshold == null * @summary Tests argument processing for initial tenuring threshold * @library /test/lib * @library / @@ -41,7 +41,7 @@ public class TestInitialTenuringThreshold { public static void runWithThresholds(int initial, int max, boolean shouldfail) throws Exception { - ProcessBuilder pb = GCArguments.createJavaProcessBuilder( + ProcessBuilder pb = GCArguments.createTestJavaProcessBuilder( "-XX:+UseParallelGC", "-XX:InitialTenuringThreshold=" + String.valueOf(initial), "-XX:MaxTenuringThreshold=" + String.valueOf(max), @@ -58,8 +58,9 @@ public static void runWithThresholds(int initial, int max, boolean shouldfail) t public static void main(String args[]) throws Exception { - ProcessBuilder pb = GCArguments.createJavaProcessBuilder( + ProcessBuilder pb = GCArguments.createTestJavaProcessBuilder( // some value below the default value of InitialTenuringThreshold of 7 + "-XX:+UseParallelGC", "-XX:MaxTenuringThreshold=1", "-version" ); diff --git a/test/hotspot/jtreg/gc/arguments/TestMaxHeapSizeTools.java b/test/hotspot/jtreg/gc/arguments/TestMaxHeapSizeTools.java index b7b27815c9e..c6d2c3c15a0 100644 --- a/test/hotspot/jtreg/gc/arguments/TestMaxHeapSizeTools.java +++ b/test/hotspot/jtreg/gc/arguments/TestMaxHeapSizeTools.java @@ -115,7 +115,7 @@ private static long align_up(long value, long alignment) { } private static void getNewOldSize(String gcflag, long[] values) throws Exception { - ProcessBuilder pb = GCArguments.createTestJvm(gcflag, + ProcessBuilder pb = GCArguments.createTestJavaProcessBuilder(gcflag, "-XX:+PrintFlagsFinal", "-version"); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldHaveExitValue(0); @@ -208,7 +208,7 @@ public static OutputAnalyzer runWhiteBoxTest(String[] vmargs, String classname, finalargs.add(classname); finalargs.addAll(Arrays.asList(arguments)); - ProcessBuilder pb = GCArguments.createTestJvm(finalargs.toArray(String[]::new)); + ProcessBuilder pb = GCArguments.createTestJavaProcessBuilder(finalargs.toArray(String[]::new)); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldHaveExitValue(0); @@ -308,7 +308,7 @@ private static void shouldContainOrNot(OutputAnalyzer output, boolean contains, } private static void expect(String[] flags, boolean hasWarning, boolean hasError, int errorcode) throws Exception { - ProcessBuilder pb = GCArguments.createTestJvm(flags); + ProcessBuilder pb = GCArguments.createTestJavaProcessBuilder(flags); OutputAnalyzer output = new OutputAnalyzer(pb.start()); shouldContainOrNot(output, hasWarning, "Warning"); shouldContainOrNot(output, hasError, "Error"); diff --git a/test/hotspot/jtreg/gc/arguments/TestMaxMinHeapFreeRatioFlags.java b/test/hotspot/jtreg/gc/arguments/TestMaxMinHeapFreeRatioFlags.java index 3cf0034f1a7..7e91fe60cfb 100644 --- a/test/hotspot/jtreg/gc/arguments/TestMaxMinHeapFreeRatioFlags.java +++ b/test/hotspot/jtreg/gc/arguments/TestMaxMinHeapFreeRatioFlags.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -98,7 +98,7 @@ public static void positiveTest(int minRatio, boolean useXminf, Boolean.toString(shrinkHeapInSteps) ); - ProcessBuilder procBuilder = GCArguments.createJavaProcessBuilder(vmOptions); + ProcessBuilder procBuilder = GCArguments.createLimitedTestJavaProcessBuilder(vmOptions); OutputAnalyzer analyzer = new OutputAnalyzer(procBuilder.start()); analyzer.shouldHaveExitValue(0); } @@ -123,7 +123,7 @@ public static void negativeTest(int minRatio, boolean useXminf, "--add-exports=java.base/jdk.internal.misc=ALL-UNNAMED", "-version" ); - ProcessBuilder procBuilder = GCArguments.createJavaProcessBuilder(vmOptions); + ProcessBuilder procBuilder = GCArguments.createLimitedTestJavaProcessBuilder(vmOptions); OutputAnalyzer analyzer = new OutputAnalyzer(procBuilder.start()); analyzer.shouldHaveExitValue(1); analyzer.shouldContain("Error: Could not create the Java Virtual Machine."); diff --git a/test/hotspot/jtreg/gc/arguments/TestMaxNewSize.java b/test/hotspot/jtreg/gc/arguments/TestMaxNewSize.java index 6abcc9f84fe..f2214b8b0cf 100644 --- a/test/hotspot/jtreg/gc/arguments/TestMaxNewSize.java +++ b/test/hotspot/jtreg/gc/arguments/TestMaxNewSize.java @@ -95,7 +95,7 @@ private static String getMaxNewSize(String[] flags) throws Exception { finalargs.add("-XX:+PrintFlagsFinal"); finalargs.add("-version"); - ProcessBuilder pb = GCArguments.createTestJvm(finalargs); + ProcessBuilder pb = GCArguments.createTestJavaProcessBuilder(finalargs); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldHaveExitValue(0); String stdout = output.getStdout(); diff --git a/test/hotspot/jtreg/gc/arguments/TestMaxRAMFlags.java b/test/hotspot/jtreg/gc/arguments/TestMaxRAMFlags.java index c2802d18a8a..4c66afd5cf5 100644 --- a/test/hotspot/jtreg/gc/arguments/TestMaxRAMFlags.java +++ b/test/hotspot/jtreg/gc/arguments/TestMaxRAMFlags.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 2023, Oracle and/or its affiliates. All rights reserved. * 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,7 @@ private static void checkMaxRAMSize(long maxram, int maxrampercent, boolean forc args.add("-XX:+PrintFlagsFinal"); args.add("-version"); - ProcessBuilder pb = GCArguments.createJavaProcessBuilder(args); + ProcessBuilder pb = GCArguments.createLimitedTestJavaProcessBuilder(args); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldHaveExitValue(0); String stdout = output.getStdout(); @@ -84,7 +84,7 @@ private static long getHeapBaseMinAddress() throws Exception { args.add("-XX:+PrintFlagsFinal"); args.add("-version"); - ProcessBuilder pb = GCArguments.createJavaProcessBuilder(args); + ProcessBuilder pb = GCArguments.createLimitedTestJavaProcessBuilder(args); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldHaveExitValue(0); String stdout = output.getStdout(); diff --git a/test/hotspot/jtreg/gc/arguments/TestMinAndInitialSurvivorRatioFlags.java b/test/hotspot/jtreg/gc/arguments/TestMinAndInitialSurvivorRatioFlags.java index 4e18a4c60b6..83f564b98a5 100644 --- a/test/hotspot/jtreg/gc/arguments/TestMinAndInitialSurvivorRatioFlags.java +++ b/test/hotspot/jtreg/gc/arguments/TestMinAndInitialSurvivorRatioFlags.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -102,7 +102,7 @@ public static void testSurvivorRatio(int survivorRatio, Boolean.toString(useAdaptiveSizePolicy) ); vmOptions.removeIf((String p) -> p.isEmpty()); - ProcessBuilder procBuilder = GCArguments.createJavaProcessBuilder(vmOptions); + ProcessBuilder procBuilder = GCArguments.createLimitedTestJavaProcessBuilder(vmOptions); OutputAnalyzer analyzer = new OutputAnalyzer(procBuilder.start()); analyzer.shouldHaveExitValue(0); } diff --git a/test/hotspot/jtreg/gc/arguments/TestNewRatioFlag.java b/test/hotspot/jtreg/gc/arguments/TestNewRatioFlag.java index 49ce08e5b0e..9076005fa86 100644 --- a/test/hotspot/jtreg/gc/arguments/TestNewRatioFlag.java +++ b/test/hotspot/jtreg/gc/arguments/TestNewRatioFlag.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -82,7 +82,7 @@ public static void testNewRatio(int ratio, LinkedList options) throws Ex Integer.toString(ratio) ); - ProcessBuilder procBuilder = GCArguments.createJavaProcessBuilder(vmOptions); + ProcessBuilder procBuilder = GCArguments.createLimitedTestJavaProcessBuilder(vmOptions); OutputAnalyzer analyzer = new OutputAnalyzer(procBuilder.start()); analyzer.shouldHaveExitValue(0); System.out.println(analyzer.getOutput()); diff --git a/test/hotspot/jtreg/gc/arguments/TestNewSizeFlags.java b/test/hotspot/jtreg/gc/arguments/TestNewSizeFlags.java index 70a124e6f14..3c3aff980dd 100644 --- a/test/hotspot/jtreg/gc/arguments/TestNewSizeFlags.java +++ b/test/hotspot/jtreg/gc/arguments/TestNewSizeFlags.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -166,7 +166,7 @@ private static OutputAnalyzer startVM(LinkedList options, Long.toString(maxHeapSize) ); vmOptions.removeIf(String::isEmpty); - ProcessBuilder procBuilder = GCArguments.createJavaProcessBuilder(vmOptions); + ProcessBuilder procBuilder = GCArguments.createLimitedTestJavaProcessBuilder(vmOptions); OutputAnalyzer analyzer = new OutputAnalyzer(procBuilder.start()); return analyzer; } diff --git a/test/hotspot/jtreg/gc/arguments/TestNewSizeThreadIncrease.java b/test/hotspot/jtreg/gc/arguments/TestNewSizeThreadIncrease.java index be69ff2c79b..82e98429100 100644 --- a/test/hotspot/jtreg/gc/arguments/TestNewSizeThreadIncrease.java +++ b/test/hotspot/jtreg/gc/arguments/TestNewSizeThreadIncrease.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2023, Oracle and/or its affiliates. All rights reserved. * 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,13 +65,13 @@ public static void main(String[] args) throws Exception { } static void runNewSizeThreadIncreaseTest(String expectedValue, boolean isNewsizeChanged) throws Exception { - ProcessBuilder pb = GCArguments.createJavaProcessBuilder("-XX:+UseSerialGC", - "-Xms96M", - "-Xmx128M", - "-XX:NewRatio=2", - "-Xlog:gc+heap+ergo=debug", - "-XX:NewSizeThreadIncrease="+expectedValue, - GCTest.class.getName()); + ProcessBuilder pb = GCArguments.createLimitedTestJavaProcessBuilder("-XX:+UseSerialGC", + "-Xms96M", + "-Xmx128M", + "-XX:NewRatio=2", + "-Xlog:gc+heap+ergo=debug", + "-XX:NewSizeThreadIncrease="+expectedValue, + GCTest.class.getName()); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldHaveExitValue(0); diff --git a/test/hotspot/jtreg/gc/arguments/TestObjectTenuringFlags.java b/test/hotspot/jtreg/gc/arguments/TestObjectTenuringFlags.java index 0a2c8c146da..ca45def0b2b 100644 --- a/test/hotspot/jtreg/gc/arguments/TestObjectTenuringFlags.java +++ b/test/hotspot/jtreg/gc/arguments/TestObjectTenuringFlags.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -161,7 +161,7 @@ private static void runTenuringFlagsConsistencyTest(String[] tenuringFlags, } Collections.addAll(vmOpts, "-XX:+UseParallelGC", "-XX:+PrintFlagsFinal", "-version"); - ProcessBuilder pb = GCArguments.createJavaProcessBuilder(vmOpts); + ProcessBuilder pb = GCArguments.createLimitedTestJavaProcessBuilder(vmOpts); OutputAnalyzer output = new OutputAnalyzer(pb.start()); if (shouldFail) { diff --git a/test/hotspot/jtreg/gc/arguments/TestParallelGCThreads.java b/test/hotspot/jtreg/gc/arguments/TestParallelGCThreads.java index c964115a632..345047fba9e 100644 --- a/test/hotspot/jtreg/gc/arguments/TestParallelGCThreads.java +++ b/test/hotspot/jtreg/gc/arguments/TestParallelGCThreads.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -56,7 +56,7 @@ public static void main(String args[]) throws Exception { private static final String printFlagsFinalPattern = " *uint *" + flagName + " *:?= *(\\d+) *\\{product\\} *"; public static void testDefaultValue() throws Exception { - ProcessBuilder pb = GCArguments.createJavaProcessBuilder( + ProcessBuilder pb = GCArguments.createLimitedTestJavaProcessBuilder( "-XX:+UnlockExperimentalVMOptions", "-XX:+PrintFlagsFinal", "-version"); OutputAnalyzer output = new OutputAnalyzer(pb.start()); @@ -94,7 +94,7 @@ public static void testFlags() throws Exception { for (String gc : supportedGC) { // Make sure the VM does not allow ParallelGCThreads set to 0 - ProcessBuilder pb = GCArguments.createJavaProcessBuilder( + ProcessBuilder pb = GCArguments.createLimitedTestJavaProcessBuilder( "-XX:+Use" + gc + "GC", "-XX:ParallelGCThreads=0", "-XX:+PrintFlagsFinal", @@ -127,7 +127,7 @@ public static void testFlags() throws Exception { } public static long getParallelGCThreadCount(String... flags) throws Exception { - ProcessBuilder pb = GCArguments.createJavaProcessBuilder(flags); + ProcessBuilder pb = GCArguments.createLimitedTestJavaProcessBuilder(flags); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldHaveExitValue(0); String stdout = output.getStdout(); diff --git a/test/hotspot/jtreg/gc/arguments/TestParallelRefProc.java b/test/hotspot/jtreg/gc/arguments/TestParallelRefProc.java index b936e87c370..d47d277e30b 100644 --- a/test/hotspot/jtreg/gc/arguments/TestParallelRefProc.java +++ b/test/hotspot/jtreg/gc/arguments/TestParallelRefProc.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -77,7 +77,7 @@ private static void testFlag(String[] args, boolean expectedTrue) throws Excepti result.addAll(Arrays.asList(args)); result.add("-XX:+PrintFlagsFinal"); result.add("-version"); - ProcessBuilder pb = GCArguments.createJavaProcessBuilder(result); + ProcessBuilder pb = GCArguments.createLimitedTestJavaProcessBuilder(result); OutputAnalyzer output = new OutputAnalyzer(pb.start()); diff --git a/test/hotspot/jtreg/gc/arguments/TestSelectDefaultGC.java b/test/hotspot/jtreg/gc/arguments/TestSelectDefaultGC.java index dfa3bbfb364..a48f21c957b 100644 --- a/test/hotspot/jtreg/gc/arguments/TestSelectDefaultGC.java +++ b/test/hotspot/jtreg/gc/arguments/TestSelectDefaultGC.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -44,7 +44,7 @@ public static void assertVMOption(OutputAnalyzer output, String option, boolean public static void testDefaultGC(boolean actAsServer) throws Exception { // Start VM without specifying GC - ProcessBuilder pb = GCArguments.createJavaProcessBuilder( + ProcessBuilder pb = GCArguments.createLimitedTestJavaProcessBuilder( "-XX:" + (actAsServer ? "+" : "-") + "AlwaysActAsServerClassMachine", "-XX:" + (actAsServer ? "-" : "+") + "NeverActAsServerClassMachine", "-XX:+PrintFlagsFinal", diff --git a/test/hotspot/jtreg/gc/arguments/TestSmallInitialHeapWithLargePageAndNUMA.java b/test/hotspot/jtreg/gc/arguments/TestSmallInitialHeapWithLargePageAndNUMA.java index df678326eb9..c1c2164a4da 100644 --- a/test/hotspot/jtreg/gc/arguments/TestSmallInitialHeapWithLargePageAndNUMA.java +++ b/test/hotspot/jtreg/gc/arguments/TestSmallInitialHeapWithLargePageAndNUMA.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2023, Oracle and/or its affiliates. All rights reserved. * 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,7 +60,7 @@ public static void main(String[] args) throws Exception { long initHeap = heapAlignment; long maxHeap = heapAlignment * 2; - ProcessBuilder pb_enabled = GCArguments.createJavaProcessBuilder( + ProcessBuilder pb_enabled = GCArguments.createLimitedTestJavaProcessBuilder( "-XX:+UseParallelGC", "-Xms" + String.valueOf(initHeap), "-Xmx" + String.valueOf(maxHeap), diff --git a/test/hotspot/jtreg/gc/arguments/TestSurvivorRatioFlag.java b/test/hotspot/jtreg/gc/arguments/TestSurvivorRatioFlag.java index 1a2246b1581..8567615220a 100644 --- a/test/hotspot/jtreg/gc/arguments/TestSurvivorRatioFlag.java +++ b/test/hotspot/jtreg/gc/arguments/TestSurvivorRatioFlag.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -87,7 +87,7 @@ public static void testSurvivorRatio(int ratio, LinkedList options) thro Integer.toString(ratio) ); - ProcessBuilder procBuilder = GCArguments.createJavaProcessBuilder(vmOptions); + ProcessBuilder procBuilder = GCArguments.createLimitedTestJavaProcessBuilder(vmOptions); OutputAnalyzer analyzer = new OutputAnalyzer(procBuilder.start()); analyzer.shouldHaveExitValue(0); } diff --git a/test/hotspot/jtreg/gc/arguments/TestTargetSurvivorRatioFlag.java b/test/hotspot/jtreg/gc/arguments/TestTargetSurvivorRatioFlag.java index f530bf35996..8f8b4aa1087 100644 --- a/test/hotspot/jtreg/gc/arguments/TestTargetSurvivorRatioFlag.java +++ b/test/hotspot/jtreg/gc/arguments/TestTargetSurvivorRatioFlag.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -116,7 +116,7 @@ public static void negativeTest(int ratio, LinkedList options) throws Ex vmOptions.add("-XX:TargetSurvivorRatio=" + ratio); vmOptions.add("-version"); - ProcessBuilder procBuilder = GCArguments.createJavaProcessBuilder(vmOptions); + ProcessBuilder procBuilder = GCArguments.createLimitedTestJavaProcessBuilder(vmOptions); OutputAnalyzer analyzer = new OutputAnalyzer(procBuilder.start()); analyzer.shouldHaveExitValue(1); @@ -151,7 +151,7 @@ public static void positiveTest(int ratio, LinkedList options) throws Ex Integer.toString(ratio) ); - ProcessBuilder procBuilder = GCArguments.createJavaProcessBuilder(vmOptions); + ProcessBuilder procBuilder = GCArguments.createLimitedTestJavaProcessBuilder(vmOptions); OutputAnalyzer analyzer = new OutputAnalyzer(procBuilder.start()); analyzer.shouldHaveExitValue(0); diff --git a/test/hotspot/jtreg/gc/arguments/TestUnrecognizedVMOptionsHandling.java b/test/hotspot/jtreg/gc/arguments/TestUnrecognizedVMOptionsHandling.java index 56bc49bd8f4..8d51a6df173 100644 --- a/test/hotspot/jtreg/gc/arguments/TestUnrecognizedVMOptionsHandling.java +++ b/test/hotspot/jtreg/gc/arguments/TestUnrecognizedVMOptionsHandling.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2023, Oracle and/or its affiliates. All rights reserved. * 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,7 +40,7 @@ public class TestUnrecognizedVMOptionsHandling { public static void main(String args[]) throws Exception { // The first two JAVA processes are expected to fail, but with a correct VM option suggestion - ProcessBuilder pb = GCArguments.createJavaProcessBuilder( + ProcessBuilder pb = GCArguments.createLimitedTestJavaProcessBuilder( "-XX:+UseDynamicNumberOfGcThreads", "-version" ); @@ -50,7 +50,7 @@ public static void main(String args[]) throws Exception { throw new RuntimeException("Not expected to get exit value 0"); } - pb = GCArguments.createJavaProcessBuilder( + pb = GCArguments.createLimitedTestJavaProcessBuilder( "-XX:MaxiumHeapSize=500m", "-version" ); @@ -61,7 +61,7 @@ public static void main(String args[]) throws Exception { } // The last JAVA process should run successfully for the purpose of sanity check - pb = GCArguments.createJavaProcessBuilder( + pb = GCArguments.createLimitedTestJavaProcessBuilder( "-XX:+UseDynamicNumberOfGCThreads", "-version" ); diff --git a/test/hotspot/jtreg/gc/arguments/TestUseCompressedOopsErgoTools.java b/test/hotspot/jtreg/gc/arguments/TestUseCompressedOopsErgoTools.java index 8979b92eaf6..19ebdea3c0e 100644 --- a/test/hotspot/jtreg/gc/arguments/TestUseCompressedOopsErgoTools.java +++ b/test/hotspot/jtreg/gc/arguments/TestUseCompressedOopsErgoTools.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -93,7 +93,7 @@ public static OutputAnalyzer runWhiteBoxTest(String[] vmargs, String classname, finalargs.add(classname); finalargs.addAll(Arrays.asList(arguments)); - ProcessBuilder pb = GCArguments.createJavaProcessBuilder(finalargs); + ProcessBuilder pb = GCArguments.createLimitedTestJavaProcessBuilder(finalargs); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldHaveExitValue(0); return output; @@ -157,7 +157,7 @@ private static boolean getFlagBoolValue(String flag, String where) { } private static String expect(String[] flags, boolean hasWarning, boolean hasError, int errorcode) throws Exception { - ProcessBuilder pb = GCArguments.createJavaProcessBuilder(flags); + ProcessBuilder pb = GCArguments.createLimitedTestJavaProcessBuilder(flags); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldHaveExitValue(errorcode); return output.getStdout(); diff --git a/test/hotspot/jtreg/gc/arguments/TestUseNUMAInterleaving.java b/test/hotspot/jtreg/gc/arguments/TestUseNUMAInterleaving.java index 7f3857594b6..4a7fb7108c3 100644 --- a/test/hotspot/jtreg/gc/arguments/TestUseNUMAInterleaving.java +++ b/test/hotspot/jtreg/gc/arguments/TestUseNUMAInterleaving.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2023, Oracle and/or its affiliates. All rights reserved. * 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,7 +39,7 @@ public class TestUseNUMAInterleaving { public static void main(String[] args) throws Exception { - ProcessBuilder pb = GCArguments.createTestJvm( + ProcessBuilder pb = GCArguments.createTestJavaProcessBuilder( "-XX:+UseNUMA", "-XX:+PrintFlagsFinal", "-version"); diff --git a/test/hotspot/jtreg/gc/arguments/TestVerifyBeforeAndAfterGCFlags.java b/test/hotspot/jtreg/gc/arguments/TestVerifyBeforeAndAfterGCFlags.java index 5b33dcdffca..f2b480311e1 100644 --- a/test/hotspot/jtreg/gc/arguments/TestVerifyBeforeAndAfterGCFlags.java +++ b/test/hotspot/jtreg/gc/arguments/TestVerifyBeforeAndAfterGCFlags.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2023, Oracle and/or its affiliates. All rights reserved. * 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,7 +86,7 @@ public static void testVerifyFlags(boolean verifyBeforeGC, (verifyAfterGC ? "-XX:+VerifyAfterGC" : "-XX:-VerifyAfterGC"), GarbageProducer.class.getName() }); - ProcessBuilder pb = GCArguments.createJavaProcessBuilder(vmOpts); + ProcessBuilder pb = GCArguments.createLimitedTestJavaProcessBuilder(vmOpts); OutputAnalyzer analyzer = new OutputAnalyzer(pb.start()); analyzer.shouldHaveExitValue(0); diff --git a/test/hotspot/jtreg/gc/class_unloading/TestG1ClassUnloadingHWM.java b/test/hotspot/jtreg/gc/class_unloading/TestG1ClassUnloadingHWM.java index 483fa227dbb..875da61a05f 100644 --- a/test/hotspot/jtreg/gc/class_unloading/TestG1ClassUnloadingHWM.java +++ b/test/hotspot/jtreg/gc/class_unloading/TestG1ClassUnloadingHWM.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2023, Oracle and/or its affiliates. All rights reserved. * 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 @@ public class TestG1ClassUnloadingHWM { private static long YoungGenSize = 32 * 1024 * 1024; private static OutputAnalyzer run(boolean enableUnloading) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-Xbootclasspath/a:.", "-XX:+UnlockDiagnosticVMOptions", "-XX:+WhiteBoxAPI", diff --git a/test/hotspot/jtreg/gc/epsilon/TestAlignment.java b/test/hotspot/jtreg/gc/epsilon/TestAlignment.java index c4eb329d3f6..fab4f421e0b 100644 --- a/test/hotspot/jtreg/gc/epsilon/TestAlignment.java +++ b/test/hotspot/jtreg/gc/epsilon/TestAlignment.java @@ -36,15 +36,22 @@ * @run main/othervm -Xmx64m -XX:-UseTLAB * -XX:+UnlockExperimentalVMOptions -XX:+UseEpsilonGC * gc.epsilon.TestAlignment - * + */ + +/** + * @test TestAlignment + * @requires vm.gc.Epsilon + * @requires vm.bits == "64" + * @summary Check Epsilon TLAB options with unusual object alignment + * @bug 8212177 * @run main/othervm -Xmx64m -XX:+UseTLAB * -XX:+UnlockExperimentalVMOptions -XX:+UseEpsilonGC - * -XX:+IgnoreUnrecognizedVMOptions -XX:ObjectAlignmentInBytes=16 + * -XX:ObjectAlignmentInBytes=16 * gc.epsilon.TestAlignment * * @run main/othervm -Xmx64m -XX:-UseTLAB * -XX:+UnlockExperimentalVMOptions -XX:+UseEpsilonGC - * -XX:+IgnoreUnrecognizedVMOptions -XX:ObjectAlignmentInBytes=16 + * -XX:ObjectAlignmentInBytes=16 * gc.epsilon.TestAlignment */ diff --git a/test/hotspot/jtreg/gc/epsilon/TestDieDefault.java b/test/hotspot/jtreg/gc/epsilon/TestDieDefault.java index a883eb9f27c..c978f149fca 100644 --- a/test/hotspot/jtreg/gc/epsilon/TestDieDefault.java +++ b/test/hotspot/jtreg/gc/epsilon/TestDieDefault.java @@ -37,14 +37,14 @@ public class TestDieDefault { public static void passWith(String... args) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(args); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(args); OutputAnalyzer out = new OutputAnalyzer(pb.start()); out.shouldNotContain("OutOfMemoryError"); out.shouldHaveExitValue(0); } public static void failWith(String... args) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(args); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(args); OutputAnalyzer out = new OutputAnalyzer(pb.start()); out.shouldContain("OutOfMemoryError"); if (out.getExitValue() == 0) { diff --git a/test/hotspot/jtreg/gc/epsilon/TestDieWithHeapDump.java b/test/hotspot/jtreg/gc/epsilon/TestDieWithHeapDump.java index c717b493330..2e19141d286 100644 --- a/test/hotspot/jtreg/gc/epsilon/TestDieWithHeapDump.java +++ b/test/hotspot/jtreg/gc/epsilon/TestDieWithHeapDump.java @@ -38,14 +38,14 @@ public class TestDieWithHeapDump { public static void passWith(String... args) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(args); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(args); OutputAnalyzer out = new OutputAnalyzer(pb.start()); out.shouldNotContain("OutOfMemoryError"); out.shouldHaveExitValue(0); } public static void failWith(String... args) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(args); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(args); Process p = pb.start(); OutputAnalyzer out = new OutputAnalyzer(p); out.shouldContain("OutOfMemoryError"); diff --git a/test/hotspot/jtreg/gc/epsilon/TestDieWithOnError.java b/test/hotspot/jtreg/gc/epsilon/TestDieWithOnError.java index 2cac3843b0e..a6593fecdff 100644 --- a/test/hotspot/jtreg/gc/epsilon/TestDieWithOnError.java +++ b/test/hotspot/jtreg/gc/epsilon/TestDieWithOnError.java @@ -39,7 +39,7 @@ public class TestDieWithOnError { static String ON_ERR_MSG = "Epsilon error handler message"; public static void passWith(String... args) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(args); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(args); OutputAnalyzer out = new OutputAnalyzer(pb.start()); out.shouldNotContain("OutOfMemoryError"); out.stdoutShouldNotMatch("^" + ON_ERR_MSG); @@ -47,7 +47,7 @@ public static void passWith(String... args) throws Exception { } public static void failWith(String... args) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(args); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(args); OutputAnalyzer out = new OutputAnalyzer(pb.start()); out.shouldContain("OutOfMemoryError"); if (out.getExitValue() == 0) { diff --git a/test/hotspot/jtreg/gc/epsilon/TestMaxTLAB.java b/test/hotspot/jtreg/gc/epsilon/TestMaxTLAB.java index c3ad148f014..9d2a4660497 100644 --- a/test/hotspot/jtreg/gc/epsilon/TestMaxTLAB.java +++ b/test/hotspot/jtreg/gc/epsilon/TestMaxTLAB.java @@ -48,29 +48,36 @@ * -XX:+UnlockExperimentalVMOptions -XX:+UseEpsilonGC * -XX:EpsilonMaxTLABSize=12345 * gc.epsilon.TestMaxTLAB - * + */ + +/** + * @test TestMaxTLAB + * @requires vm.gc.Epsilon + * @requires vm.bits == "64" + * @summary Check EpsilonMaxTLAB options + * @bug 8212177 * @run main/othervm -Xmx64m * -XX:+UnlockExperimentalVMOptions -XX:+UseEpsilonGC * -XX:EpsilonMaxTLABSize=1 - * -XX:+IgnoreUnrecognizedVMOptions -XX:ObjectAlignmentInBytes=16 + * -XX:ObjectAlignmentInBytes=16 * gc.epsilon.TestMaxTLAB * * @run main/othervm -Xmx64m * -XX:+UnlockExperimentalVMOptions -XX:+UseEpsilonGC * -XX:EpsilonMaxTLABSize=1K - * -XX:+IgnoreUnrecognizedVMOptions -XX:ObjectAlignmentInBytes=16 + * -XX:ObjectAlignmentInBytes=16 * gc.epsilon.TestMaxTLAB * * @run main/othervm -Xmx64m * -XX:+UnlockExperimentalVMOptions -XX:+UseEpsilonGC * -XX:EpsilonMaxTLABSize=1M - * -XX:+IgnoreUnrecognizedVMOptions -XX:ObjectAlignmentInBytes=16 + * -XX:ObjectAlignmentInBytes=16 * gc.epsilon.TestMaxTLAB * * @run main/othervm -Xmx64m * -XX:+UnlockExperimentalVMOptions -XX:+UseEpsilonGC * -XX:EpsilonMaxTLABSize=12345 - * -XX:+IgnoreUnrecognizedVMOptions -XX:ObjectAlignmentInBytes=16 + * -XX:ObjectAlignmentInBytes=16 * gc.epsilon.TestMaxTLAB */ diff --git a/test/hotspot/jtreg/gc/ergonomics/TestDynamicNumberOfGCThreads.java b/test/hotspot/jtreg/gc/ergonomics/TestDynamicNumberOfGCThreads.java index 80f1828c0dd..3e7293a5a92 100644 --- a/test/hotspot/jtreg/gc/ergonomics/TestDynamicNumberOfGCThreads.java +++ b/test/hotspot/jtreg/gc/ergonomics/TestDynamicNumberOfGCThreads.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -73,7 +73,7 @@ private static void testDynamicNumberOfGCThreads(String gcFlag) throws Exception String[] baseArgs = {"-XX:+UnlockExperimentalVMOptions", "-XX:+" + gcFlag, "-Xmx10M", "-XX:+UseDynamicNumberOfGCThreads", "-Xlog:gc+task=trace", GCTest.class.getName()}; // Base test with gc and +UseDynamicNumberOfGCThreads: - ProcessBuilder pb_enabled = ProcessTools.createJavaProcessBuilder(baseArgs); + ProcessBuilder pb_enabled = ProcessTools.createLimitedTestJavaProcessBuilder(baseArgs); verifyDynamicNumberOfGCThreads(new OutputAnalyzer(pb_enabled.start())); // Turn on parallel reference processing @@ -81,7 +81,7 @@ private static void testDynamicNumberOfGCThreads(String gcFlag) throws Exception String[] parRefArgs = new String[baseArgs.length + parRefProcArg.length]; System.arraycopy(parRefProcArg, 0, parRefArgs, 0, parRefProcArg.length); System.arraycopy(baseArgs, 0, parRefArgs, parRefProcArg.length, baseArgs.length); - pb_enabled = ProcessTools.createJavaProcessBuilder(parRefArgs); + pb_enabled = ProcessTools.createLimitedTestJavaProcessBuilder(parRefArgs); verifyDynamicNumberOfGCThreads(new OutputAnalyzer(pb_enabled.start())); } diff --git a/test/hotspot/jtreg/gc/ergonomics/TestInitialGCThreadLogging.java b/test/hotspot/jtreg/gc/ergonomics/TestInitialGCThreadLogging.java index a20721a9e56..dc1b83cd2c1 100644 --- a/test/hotspot/jtreg/gc/ergonomics/TestInitialGCThreadLogging.java +++ b/test/hotspot/jtreg/gc/ergonomics/TestInitialGCThreadLogging.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2023, Oracle and/or its affiliates. All rights reserved. * 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 @@ private static void verifyDynamicNumberOfGCThreads(OutputAnalyzer output, String private static void testInitialGCThreadLogging(String gcFlag, String threadName) throws Exception { // Base test with gc and +UseDynamicNumberOfGCThreads: - ProcessBuilder pb_enabled = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb_enabled = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:+UnlockExperimentalVMOptions", "-XX:+" + gcFlag, "-Xmx10M", diff --git a/test/hotspot/jtreg/gc/g1/Test2GbHeap.java b/test/hotspot/jtreg/gc/g1/Test2GbHeap.java index 125ea34a901..8e06ac3ee2c 100644 --- a/test/hotspot/jtreg/gc/g1/Test2GbHeap.java +++ b/test/hotspot/jtreg/gc/g1/Test2GbHeap.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -49,7 +49,7 @@ public static void main(String[] args) throws Exception { testArguments.add("-Xmx2g"); testArguments.add("-version"); - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(testArguments); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(testArguments); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldHaveExitValue(0); diff --git a/test/hotspot/jtreg/gc/g1/TestEagerReclaimHumongousRegions.java b/test/hotspot/jtreg/gc/g1/TestEagerReclaimHumongousRegions.java index a459c1131ad..a334783eca6 100644 --- a/test/hotspot/jtreg/gc/g1/TestEagerReclaimHumongousRegions.java +++ b/test/hotspot/jtreg/gc/g1/TestEagerReclaimHumongousRegions.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -80,7 +80,7 @@ public static void main(String[] args) { public class TestEagerReclaimHumongousRegions { public static void main(String[] args) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:+UseG1GC", "-Xms128M", "-Xmx128M", diff --git a/test/hotspot/jtreg/gc/g1/TestEagerReclaimHumongousRegionsClearMarkBits.java b/test/hotspot/jtreg/gc/g1/TestEagerReclaimHumongousRegionsClearMarkBits.java index 701917fc7ae..bcb156d9074 100644 --- a/test/hotspot/jtreg/gc/g1/TestEagerReclaimHumongousRegionsClearMarkBits.java +++ b/test/hotspot/jtreg/gc/g1/TestEagerReclaimHumongousRegionsClearMarkBits.java @@ -30,6 +30,7 @@ * mark bitmaps at reclaim. * @key randomness * @requires vm.gc.G1 + * @requires vm.debug * @library /test/lib * @modules java.base/jdk.internal.misc * java.management @@ -118,7 +119,7 @@ public static void main(String[] args) { public class TestEagerReclaimHumongousRegionsClearMarkBits { public static void main(String[] args) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:+UseG1GC", "-Xms128M", "-Xmx128M", @@ -129,7 +130,6 @@ public static void main(String[] args) throws Exception { "-XX:+UnlockDiagnosticVMOptions", "-XX:+VerifyAfterGC", "-XX:ConcGCThreads=1", // Want to make marking as slow as possible. - "-XX:+IgnoreUnrecognizedVMOptions", // G1VerifyBitmaps is develop only. "-XX:+G1VerifyBitmaps", TestEagerReclaimHumongousRegionsClearMarkBitsReclaimRegionFast.class.getName()); OutputAnalyzer output = new OutputAnalyzer(pb.start()); diff --git a/test/hotspot/jtreg/gc/g1/TestEagerReclaimHumongousRegionsLog.java b/test/hotspot/jtreg/gc/g1/TestEagerReclaimHumongousRegionsLog.java index 5f134e290b2..30aee3ced47 100644 --- a/test/hotspot/jtreg/gc/g1/TestEagerReclaimHumongousRegionsLog.java +++ b/test/hotspot/jtreg/gc/g1/TestEagerReclaimHumongousRegionsLog.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -54,7 +54,7 @@ private static String getSumValue(String s) { } public static void runTest() throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-Xbootclasspath/a:.", "-XX:+UnlockExperimentalVMOptions", "-XX:+UnlockDiagnosticVMOptions", diff --git a/test/hotspot/jtreg/gc/g1/TestEagerReclaimHumongousRegionsWithRefs.java b/test/hotspot/jtreg/gc/g1/TestEagerReclaimHumongousRegionsWithRefs.java index b2eaa12e6f3..585f4e867ab 100644 --- a/test/hotspot/jtreg/gc/g1/TestEagerReclaimHumongousRegionsWithRefs.java +++ b/test/hotspot/jtreg/gc/g1/TestEagerReclaimHumongousRegionsWithRefs.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -92,7 +92,7 @@ public static void main(String[] args) { public class TestEagerReclaimHumongousRegionsWithRefs { public static void main(String[] args) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:+UseG1GC", "-Xms128M", "-Xmx128M", diff --git a/test/hotspot/jtreg/gc/g1/TestG1SkipCompaction.java b/test/hotspot/jtreg/gc/g1/TestG1SkipCompaction.java index f5fadcbb880..dbe7d23bb47 100644 --- a/test/hotspot/jtreg/gc/g1/TestG1SkipCompaction.java +++ b/test/hotspot/jtreg/gc/g1/TestG1SkipCompaction.java @@ -21,6 +21,8 @@ * questions. */ +package gc.g1; + /* * @test TestG1SkipCompaction * @summary Test for JDK-8262068 Improve G1 Full GC by skipping compaction @@ -29,7 +31,7 @@ * @library /test/lib * @modules java.base/jdk.internal.misc * java.management - * @run main/othervm -Xms256m -Xmx256m TestG1SkipCompaction + * @run main/othervm -Xms256m -Xmx256m gc.g1.TestG1SkipCompaction */ import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -52,7 +54,7 @@ public static void runTest() throws Exception { "-XX:G1HeapRegionSize=1m", GCTest.class.getName() }; - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(arguments); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(arguments); OutputAnalyzer output = new OutputAnalyzer(pb.start()); System.out.println(output.getStdout()); diff --git a/test/hotspot/jtreg/gc/g1/TestG1TraceEagerReclaimHumongousObjects.java b/test/hotspot/jtreg/gc/g1/TestG1TraceEagerReclaimHumongousObjects.java index 3eafc348a4b..4dedac0a61b 100644 --- a/test/hotspot/jtreg/gc/g1/TestG1TraceEagerReclaimHumongousObjects.java +++ b/test/hotspot/jtreg/gc/g1/TestG1TraceEagerReclaimHumongousObjects.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2023, Oracle and/or its affiliates. All rights reserved. * 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,14 +41,14 @@ public class TestG1TraceEagerReclaimHumongousObjects { public static void main(String[] args) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-XX:+UseG1GC", - "-Xms128M", - "-Xmx128M", - "-Xmn16M", - "-XX:G1HeapRegionSize=1M", - "-Xlog:gc+phases=trace,gc+humongous=trace", - "-XX:+UnlockExperimentalVMOptions", - GCWithHumongousObjectTest.class.getName()); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:+UseG1GC", + "-Xms128M", + "-Xmx128M", + "-Xmn16M", + "-XX:G1HeapRegionSize=1M", + "-Xlog:gc+phases=trace,gc+humongous=trace", + "-XX:+UnlockExperimentalVMOptions", + GCWithHumongousObjectTest.class.getName()); OutputAnalyzer output = new OutputAnalyzer(pb.start()); diff --git a/test/hotspot/jtreg/gc/g1/TestGCLogMessages.java b/test/hotspot/jtreg/gc/g1/TestGCLogMessages.java index 6168b12bb0a..ccd7a7f2554 100644 --- a/test/hotspot/jtreg/gc/g1/TestGCLogMessages.java +++ b/test/hotspot/jtreg/gc/g1/TestGCLogMessages.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -185,26 +185,26 @@ public static void main(String[] args) throws Exception { private void testNormalLogs() throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-XX:+UseG1GC", - "-Xmx10M", - GCTest.class.getName()); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:+UseG1GC", + "-Xmx10M", + GCTest.class.getName()); OutputAnalyzer output = new OutputAnalyzer(pb.start()); checkMessagesAtLevel(output, allLogMessages, Level.OFF); output.shouldHaveExitValue(0); - pb = ProcessTools.createJavaProcessBuilder("-XX:+UseG1GC", - "-Xmx10M", - "-Xlog:gc+phases=debug", - GCTest.class.getName()); + pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:+UseG1GC", + "-Xmx10M", + "-Xlog:gc+phases=debug", + GCTest.class.getName()); output = new OutputAnalyzer(pb.start()); checkMessagesAtLevel(output, allLogMessages, Level.DEBUG); - pb = ProcessTools.createJavaProcessBuilder("-XX:+UseG1GC", - "-Xmx10M", - "-Xlog:gc+phases=trace", - GCTest.class.getName()); + pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:+UseG1GC", + "-Xmx10M", + "-Xlog:gc+phases=trace", + GCTest.class.getName()); output = new OutputAnalyzer(pb.start()); checkMessagesAtLevel(output, allLogMessages, Level.TRACE); @@ -220,10 +220,10 @@ private void testNormalLogs() throws Exception { }; private void testConcurrentRefinementLogs() throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-XX:+UseG1GC", - "-Xmx10M", - "-Xlog:gc+refine+stats=debug", - GCTest.class.getName()); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:+UseG1GC", + "-Xmx10M", + "-Xlog:gc+refine+stats=debug", + GCTest.class.getName()); OutputAnalyzer output = new OutputAnalyzer(pb.start()); checkMessagesAtLevel(output, concRefineMessages, Level.DEBUG); } @@ -235,29 +235,29 @@ private void testConcurrentRefinementLogs() throws Exception { }; private void testWithEvacuationFailureLogs() throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-XX:+UseG1GC", - "-Xmx32M", - "-Xmn16M", - "-XX:+G1EvacuationFailureALot", - "-XX:G1EvacuationFailureALotCount=100", - "-XX:G1EvacuationFailureALotInterval=1", - "-XX:+UnlockDiagnosticVMOptions", - "-XX:-G1UsePreventiveGC", - "-Xlog:gc+phases=debug", - GCTestWithEvacuationFailure.class.getName()); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:+UseG1GC", + "-Xmx32M", + "-Xmn16M", + "-XX:+G1EvacuationFailureALot", + "-XX:G1EvacuationFailureALotCount=100", + "-XX:G1EvacuationFailureALotInterval=1", + "-XX:+UnlockDiagnosticVMOptions", + "-XX:-G1UsePreventiveGC", + "-Xlog:gc+phases=debug", + GCTestWithEvacuationFailure.class.getName()); OutputAnalyzer output = new OutputAnalyzer(pb.start()); checkMessagesAtLevel(output, exhFailureMessages, Level.DEBUG); output.shouldHaveExitValue(0); - pb = ProcessTools.createJavaProcessBuilder("-XX:+UseG1GC", - "-Xmx32M", - "-Xmn16M", - "-Xms32M", - "-XX:+UnlockDiagnosticVMOptions", - "-XX:-G1UsePreventiveGC", - "-Xlog:gc+phases=trace", - GCTestWithEvacuationFailure.class.getName()); + pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:+UseG1GC", + "-Xmx32M", + "-Xmn16M", + "-Xms32M", + "-XX:+UnlockDiagnosticVMOptions", + "-XX:-G1UsePreventiveGC", + "-Xlog:gc+phases=trace", + GCTestWithEvacuationFailure.class.getName()); output = new OutputAnalyzer(pb.start()); checkMessagesAtLevel(output, exhFailureMessages, Level.TRACE); @@ -265,13 +265,13 @@ private void testWithEvacuationFailureLogs() throws Exception { } private void testWithConcurrentStart() throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-XX:+UseG1GC", - "-Xmx10M", - "-Xbootclasspath/a:.", - "-Xlog:gc*=debug", - "-XX:+UnlockDiagnosticVMOptions", - "-XX:+WhiteBoxAPI", - GCTestWithConcurrentStart.class.getName()); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:+UseG1GC", + "-Xmx10M", + "-Xbootclasspath/a:.", + "-Xlog:gc*=debug", + "-XX:+UnlockDiagnosticVMOptions", + "-XX:+WhiteBoxAPI", + GCTestWithConcurrentStart.class.getName()); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldContain("Clear Claimed Marks"); @@ -279,13 +279,13 @@ private void testWithConcurrentStart() throws Exception { } private void testExpandHeap() throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-XX:+UseG1GC", - "-Xmx10M", - "-Xbootclasspath/a:.", - "-Xlog:gc+ergo+heap=debug", - "-XX:+UnlockDiagnosticVMOptions", - "-XX:+WhiteBoxAPI", - GCTest.class.getName()); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:+UseG1GC", + "-Xmx10M", + "-Xbootclasspath/a:.", + "-Xlog:gc+ergo+heap=debug", + "-XX:+UnlockDiagnosticVMOptions", + "-XX:+WhiteBoxAPI", + GCTest.class.getName()); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldContain("Expand the heap. requested expansion amount: "); diff --git a/test/hotspot/jtreg/gc/g1/TestHumongousAllocConcurrentStart.java b/test/hotspot/jtreg/gc/g1/TestHumongousAllocConcurrentStart.java index c399e50aabd..dc8c28a6008 100644 --- a/test/hotspot/jtreg/gc/g1/TestHumongousAllocConcurrentStart.java +++ b/test/hotspot/jtreg/gc/g1/TestHumongousAllocConcurrentStart.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2023, Oracle and/or its affiliates. All rights reserved. * 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 @@ public class TestHumongousAllocConcurrentStart { private static final int initiatingHeapOccupancyPercent = 50; // % public static void main(String[] args) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:+UseG1GC", "-Xms" + heapSize + "m", "-Xmx" + heapSize + "m", diff --git a/test/hotspot/jtreg/gc/g1/TestHumongousAllocNearlyFullRegion.java b/test/hotspot/jtreg/gc/g1/TestHumongousAllocNearlyFullRegion.java index aae56bce361..6d141870ae3 100644 --- a/test/hotspot/jtreg/gc/g1/TestHumongousAllocNearlyFullRegion.java +++ b/test/hotspot/jtreg/gc/g1/TestHumongousAllocNearlyFullRegion.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2023, Oracle and/or its affiliates. All rights reserved. * 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 TestHumongousAllocNearlyFullRegion { private static final int heapRegionSize = 1; // MB public static void main(String[] args) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:+UseG1GC", "-Xms" + heapSize + "m", "-Xmx" + heapSize + "m", diff --git a/test/hotspot/jtreg/gc/g1/TestHumongousCodeCacheRoots.java b/test/hotspot/jtreg/gc/g1/TestHumongousCodeCacheRoots.java index 57b43054039..057b8310de6 100644 --- a/test/hotspot/jtreg/gc/g1/TestHumongousCodeCacheRoots.java +++ b/test/hotspot/jtreg/gc/g1/TestHumongousCodeCacheRoots.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -106,7 +106,7 @@ public static OutputAnalyzer runWhiteBoxTest(String[] vmargs, String classname, finalargs.add(classname); finalargs.addAll(Arrays.asList(arguments)); - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(finalargs); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(finalargs); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldHaveExitValue(0); return output; diff --git a/test/hotspot/jtreg/gc/g1/TestHumongousConcurrentStartUndo.java b/test/hotspot/jtreg/gc/g1/TestHumongousConcurrentStartUndo.java index b16d8d276b0..6376149fbf9 100644 --- a/test/hotspot/jtreg/gc/g1/TestHumongousConcurrentStartUndo.java +++ b/test/hotspot/jtreg/gc/g1/TestHumongousConcurrentStartUndo.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2020, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -56,7 +56,7 @@ public class TestHumongousConcurrentStartUndo { private static final int YoungSize = HeapSize / 8; public static void main(String[] args) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-Xbootclasspath/a:.", "-XX:+UseG1GC", "-Xms" + HeapSize + "m", diff --git a/test/hotspot/jtreg/gc/g1/TestLargePageUseForAuxMemory.java b/test/hotspot/jtreg/gc/g1/TestLargePageUseForAuxMemory.java index df1ab73d405..4fd06522241 100644 --- a/test/hotspot/jtreg/gc/g1/TestLargePageUseForAuxMemory.java +++ b/test/hotspot/jtreg/gc/g1/TestLargePageUseForAuxMemory.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -33,17 +33,21 @@ * @requires vm.opt.LargePageSizeInBytes == null * @build jdk.test.whitebox.WhiteBox * @run driver jdk.test.lib.helpers.ClassFileInstaller jdk.test.whitebox.WhiteBox - * @run main/othervm -Xbootclasspath/a:. -XX:+UseG1GC -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI -XX:+IgnoreUnrecognizedVMOptions -XX:+UseLargePages gc.g1.TestLargePageUseForAuxMemory + * @run main/othervm -Xbootclasspath/a:. -XX:+UseG1GC -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI -XX:+UseLargePages gc.g1.TestLargePageUseForAuxMemory */ +import java.util.ArrayList; +import java.util.List; import java.lang.Math; +import java.util.Collections; import jdk.test.lib.process.OutputAnalyzer; import jdk.test.lib.process.ProcessTools; import jdk.test.lib.Asserts; import jdk.test.lib.Platform; -import jtreg.SkippedException; import jdk.test.whitebox.WhiteBox; +import jtreg.SkippedException; + public class TestLargePageUseForAuxMemory { static final long HEAP_REGION_SIZE = 1 * 1024 * 1024; static long largePageSize; @@ -106,19 +110,22 @@ static void checkBitmaps(OutputAnalyzer output, long expectedPageSize) throws Ex checkSize(output, expectedPageSize, "Next Bitmap: .*page_size=([^ ]+)"); } + static List getOpts(long heapsize, boolean largePageEnabled) { + return List.of("-XX:+UseG1GC", + "-XX:G1HeapRegionSize=" + HEAP_REGION_SIZE, + "-Xmx" + heapsize, + "-Xlog:pagesize,gc+init,gc+heap+coops=debug", + "-XX:" + (largePageEnabled ? "+" : "-") + "UseLargePages", + "-version"); + } + static void testVM(String what, long heapsize, boolean cardsShouldUseLargePages, boolean bitmapShouldUseLargePages) throws Exception { System.out.println(what + " heapsize " + heapsize + " card table should use large pages " + cardsShouldUseLargePages + " " + "bitmaps should use large pages " + bitmapShouldUseLargePages); ProcessBuilder pb; + // Test with large page enabled. - pb = ProcessTools.createJavaProcessBuilder("-XX:+UseG1GC", - "-XX:G1HeapRegionSize=" + HEAP_REGION_SIZE, - "-Xmx" + heapsize, - "-Xlog:pagesize,gc+init,gc+heap+coops=debug", - "-XX:+UseLargePages", - "-XX:+IgnoreUnrecognizedVMOptions", // there is no ObjectAlignmentInBytes in 32 bit builds - "-XX:ObjectAlignmentInBytes=8", - "-version"); + pb = ProcessTools.createLimitedTestJavaProcessBuilder(getOpts(heapsize, true)); OutputAnalyzer output = new OutputAnalyzer(pb.start()); // Only expect large page size if large pages are enabled. @@ -132,14 +139,7 @@ static void testVM(String what, long heapsize, boolean cardsShouldUseLargePages, output.shouldHaveExitValue(0); // Test with large page disabled. - pb = ProcessTools.createJavaProcessBuilder("-XX:+UseG1GC", - "-XX:G1HeapRegionSize=" + HEAP_REGION_SIZE, - "-Xmx" + heapsize, - "-Xlog:pagesize", - "-XX:-UseLargePages", - "-XX:+IgnoreUnrecognizedVMOptions", // there is no ObjectAlignmentInBytes in 32 bit builds - "-XX:ObjectAlignmentInBytes=8", - "-version"); + pb = ProcessTools.createLimitedTestJavaProcessBuilder(getOpts(heapsize, false)); output = new OutputAnalyzer(pb.start()); checkSmallTables(output, smallPageSize); diff --git a/test/hotspot/jtreg/gc/g1/TestLargePageUseForHeap.java b/test/hotspot/jtreg/gc/g1/TestLargePageUseForHeap.java index fde6179ee0d..90f8747f3b3 100644 --- a/test/hotspot/jtreg/gc/g1/TestLargePageUseForHeap.java +++ b/test/hotspot/jtreg/gc/g1/TestLargePageUseForHeap.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -34,7 +34,7 @@ * @build jdk.test.whitebox.WhiteBox * @run driver jdk.test.lib.helpers.ClassFileInstaller jdk.test.whitebox.WhiteBox * @run main/othervm -Xbootclasspath/a:. -XX:+UseG1GC -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI - -XX:+IgnoreUnrecognizedVMOptions -XX:+UseLargePages gc.g1.TestLargePageUseForHeap + -XX:+UseLargePages gc.g1.TestLargePageUseForHeap */ import jdk.test.lib.process.OutputAnalyzer; @@ -87,12 +87,12 @@ static void checkHeap(OutputAnalyzer output, long expectedPageSize) throws Excep static void testVM(long regionSize) throws Exception { ProcessBuilder pb; // Test with large page enabled. - pb = ProcessTools.createJavaProcessBuilder("-XX:+UseG1GC", - "-XX:G1HeapRegionSize=" + regionSize, - "-Xmx128m", - "-Xlog:gc+init,pagesize,gc+heap+coops=debug", - "-XX:+UseLargePages", - "-version"); + pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:+UseG1GC", + "-XX:G1HeapRegionSize=" + regionSize, + "-Xmx128m", + "-Xlog:gc+init,pagesize,gc+heap+coops=debug", + "-XX:+UseLargePages", + "-version"); OutputAnalyzer output = new OutputAnalyzer(pb.start()); boolean largePageEnabled = checkLargePageEnabled(output); @@ -100,12 +100,12 @@ static void testVM(long regionSize) throws Exception { output.shouldHaveExitValue(0); // Test with large page disabled. - pb = ProcessTools.createJavaProcessBuilder("-XX:+UseG1GC", - "-XX:G1HeapRegionSize=" + regionSize, - "-Xmx128m", - "-Xlog:gc+init,pagesize,gc+heap+coops=debug", - "-XX:-UseLargePages", - "-version"); + pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:+UseG1GC", + "-XX:G1HeapRegionSize=" + regionSize, + "-Xmx128m", + "-Xlog:gc+init,pagesize,gc+heap+coops=debug", + "-XX:-UseLargePages", + "-version"); output = new OutputAnalyzer(pb.start()); checkHeap(output, smallPageSize); diff --git a/test/hotspot/jtreg/gc/g1/TestMarkStackSizes.java b/test/hotspot/jtreg/gc/g1/TestMarkStackSizes.java index 7649f358b7f..8d61fa333a5 100644 --- a/test/hotspot/jtreg/gc/g1/TestMarkStackSizes.java +++ b/test/hotspot/jtreg/gc/g1/TestMarkStackSizes.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2020, 2023, Oracle and/or its affiliates. All rights reserved. * 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,7 +50,7 @@ private static void runTest(boolean shouldSucceed, String... extraArgs) throws E Collections.addAll(testArguments, extraArgs); testArguments.add("-version"); - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(testArguments); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(testArguments); OutputAnalyzer output = new OutputAnalyzer(pb.start()); diff --git a/test/hotspot/jtreg/gc/g1/TestMixedGCLiveThreshold.java b/test/hotspot/jtreg/gc/g1/TestMixedGCLiveThreshold.java index a17d0f41e25..4c0619cd2b3 100644 --- a/test/hotspot/jtreg/gc/g1/TestMixedGCLiveThreshold.java +++ b/test/hotspot/jtreg/gc/g1/TestMixedGCLiveThreshold.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2021, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -109,7 +109,7 @@ private static OutputAnalyzer testWithMixedGCLiveThresholdPercent(int percent) t basicOpts.add(GCTest.class.getName()); - ProcessBuilder procBuilder = ProcessTools.createJavaProcessBuilder(basicOpts); + ProcessBuilder procBuilder = ProcessTools.createLimitedTestJavaProcessBuilder(basicOpts); OutputAnalyzer analyzer = new OutputAnalyzer(procBuilder.start()); return analyzer; } diff --git a/test/hotspot/jtreg/gc/g1/TestPLABOutput.java b/test/hotspot/jtreg/gc/g1/TestPLABOutput.java index 1462b8d246b..13a496ca47e 100644 --- a/test/hotspot/jtreg/gc/g1/TestPLABOutput.java +++ b/test/hotspot/jtreg/gc/g1/TestPLABOutput.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2023, Oracle and/or its affiliates. All rights reserved. * 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,7 +59,7 @@ public static void runTest() throws Exception { GCTest.class.getName() }; - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(arguments); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(arguments); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldHaveExitValue(0); diff --git a/test/hotspot/jtreg/gc/g1/TestPLABSizeBounds.java b/test/hotspot/jtreg/gc/g1/TestPLABSizeBounds.java index 4ba04a38712..6c1e7f16dd3 100644 --- a/test/hotspot/jtreg/gc/g1/TestPLABSizeBounds.java +++ b/test/hotspot/jtreg/gc/g1/TestPLABSizeBounds.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2023, Oracle and/or its affiliates. All rights reserved. * 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 static void runTest(int regionSize, int plabSize, boolean shouldSucceed) testArguments.add("-XX:OldPLABSize=" + plabSize); testArguments.add(GCTest.class.getName()); - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(testArguments); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(testArguments); OutputAnalyzer output = new OutputAnalyzer(pb.start()); if (shouldSucceed) { diff --git a/test/hotspot/jtreg/gc/g1/TestPeriodicLogMessages.java b/test/hotspot/jtreg/gc/g1/TestPeriodicLogMessages.java index 5634aa143b2..c80ab7a50e8 100644 --- a/test/hotspot/jtreg/gc/g1/TestPeriodicLogMessages.java +++ b/test/hotspot/jtreg/gc/g1/TestPeriodicLogMessages.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 2023, Oracle and/or its affiliates. All rights reserved. * 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,22 +40,22 @@ public class TestPeriodicLogMessages { public static void main(String[] args) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-XX:+UseG1GC", - "-XX:G1PeriodicGCInterval=0", - "-Xlog:gc+init,gc+periodic=debug", - "-Xmx10M", - GCTest.class.getName()); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:+UseG1GC", + "-XX:G1PeriodicGCInterval=0", + "-Xlog:gc+init,gc+periodic=debug", + "-Xmx10M", + GCTest.class.getName()); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldContain("Periodic GC: Disabled"); output.shouldNotContain("Checking for periodic GC"); output.shouldHaveExitValue(0); - pb = ProcessTools.createJavaProcessBuilder("-XX:+UseG1GC", - "-XX:G1PeriodicGCInterval=100", - "-Xlog:gc+init,gc+periodic=debug", - "-Xmx10M", - GCTest.class.getName()); + pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:+UseG1GC", + "-XX:G1PeriodicGCInterval=100", + "-Xlog:gc+init,gc+periodic=debug", + "-Xmx10M", + GCTest.class.getName()); output = new OutputAnalyzer(pb.start()); output.shouldContain("Periodic GC: Enabled"); diff --git a/test/hotspot/jtreg/gc/g1/TestPrintRegionRememberedSetInfo.java b/test/hotspot/jtreg/gc/g1/TestPrintRegionRememberedSetInfo.java index 08afcfc9aee..bc4d59d9a3c 100644 --- a/test/hotspot/jtreg/gc/g1/TestPrintRegionRememberedSetInfo.java +++ b/test/hotspot/jtreg/gc/g1/TestPrintRegionRememberedSetInfo.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -69,7 +69,7 @@ public static String runTest(String arg) throws Exception { finalargs.add(RunAndWaitForMarking.class.getName()); - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(finalargs); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(finalargs); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldHaveExitValue(0); diff --git a/test/hotspot/jtreg/gc/g1/TestRemsetLoggingThreads.java b/test/hotspot/jtreg/gc/g1/TestRemsetLoggingThreads.java index 8d8f77db81a..5d4b4d958f8 100644 --- a/test/hotspot/jtreg/gc/g1/TestRemsetLoggingThreads.java +++ b/test/hotspot/jtreg/gc/g1/TestRemsetLoggingThreads.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -44,12 +44,12 @@ public class TestRemsetLoggingThreads { private static void runTest(int refinementThreads, int workerThreads) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-XX:+UseG1GC", - "-XX:+UnlockDiagnosticVMOptions", - "-Xlog:gc+remset+exit=trace", - "-XX:G1ConcRefinementThreads=" + refinementThreads, - "-XX:ParallelGCThreads=" + workerThreads, - "-version"); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:+UseG1GC", + "-XX:+UnlockDiagnosticVMOptions", + "-Xlog:gc+remset+exit=trace", + "-XX:G1ConcRefinementThreads=" + refinementThreads, + "-XX:ParallelGCThreads=" + workerThreads, + "-version"); OutputAnalyzer output = new OutputAnalyzer(pb.start()); diff --git a/test/hotspot/jtreg/gc/g1/TestRemsetLoggingTools.java b/test/hotspot/jtreg/gc/g1/TestRemsetLoggingTools.java index 17777427916..89f3871e774 100644 --- a/test/hotspot/jtreg/gc/g1/TestRemsetLoggingTools.java +++ b/test/hotspot/jtreg/gc/g1/TestRemsetLoggingTools.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -77,7 +77,7 @@ public static String runTest(String[] additionalArgs, int numGCs) throws Excepti finalargs.add(VerifySummaryOutput.class.getName()); finalargs.add(String.valueOf(numGCs)); - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(finalargs); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(finalargs); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldHaveExitValue(0); diff --git a/test/hotspot/jtreg/gc/g1/TestSharedArchiveWithPreTouch.java b/test/hotspot/jtreg/gc/g1/TestSharedArchiveWithPreTouch.java index 841ed393392..d894c58d737 100644 --- a/test/hotspot/jtreg/gc/g1/TestSharedArchiveWithPreTouch.java +++ b/test/hotspot/jtreg/gc/g1/TestSharedArchiveWithPreTouch.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2023, Oracle and/or its affiliates. All rights reserved. * 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,7 +59,7 @@ public static void main(String[] args) throws Exception { } dump_args.addAll(Arrays.asList(new String[] { "-Xshare:dump", "-Xlog:cds" })); - pb = ProcessTools.createJavaProcessBuilder(dump_args); + pb = ProcessTools.createLimitedTestJavaProcessBuilder(dump_args); OutputAnalyzer output = new OutputAnalyzer(pb.start()); try { output.shouldContain("Loading classes to share"); @@ -72,7 +72,7 @@ public static void main(String[] args) throws Exception { } load_args.addAll(Arrays.asList(new String[] { "-Xshare:on", "-version" })); - pb = ProcessTools.createJavaProcessBuilder(load_args.toArray(new String[0])); + pb = ProcessTools.createLimitedTestJavaProcessBuilder(load_args.toArray(new String[0])); output = new OutputAnalyzer(pb.start()); output.shouldContain("sharing"); output.shouldHaveExitValue(0); diff --git a/test/hotspot/jtreg/gc/g1/TestShrinkAuxiliaryData.java b/test/hotspot/jtreg/gc/g1/TestShrinkAuxiliaryData.java index 1b38c2d4c26..2596ff788e7 100644 --- a/test/hotspot/jtreg/gc/g1/TestShrinkAuxiliaryData.java +++ b/test/hotspot/jtreg/gc/g1/TestShrinkAuxiliaryData.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -101,7 +101,7 @@ protected void test() throws Exception { } private void performTest(List opts) throws Exception { - ProcessBuilder pb = ProcessTools.createTestJvm(opts); + ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder(opts); OutputAnalyzer output = new OutputAnalyzer(pb.start()); System.out.println(output.getStdout()); diff --git a/test/hotspot/jtreg/gc/g1/TestShrinkDefragmentedHeap.java b/test/hotspot/jtreg/gc/g1/TestShrinkDefragmentedHeap.java index 3f41a8f45f8..acdce6b6417 100644 --- a/test/hotspot/jtreg/gc/g1/TestShrinkDefragmentedHeap.java +++ b/test/hotspot/jtreg/gc/g1/TestShrinkDefragmentedHeap.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2023, Oracle and/or its affiliates. All rights reserved. * 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,7 @@ public class TestShrinkDefragmentedHeap { private static final int REGION_SIZE = 1 * 1024 * 1024; public static void main(String[] args) throws Exception, Throwable { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:InitialHeapSize=" + INITIAL_HEAP_SIZE, "-Xmn" + MINIMAL_YOUNG_SIZE, "-Xmx" + MAXIMUM_HEAP_SIZE, diff --git a/test/hotspot/jtreg/gc/g1/TestSkipRebuildRemsetPhase.java b/test/hotspot/jtreg/gc/g1/TestSkipRebuildRemsetPhase.java index 860d3ce48c7..33217d1c51d 100644 --- a/test/hotspot/jtreg/gc/g1/TestSkipRebuildRemsetPhase.java +++ b/test/hotspot/jtreg/gc/g1/TestSkipRebuildRemsetPhase.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2021, 2023, Oracle and/or its affiliates. All rights reserved. * 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,16 +40,16 @@ public class TestSkipRebuildRemsetPhase { public static void main(String[] args) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-Xbootclasspath/a:.", - "-XX:+UseG1GC", - "-XX:+UnlockExperimentalVMOptions", - "-XX:+UnlockDiagnosticVMOptions", - "-XX:+WhiteBoxAPI", - "-XX:G1MixedGCLiveThresholdPercent=20", - "-Xlog:gc+marking=debug,gc+phases=debug,gc+remset+tracking=trace", - "-Xms10M", - "-Xmx10M", - GCTest.class.getName()); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-Xbootclasspath/a:.", + "-XX:+UseG1GC", + "-XX:+UnlockExperimentalVMOptions", + "-XX:+UnlockDiagnosticVMOptions", + "-XX:+WhiteBoxAPI", + "-XX:G1MixedGCLiveThresholdPercent=20", + "-Xlog:gc+marking=debug,gc+phases=debug,gc+remset+tracking=trace", + "-Xms10M", + "-Xmx10M", + GCTest.class.getName()); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldContain("Skipping Remembered Set Rebuild."); output.shouldContain("No Remembered Sets to update after rebuild"); diff --git a/test/hotspot/jtreg/gc/g1/TestVerifyGCType.java b/test/hotspot/jtreg/gc/g1/TestVerifyGCType.java index 8331d6c5baa..e2f3399de35 100644 --- a/test/hotspot/jtreg/gc/g1/TestVerifyGCType.java +++ b/test/hotspot/jtreg/gc/g1/TestVerifyGCType.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -153,7 +153,7 @@ private static OutputAnalyzer testWithVerificationType(String[] types) throws Ex basicOpts.add(TriggerGCs.class.getName()); - ProcessBuilder procBuilder = ProcessTools.createJavaProcessBuilder(basicOpts); + ProcessBuilder procBuilder = ProcessTools.createLimitedTestJavaProcessBuilder(basicOpts); OutputAnalyzer analyzer = new OutputAnalyzer(procBuilder.start()); return analyzer; } diff --git a/test/hotspot/jtreg/gc/g1/mixedgc/TestLogging.java b/test/hotspot/jtreg/gc/g1/mixedgc/TestLogging.java index 9cb1cdf7583..e4b4074264d 100644 --- a/test/hotspot/jtreg/gc/g1/mixedgc/TestLogging.java +++ b/test/hotspot/jtreg/gc/g1/mixedgc/TestLogging.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -90,7 +90,7 @@ private static OutputAnalyzer spawnMixedGCProvoker(String... extraFlags) Collections.addAll(testOpts, extraFlags); testOpts.add(RunMixedGC.class.getName()); System.out.println(testOpts); - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(testOpts); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(testOpts); return new OutputAnalyzer(pb.start()); } } diff --git a/test/hotspot/jtreg/gc/g1/numa/TestG1NUMATouchRegions.java b/test/hotspot/jtreg/gc/g1/numa/TestG1NUMATouchRegions.java index 500eb5eff34..4d231080a24 100644 --- a/test/hotspot/jtreg/gc/g1/numa/TestG1NUMATouchRegions.java +++ b/test/hotspot/jtreg/gc/g1/numa/TestG1NUMATouchRegions.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,7 +21,7 @@ * questions. */ -package gc.g1; +package gc.g1.numa; /** * @test TestG1NUMATouchRegions @@ -33,7 +33,9 @@ * java.management * @build jdk.test.whitebox.WhiteBox * @run driver jdk.test.lib.helpers.ClassFileInstaller jdk.test.whitebox.WhiteBox - * @run main/othervm -XX:+UseG1GC -Xbootclasspath/a:. -XX:+UseNUMA -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI gc.g1.TestG1NUMATouchRegions + * @run main/othervm -XX:+UseG1GC -Xbootclasspath/a:. -XX:+UseNUMA + * -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI + * gc.g1.numa.TestG1NUMATouchRegions */ import java.util.LinkedList; @@ -179,7 +181,7 @@ static void testMemoryTouch(String largePagesSetting, int regionSizeInMB) throws return; } - ProcessBuilder pb_enabled = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb_enabled = ProcessTools.createLimitedTestJavaProcessBuilder( "-Xbootclasspath/a:.", "-Xlog:pagesize,gc+heap+region=trace", "-XX:+UseG1GC", diff --git a/test/hotspot/jtreg/gc/logging/TestDeprecatedPrintFlags.java b/test/hotspot/jtreg/gc/logging/TestDeprecatedPrintFlags.java index cedb42c2e2f..04607502a22 100644 --- a/test/hotspot/jtreg/gc/logging/TestDeprecatedPrintFlags.java +++ b/test/hotspot/jtreg/gc/logging/TestDeprecatedPrintFlags.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -42,7 +42,7 @@ public class TestDeprecatedPrintFlags { public static void testPrintGC() throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-XX:+PrintGC", DoGC.class.getName()); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:+PrintGC", DoGC.class.getName()); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldContain("-XX:+PrintGC is deprecated. Will use -Xlog:gc instead."); output.shouldNotContain("PrintGCDetails"); @@ -52,7 +52,7 @@ public static void testPrintGC() throws Exception { } public static void testPrintGCDetails() throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-XX:+PrintGCDetails", DoGC.class.getName()); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:+PrintGCDetails", DoGC.class.getName()); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldContain("-XX:+PrintGCDetails is deprecated. Will use -Xlog:gc* instead."); output.shouldNotContain("PrintGC is deprecated"); @@ -63,7 +63,7 @@ public static void testPrintGCDetails() throws Exception { public static void testXloggc() throws Exception { String fileName = "gc-test.log"; - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-Xloggc:" + fileName, DoGC.class.getName()); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-Xloggc:" + fileName, DoGC.class.getName()); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldContain("-Xloggc is deprecated. Will use -Xlog:gc:gc-test.log instead."); output.shouldNotContain("PrintGCDetails"); @@ -80,7 +80,7 @@ public static void testXloggc() throws Exception { public static void testXloggcWithPrintGCDetails() throws Exception { String fileName = "gc-test.log"; - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-XX:+PrintGCDetails", "-Xloggc:" + fileName, DoGC.class.getName()); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:+PrintGCDetails", "-Xloggc:" + fileName, DoGC.class.getName()); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldContain("-XX:+PrintGCDetails is deprecated. Will use -Xlog:gc* instead."); output.shouldContain("-Xloggc is deprecated. Will use -Xlog:gc:gc-test.log instead."); diff --git a/test/hotspot/jtreg/gc/logging/TestGCId.java b/test/hotspot/jtreg/gc/logging/TestGCId.java index f720bfac7ab..dca1681e0e8 100644 --- a/test/hotspot/jtreg/gc/logging/TestGCId.java +++ b/test/hotspot/jtreg/gc/logging/TestGCId.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -74,7 +74,7 @@ private static void verifyContainsGCIDs(OutputAnalyzer output) { private static void testGCId(String gcFlag) throws Exception { ProcessBuilder pb_default = - ProcessTools.createJavaProcessBuilder("-XX:+UnlockExperimentalVMOptions", "-XX:+" + gcFlag, "-Xlog:gc", "-Xmx10M", GCTest.class.getName()); + ProcessTools.createLimitedTestJavaProcessBuilder("-XX:+UnlockExperimentalVMOptions", "-XX:+" + gcFlag, "-Xlog:gc", "-Xmx10M", GCTest.class.getName()); verifyContainsGCIDs(new OutputAnalyzer(pb_default.start())); } diff --git a/test/hotspot/jtreg/gc/logging/TestMetaSpaceLog.java b/test/hotspot/jtreg/gc/logging/TestMetaSpaceLog.java index 659f7ed9a47..260a62eb5bd 100644 --- a/test/hotspot/jtreg/gc/logging/TestMetaSpaceLog.java +++ b/test/hotspot/jtreg/gc/logging/TestMetaSpaceLog.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2023, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2018, Google and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -95,7 +95,7 @@ private static void testMetaSpaceUpdate() throws Exception { String testSrc= "-Dtest.src=" + System.getProperty("test.src", "."); ProcessBuilder pb = - ProcessTools.createTestJvm( + ProcessTools.createTestJavaProcessBuilder( "-Xlog:gc*", "-Xbootclasspath/a:.", "-XX:+UnlockDiagnosticVMOptions", diff --git a/test/hotspot/jtreg/gc/logging/TestPrintReferences.java b/test/hotspot/jtreg/gc/logging/TestPrintReferences.java index c671f301e3a..4b0789be926 100644 --- a/test/hotspot/jtreg/gc/logging/TestPrintReferences.java +++ b/test/hotspot/jtreg/gc/logging/TestPrintReferences.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -68,10 +68,10 @@ static String indent(int count) { } public static void testRefs() throws Exception { - ProcessBuilder pb_enabled = ProcessTools.createJavaProcessBuilder("-Xlog:gc+ref+phases=debug", - "-XX:+UseG1GC", - "-Xmx32M", - GCTest.class.getName()); + ProcessBuilder pb_enabled = ProcessTools.createLimitedTestJavaProcessBuilder("-Xlog:gc+ref+phases=debug", + "-XX:+UseG1GC", + "-Xmx32M", + GCTest.class.getName()); OutputAnalyzer output = new OutputAnalyzer(pb_enabled.start()); checkRefsLogFormat(output); @@ -94,13 +94,13 @@ private static void checkRefsLogFormat(OutputAnalyzer output) { } public static void testPhases(boolean parallelRefProcEnabled) throws Exception { - ProcessBuilder pb_enabled = ProcessTools.createJavaProcessBuilder("-Xlog:gc+phases+ref=debug", - "-XX:+UseG1GC", - "-Xmx32M", - "-XX:" + (parallelRefProcEnabled ? "+" : "-") + "ParallelRefProcEnabled", - "-XX:-UseDynamicNumberOfGCThreads", - "-XX:ParallelGCThreads=2", - GCTest.class.getName()); + ProcessBuilder pb_enabled = ProcessTools.createLimitedTestJavaProcessBuilder("-Xlog:gc+phases+ref=debug", + "-XX:+UseG1GC", + "-Xmx32M", + "-XX:" + (parallelRefProcEnabled ? "+" : "-") + "ParallelRefProcEnabled", + "-XX:-UseDynamicNumberOfGCThreads", + "-XX:ParallelGCThreads=2", + GCTest.class.getName()); OutputAnalyzer output = new OutputAnalyzer(pb_enabled.start()); checkLogFormat(output, parallelRefProcEnabled); diff --git a/test/hotspot/jtreg/gc/metaspace/TestMetaspaceMemoryPool.java b/test/hotspot/jtreg/gc/metaspace/TestMetaspaceMemoryPool.java index 2caf4f77a71..71cf2003ddd 100644 --- a/test/hotspot/jtreg/gc/metaspace/TestMetaspaceMemoryPool.java +++ b/test/hotspot/jtreg/gc/metaspace/TestMetaspaceMemoryPool.java @@ -37,11 +37,12 @@ * @library / * @modules java.base/jdk.internal.misc * java.management - * @run main/othervm -XX:+IgnoreUnrecognizedVMOptions -XX:-UseCompressedOops gc.metaspace.TestMetaspaceMemoryPool - * @run main/othervm -XX:+IgnoreUnrecognizedVMOptions -XX:-UseCompressedOops -XX:MaxMetaspaceSize=60m gc.metaspace.TestMetaspaceMemoryPool - * @run main/othervm -XX:+IgnoreUnrecognizedVMOptions -XX:+UseCompressedOops -XX:+UseCompressedClassPointers gc.metaspace.TestMetaspaceMemoryPool - * @run main/othervm -XX:+IgnoreUnrecognizedVMOptions -XX:+UseCompressedOops -XX:+UseCompressedClassPointers -XX:CompressedClassSpaceSize=60m gc.metaspace.TestMetaspaceMemoryPool + * @run main/othervm -XX:-UseCompressedOops gc.metaspace.TestMetaspaceMemoryPool + * @run main/othervm -XX:-UseCompressedOops -XX:MaxMetaspaceSize=60m gc.metaspace.TestMetaspaceMemoryPool + * @run main/othervm -XX:+UseCompressedOops -XX:+UseCompressedClassPointers gc.metaspace.TestMetaspaceMemoryPool + * @run main/othervm -XX:+UseCompressedOops -XX:+UseCompressedClassPointers -XX:CompressedClassSpaceSize=60m gc.metaspace.TestMetaspaceMemoryPool */ + public class TestMetaspaceMemoryPool { public static void main(String[] args) { verifyThatMetaspaceMemoryManagerExists(); diff --git a/test/hotspot/jtreg/gc/metaspace/TestMetaspacePerfCounters.java b/test/hotspot/jtreg/gc/metaspace/TestMetaspacePerfCounters.java index f6f7c9af999..34cc36b9d51 100644 --- a/test/hotspot/jtreg/gc/metaspace/TestMetaspacePerfCounters.java +++ b/test/hotspot/jtreg/gc/metaspace/TestMetaspacePerfCounters.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2022, Oracle and/or its affiliates. All rights reserved. * 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,10 @@ import gc.testlibrary.PerfCounter; import gc.testlibrary.PerfCounters; -/* @test TestMetaspacePerfCountersSerial +/* @test id=Serial-64 * @bug 8014659 * @requires vm.gc.Serial + * @requires vm.bits == "64" * @library /test/lib / * @summary Tests that performance counters for metaspace and compressed class * space exists and works. @@ -47,13 +48,14 @@ * java.compiler * java.management/sun.management * jdk.internal.jvmstat/sun.jvmstat.monitor - * @run main/othervm -XX:+IgnoreUnrecognizedVMOptions -XX:-UseCompressedOops -XX:-UseCompressedClassPointers -XX:+UsePerfData -XX:+UseSerialGC gc.metaspace.TestMetaspacePerfCounters - * @run main/othervm -XX:+IgnoreUnrecognizedVMOptions -XX:+UseCompressedOops -XX:+UseCompressedClassPointers -XX:+UsePerfData -XX:+UseSerialGC gc.metaspace.TestMetaspacePerfCounters + * @run main/othervm -XX:-UseCompressedOops -XX:-UseCompressedClassPointers -XX:+UsePerfData -XX:+UseSerialGC gc.metaspace.TestMetaspacePerfCounters + * @run main/othervm -XX:+UseCompressedOops -XX:+UseCompressedClassPointers -XX:+UsePerfData -XX:+UseSerialGC gc.metaspace.TestMetaspacePerfCounters */ -/* @test TestMetaspacePerfCountersParallel +/* @test id=Parallel-64 * @bug 8014659 * @requires vm.gc.Parallel + * @requires vm.bits == "64" * @library /test/lib / * @summary Tests that performance counters for metaspace and compressed class * space exists and works. @@ -61,13 +63,14 @@ * java.compiler * java.management/sun.management * jdk.internal.jvmstat/sun.jvmstat.monitor - * @run main/othervm -XX:+IgnoreUnrecognizedVMOptions -XX:-UseCompressedOops -XX:-UseCompressedClassPointers -XX:+UsePerfData -XX:+UseParallelGC gc.metaspace.TestMetaspacePerfCounters - * @run main/othervm -XX:+IgnoreUnrecognizedVMOptions -XX:+UseCompressedOops -XX:+UseCompressedClassPointers -XX:+UsePerfData -XX:+UseParallelGC gc.metaspace.TestMetaspacePerfCounters + * @run main/othervm -XX:-UseCompressedOops -XX:-UseCompressedClassPointers -XX:+UsePerfData -XX:+UseParallelGC gc.metaspace.TestMetaspacePerfCounters + * @run main/othervm -XX:+UseCompressedOops -XX:+UseCompressedClassPointers -XX:+UsePerfData -XX:+UseParallelGC gc.metaspace.TestMetaspacePerfCounters */ -/* @test TestMetaspacePerfCountersG1 +/* @test id=G1-64 * @bug 8014659 * @requires vm.gc.G1 + * @requires vm.bits == "64" * @library /test/lib / * @summary Tests that performance counters for metaspace and compressed class * space exists and works. @@ -75,13 +78,14 @@ * java.compiler * java.management/sun.management * jdk.internal.jvmstat/sun.jvmstat.monitor - * @run main/othervm -XX:+IgnoreUnrecognizedVMOptions -XX:-UseCompressedOops -XX:-UseCompressedClassPointers -XX:+UsePerfData -XX:+UseG1GC gc.metaspace.TestMetaspacePerfCounters - * @run main/othervm -XX:+IgnoreUnrecognizedVMOptions -XX:+UseCompressedOops -XX:+UseCompressedClassPointers -XX:+UsePerfData -XX:+UseG1GC gc.metaspace.TestMetaspacePerfCounters + * @run main/othervm -XX:-UseCompressedOops -XX:-UseCompressedClassPointers -XX:+UsePerfData -XX:+UseG1GC gc.metaspace.TestMetaspacePerfCounters + * @run main/othervm -XX:+UseCompressedOops -XX:+UseCompressedClassPointers -XX:+UsePerfData -XX:+UseG1GC gc.metaspace.TestMetaspacePerfCounters */ -/* @test TestMetaspacePerfCountersShenandoah +/* @test id=Shenandoah-64 * @bug 8014659 * @requires vm.gc.Shenandoah + * @requires vm.bits == "64" * @library /test/lib / * @summary Tests that performance counters for metaspace and compressed class * space exists and works. @@ -89,9 +93,96 @@ * java.compiler * java.management/sun.management * jdk.internal.jvmstat/sun.jvmstat.monitor - * @run main/othervm -XX:+IgnoreUnrecognizedVMOptions -XX:-UseCompressedOops -XX:-UseCompressedClassPointers -XX:+UsePerfData -XX:+UnlockExperimentalVMOptions -XX:+UseShenandoahGC gc.metaspace.TestMetaspacePerfCounters - * @run main/othervm -XX:+IgnoreUnrecognizedVMOptions -XX:+UseCompressedOops -XX:+UseCompressedClassPointers -XX:+UsePerfData -XX:+UnlockExperimentalVMOptions -XX:+UseShenandoahGC gc.metaspace.TestMetaspacePerfCounters + * @run main/othervm -XX:-UseCompressedOops -XX:-UseCompressedClassPointers -XX:+UsePerfData -XX:+UseShenandoahGC gc.metaspace.TestMetaspacePerfCounters + * @run main/othervm -XX:+UseCompressedOops -XX:+UseCompressedClassPointers -XX:+UsePerfData -XX:+UseShenandoahGC gc.metaspace.TestMetaspacePerfCounters */ + +/* @test id=Epsilon-64 + * @bug 8014659 + * @requires vm.gc.Epsilon + * @requires vm.bits == "64" + * @library /test/lib / + * @summary Tests that performance counters for metaspace and compressed class + * space exists and works. + * @modules java.base/jdk.internal.misc + * java.compiler + * java.management/sun.management + * jdk.internal.jvmstat/sun.jvmstat.monitor + * @run main/othervm -XX:+UnlockExperimentalVMOptions -XX:-UseCompressedOops -XX:-UseCompressedClassPointers -XX:+UsePerfData -XX:+UseEpsilonGC gc.metaspace.TestMetaspacePerfCounters + * @run main/othervm -XX:+UnlockExperimentalVMOptions -XX:+UseCompressedOops -XX:+UseCompressedClassPointers -XX:+UsePerfData -XX:+UseEpsilonGC gc.metaspace.TestMetaspacePerfCounters + */ + +/* @test id=Serial-32 + * @bug 8014659 + * @requires vm.gc.Serial + * @requires vm.bits == "32" + * @library /test/lib / + * @summary Tests that performance counters for metaspace and compressed class + * space exists and works. + * @modules java.base/jdk.internal.misc + * java.compiler + * java.management/sun.management + * jdk.internal.jvmstat/sun.jvmstat.monitor + * @run main/othervm -XX:+UsePerfData -XX:+UseSerialGC gc.metaspace.TestMetaspacePerfCounters + */ + +/* @test id=Parallel-32 + * @bug 8014659 + * @requires vm.gc.Parallel + * @requires vm.bits == "32" + * @library /test/lib / + * @summary Tests that performance counters for metaspace and compressed class + * space exists and works. + * @modules java.base/jdk.internal.misc + * java.compiler + * java.management/sun.management + * jdk.internal.jvmstat/sun.jvmstat.monitor + * @run main/othervm -XX:+UsePerfData -XX:+UseParallelGC gc.metaspace.TestMetaspacePerfCounters + */ + +/* @test id=G1-32 + * @bug 8014659 + * @requires vm.gc.G1 + * @requires vm.bits == "32" + * @library /test/lib / + * @summary Tests that performance counters for metaspace and compressed class + * space exists and works. + * @modules java.base/jdk.internal.misc + * java.compiler + * java.management/sun.management + * jdk.internal.jvmstat/sun.jvmstat.monitor + * @run main/othervm -XX:+UsePerfData -XX:+UseG1GC gc.metaspace.TestMetaspacePerfCounters + */ + +/* @test id=Shenandoah-32 + * @bug 8014659 + * @requires vm.gc.Shenandoah + * @requires vm.bits == "32" + * @library /test/lib / + * @summary Tests that performance counters for metaspace and compressed class + * space exists and works. + * @modules java.base/jdk.internal.misc + * java.compiler + * java.management/sun.management + * jdk.internal.jvmstat/sun.jvmstat.monitor + * @run main/othervm -XX:+UsePerfData -XX:+UseShenandoahGC gc.metaspace.TestMetaspacePerfCounters + */ + + +/* @test id=Epsilon-32 + * @bug 8014659 + * @requires vm.gc.Epsilon + * @requires vm.bits == "32" + * @library /test/lib / + * @summary Tests that performance counters for metaspace and compressed class + * space exists and works. + * @modules java.base/jdk.internal.misc + * java.compiler + * java.management/sun.management + * jdk.internal.jvmstat/sun.jvmstat.monitor + * @run main/othervm -XX:+UsePerfData -XX:+UnlockExperimentalVMOptions -XX:+UseEpsilonGC gc.metaspace.TestMetaspacePerfCounters + */ + public class TestMetaspacePerfCounters { public static Class fooClass = null; private static final String[] counterNames = {"minCapacity", "maxCapacity", "capacity", "used"}; diff --git a/test/hotspot/jtreg/gc/metaspace/TestMetaspaceSizeFlags.java b/test/hotspot/jtreg/gc/metaspace/TestMetaspaceSizeFlags.java index d717315b93f..eda71fa9c4b 100644 --- a/test/hotspot/jtreg/gc/metaspace/TestMetaspaceSizeFlags.java +++ b/test/hotspot/jtreg/gc/metaspace/TestMetaspaceSizeFlags.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -84,7 +84,7 @@ private static MetaspaceFlags runAndGetValue(long maxMetaspaceSize, long metaspa } private static OutputAnalyzer run(long maxMetaspaceSize, long metaspaceSize) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:MaxMetaspaceSize=" + maxMetaspaceSize, "-XX:MetaspaceSize=" + metaspaceSize, "-XX:-UseLargePages", // Prevent us from using 2GB large pages on solaris + sparc. diff --git a/test/hotspot/jtreg/gc/metaspace/TestPerfCountersAndMemoryPools.java b/test/hotspot/jtreg/gc/metaspace/TestPerfCountersAndMemoryPools.java index 1dd929afebd..149183e9db4 100644 --- a/test/hotspot/jtreg/gc/metaspace/TestPerfCountersAndMemoryPools.java +++ b/test/hotspot/jtreg/gc/metaspace/TestPerfCountersAndMemoryPools.java @@ -34,13 +34,27 @@ * @bug 8023476 * @library /test/lib / * @requires vm.gc.Serial + * @requires vm.bits == "64" * @summary Tests that a MemoryPoolMXBeans and PerfCounters for metaspace * report the same data. * @modules java.base/jdk.internal.misc * java.management * jdk.internal.jvmstat/sun.jvmstat.monitor - * @run main/othervm -XX:+IgnoreUnrecognizedVMOptions -XX:-UseCompressedOops -XX:-UseCompressedClassPointers -XX:+UseSerialGC -XX:+UsePerfData -Xint gc.metaspace.TestPerfCountersAndMemoryPools - * @run main/othervm -XX:+IgnoreUnrecognizedVMOptions -XX:+UseCompressedOops -XX:+UseCompressedClassPointers -XX:+UseSerialGC -XX:+UsePerfData -Xint gc.metaspace.TestPerfCountersAndMemoryPools + * @run main/othervm -XX:-UseCompressedOops -XX:-UseCompressedClassPointers -XX:+UseSerialGC -XX:+UsePerfData -Xint gc.metaspace.TestPerfCountersAndMemoryPools + * @run main/othervm -XX:+UseCompressedOops -XX:+UseCompressedClassPointers -XX:+UseSerialGC -XX:+UsePerfData -Xint gc.metaspace.TestPerfCountersAndMemoryPools + */ + +/* @test TestPerfCountersAndMemoryPools + * @bug 8023476 + * @library /test/lib / + * @requires vm.gc.Serial + * @requires vm.bits == "32" + * @summary Tests that a MemoryPoolMXBeans and PerfCounters for metaspace + * report the same data. + * @modules java.base/jdk.internal.misc + * java.management + * jdk.internal.jvmstat/sun.jvmstat.monitor + * @run main/othervm -Xlog:class+load,class+unload=trace -XX:+UseSerialGC -XX:+UsePerfData -Xint gc.metaspace.TestPerfCountersAndMemoryPools */ public class TestPerfCountersAndMemoryPools { public static void main(String[] args) throws Exception { diff --git a/test/hotspot/jtreg/gc/metaspace/TestSizeTransitions.java b/test/hotspot/jtreg/gc/metaspace/TestSizeTransitions.java index 5ecacc7be70..a87ed22e15b 100644 --- a/test/hotspot/jtreg/gc/metaspace/TestSizeTransitions.java +++ b/test/hotspot/jtreg/gc/metaspace/TestSizeTransitions.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 2023, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2019, Twitter, Inc. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -119,7 +119,7 @@ public static void main(String... args) throws Exception { System.out.println(" " + a); } - final ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(jvmArgs); + final ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(jvmArgs); final OutputAnalyzer output = new OutputAnalyzer(pb.start()); System.out.println(output.getStdout()); output.shouldHaveExitValue(0); diff --git a/test/hotspot/jtreg/gc/serial/HeapChangeLogging.java b/test/hotspot/jtreg/gc/serial/HeapChangeLogging.java index 9d7d8961527..8480d046dfb 100644 --- a/test/hotspot/jtreg/gc/serial/HeapChangeLogging.java +++ b/test/hotspot/jtreg/gc/serial/HeapChangeLogging.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2023, Oracle and/or its affiliates. All rights reserved. * 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,7 +41,7 @@ public class HeapChangeLogging { public static void main(String[] args) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-Xmx128m", "-Xmn100m", "-XX:+UseSerialGC", "-Xlog:gc", HeapFiller.class.getName()); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-Xmx128m", "-Xmn100m", "-XX:+UseSerialGC", "-Xlog:gc", HeapFiller.class.getName()); OutputAnalyzer output = new OutputAnalyzer(pb.start()); String stdout = output.getStdout(); System.out.println(stdout); diff --git a/test/hotspot/jtreg/gc/shenandoah/TestEvilSyncBug.java b/test/hotspot/jtreg/gc/shenandoah/TestEvilSyncBug.java index e58e8d6db5c..67690d8cad5 100644 --- a/test/hotspot/jtreg/gc/shenandoah/TestEvilSyncBug.java +++ b/test/hotspot/jtreg/gc/shenandoah/TestEvilSyncBug.java @@ -56,7 +56,7 @@ public static void main(String[] args) throws Exception { for (int c = 0; c < NUM_RUNS; c++) { Callable task = () -> { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-Xms128m", + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-Xms128m", "-Xmx128m", "-XX:+UnlockExperimentalVMOptions", "-XX:+UnlockDiagnosticVMOptions", diff --git a/test/hotspot/jtreg/gc/shenandoah/TestObjItrWithHeapDump.java b/test/hotspot/jtreg/gc/shenandoah/TestObjItrWithHeapDump.java index 41943d4befd..c0161b7a238 100644 --- a/test/hotspot/jtreg/gc/shenandoah/TestObjItrWithHeapDump.java +++ b/test/hotspot/jtreg/gc/shenandoah/TestObjItrWithHeapDump.java @@ -41,7 +41,7 @@ public static void testWith(String... args) throws Exception { String[] cmds = Arrays.copyOf(args, args.length + 2); cmds[args.length] = TestObjItrWithHeapDump.class.getName(); cmds[args.length + 1] = "test"; - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(cmds); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(cmds); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldHaveExitValue(0); diff --git a/test/hotspot/jtreg/gc/shenandoah/TestPeriodicGC.java b/test/hotspot/jtreg/gc/shenandoah/TestPeriodicGC.java index 84795fa4042..b65aa0cd0b4 100644 --- a/test/hotspot/jtreg/gc/shenandoah/TestPeriodicGC.java +++ b/test/hotspot/jtreg/gc/shenandoah/TestPeriodicGC.java @@ -42,7 +42,7 @@ public static void testWith(String msg, boolean periodic, String... args) throws String[] cmds = Arrays.copyOf(args, args.length + 2); cmds[args.length] = TestPeriodicGC.class.getName(); cmds[args.length + 1] = "test"; - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(cmds); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(cmds); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldHaveExitValue(0); diff --git a/test/hotspot/jtreg/gc/shenandoah/TestVerifyJCStress.java b/test/hotspot/jtreg/gc/shenandoah/TestVerifyJCStress.java index b45d7e18d52..435c4c25004 100644 --- a/test/hotspot/jtreg/gc/shenandoah/TestVerifyJCStress.java +++ b/test/hotspot/jtreg/gc/shenandoah/TestVerifyJCStress.java @@ -40,21 +40,55 @@ * TestVerifyJCStress */ +/* + * @test id=default-debug + * @summary Tests that we pass at least one jcstress-like test with all verification turned on + * @requires vm.gc.Shenandoah + * @requires vm.debug + * @modules java.base/jdk.internal.misc + * java.management + * + * @run main/othervm -Xmx1g -Xms1g -XX:+UnlockExperimentalVMOptions -XX:+UnlockDiagnosticVMOptions + * -XX:+UseShenandoahGC -XX:ShenandoahGCHeuristics=adaptive + * -XX:+ShenandoahVerify -XX:+ShenandoahVerifyOptoBarriers + * TestVerifyJCStress + * + * @run main/othervm -Xmx1g -Xms1g -XX:+UnlockExperimentalVMOptions -XX:+UnlockDiagnosticVMOptions + * -XX:+UseShenandoahGC -XX:ShenandoahGCHeuristics=compact + * -XX:+ShenandoahVerify -XX:+ShenandoahVerifyOptoBarriers + * TestVerifyJCStress + */ + /* * @test id=default * @summary Tests that we pass at least one jcstress-like test with all verification turned on * @requires vm.gc.Shenandoah + * @requires !vm.debug * @modules java.base/jdk.internal.misc * java.management * * @run main/othervm -Xmx1g -Xms1g -XX:+UnlockExperimentalVMOptions -XX:+UnlockDiagnosticVMOptions * -XX:+UseShenandoahGC -XX:ShenandoahGCHeuristics=adaptive - * -XX:+ShenandoahVerify -XX:+IgnoreUnrecognizedVMOptions -XX:+ShenandoahVerifyOptoBarriers + * -XX:+ShenandoahVerify * TestVerifyJCStress * * @run main/othervm -Xmx1g -Xms1g -XX:+UnlockExperimentalVMOptions -XX:+UnlockDiagnosticVMOptions * -XX:+UseShenandoahGC -XX:ShenandoahGCHeuristics=compact - * -XX:+ShenandoahVerify -XX:+IgnoreUnrecognizedVMOptions -XX:+ShenandoahVerifyOptoBarriers + * -XX:+ShenandoahVerify + * TestVerifyJCStress + */ + +/* + * @test id=iu-debug + * @summary Tests that we pass at least one jcstress-like test with all verification turned on + * @requires vm.gc.Shenandoah + * @requires vm.debug + * @modules java.base/jdk.internal.misc + * java.management + * + * @run main/othervm -Xmx1g -Xms1g -XX:+UnlockExperimentalVMOptions -XX:+UnlockDiagnosticVMOptions + * -XX:+UseShenandoahGC -XX:ShenandoahGCMode=iu + * -XX:+ShenandoahVerify -XX:+ShenandoahVerifyOptoBarriers * TestVerifyJCStress */ @@ -62,20 +96,30 @@ * @test id=iu * @summary Tests that we pass at least one jcstress-like test with all verification turned on * @requires vm.gc.Shenandoah + * @requires !vm.debug * @modules java.base/jdk.internal.misc * java.management * * @run main/othervm -Xmx1g -Xms1g -XX:+UnlockExperimentalVMOptions -XX:+UnlockDiagnosticVMOptions * -XX:+UseShenandoahGC -XX:ShenandoahGCMode=iu - * -XX:+ShenandoahVerify -XX:+IgnoreUnrecognizedVMOptions -XX:+ShenandoahVerifyOptoBarriers + * -XX:+ShenandoahVerify * TestVerifyJCStress + */ + +/* + * @test id=iu-c1 + * @summary Tests that we pass at least one jcstress-like test with all verification turned on + * @requires vm.gc.Shenandoah + * @modules java.base/jdk.internal.misc + * java.management * * @run main/othervm -Xmx1g -Xms1g -XX:+UnlockExperimentalVMOptions -XX:+UnlockDiagnosticVMOptions * -XX:+UseShenandoahGC -XX:ShenandoahGCMode=iu - * -XX:+ShenandoahVerify -XX:+IgnoreUnrecognizedVMOptions -XX:TieredStopAtLevel=1 + * -XX:+ShenandoahVerify -XX:TieredStopAtLevel=1 * TestVerifyJCStress */ + import java.util.*; import java.util.concurrent.*; import java.util.concurrent.locks.*; diff --git a/test/hotspot/jtreg/gc/shenandoah/oom/TestAllocLargeObj.java b/test/hotspot/jtreg/gc/shenandoah/oom/TestAllocLargeObj.java index 3996c19a98d..1057eb4a977 100644 --- a/test/hotspot/jtreg/gc/shenandoah/oom/TestAllocLargeObj.java +++ b/test/hotspot/jtreg/gc/shenandoah/oom/TestAllocLargeObj.java @@ -55,7 +55,7 @@ public static void main(String[] args) throws Exception { } { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-Xmx16m", "-XX:+UnlockExperimentalVMOptions", "-XX:+UseShenandoahGC", @@ -68,7 +68,7 @@ public static void main(String[] args) throws Exception { } { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-Xmx1g", "-XX:+UnlockExperimentalVMOptions", "-XX:+UseShenandoahGC", diff --git a/test/hotspot/jtreg/gc/shenandoah/oom/TestAllocLargerThanHeap.java b/test/hotspot/jtreg/gc/shenandoah/oom/TestAllocLargerThanHeap.java index c996bfd714e..1567e3d05da 100644 --- a/test/hotspot/jtreg/gc/shenandoah/oom/TestAllocLargerThanHeap.java +++ b/test/hotspot/jtreg/gc/shenandoah/oom/TestAllocLargerThanHeap.java @@ -50,7 +50,7 @@ public static void main(String[] args) throws Exception { } { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-Xmx16m", "-XX:+UnlockExperimentalVMOptions", "-XX:+UseShenandoahGC", @@ -63,7 +63,7 @@ public static void main(String[] args) throws Exception { } { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-Xmx1g", "-XX:+UnlockExperimentalVMOptions", "-XX:+UseShenandoahGC", diff --git a/test/hotspot/jtreg/gc/shenandoah/oom/TestAllocSmallObj.java b/test/hotspot/jtreg/gc/shenandoah/oom/TestAllocSmallObj.java index 0820237ab94..bc32c1f0aa0 100644 --- a/test/hotspot/jtreg/gc/shenandoah/oom/TestAllocSmallObj.java +++ b/test/hotspot/jtreg/gc/shenandoah/oom/TestAllocSmallObj.java @@ -54,7 +54,7 @@ public static void main(String[] args) throws Exception { } { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-Xmx16m", "-XX:+UnlockExperimentalVMOptions", "-XX:+UseShenandoahGC", @@ -67,7 +67,7 @@ public static void main(String[] args) throws Exception { } { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-Xmx1g", "-XX:+UnlockExperimentalVMOptions", "-XX:+UseShenandoahGC", diff --git a/test/hotspot/jtreg/gc/shenandoah/oom/TestClassLoaderLeak.java b/test/hotspot/jtreg/gc/shenandoah/oom/TestClassLoaderLeak.java index 21962b2182d..080842c37f9 100644 --- a/test/hotspot/jtreg/gc/shenandoah/oom/TestClassLoaderLeak.java +++ b/test/hotspot/jtreg/gc/shenandoah/oom/TestClassLoaderLeak.java @@ -99,7 +99,7 @@ public static void testWith(boolean shouldPass, String... args) throws Exception pbArgs.add(TestClassLoaderLeak.class.getName()); pbArgs.add("test"); - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(pbArgs.toArray(new String[0])); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(pbArgs.toArray(new String[0])); OutputAnalyzer analyzer = new OutputAnalyzer(pb.start()); diff --git a/test/hotspot/jtreg/gc/shenandoah/oom/TestThreadFailure.java b/test/hotspot/jtreg/gc/shenandoah/oom/TestThreadFailure.java index a342b416010..75cb2d5c31a 100644 --- a/test/hotspot/jtreg/gc/shenandoah/oom/TestThreadFailure.java +++ b/test/hotspot/jtreg/gc/shenandoah/oom/TestThreadFailure.java @@ -62,7 +62,7 @@ public static void main(String[] args) throws Exception { } { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-Xmx32m", "-XX:+UnlockExperimentalVMOptions", "-XX:+UseShenandoahGC", diff --git a/test/hotspot/jtreg/gc/shenandoah/options/TestArgumentRanges.java b/test/hotspot/jtreg/gc/shenandoah/options/TestArgumentRanges.java index bcda88b553f..2cc2c2c2197 100644 --- a/test/hotspot/jtreg/gc/shenandoah/options/TestArgumentRanges.java +++ b/test/hotspot/jtreg/gc/shenandoah/options/TestArgumentRanges.java @@ -46,7 +46,7 @@ public static void main(String[] args) throws Exception { private static void testHeuristics() throws Exception { { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-Xmx128m", "-XX:+UnlockDiagnosticVMOptions", "-XX:+UnlockExperimentalVMOptions", @@ -57,7 +57,7 @@ private static void testHeuristics() throws Exception { output.shouldHaveExitValue(0); } { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-Xmx128m", "-XX:+UnlockDiagnosticVMOptions", "-XX:+UnlockExperimentalVMOptions", @@ -68,7 +68,7 @@ private static void testHeuristics() throws Exception { output.shouldHaveExitValue(0); } { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-Xmx128m", "-XX:+UnlockDiagnosticVMOptions", "-XX:+UnlockExperimentalVMOptions", @@ -83,7 +83,7 @@ private static void testHeuristics() throws Exception { private static void testRange(String option, int min, int max) throws Exception { { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-Xmx128m", "-XX:+UnlockDiagnosticVMOptions", "-XX:+UnlockExperimentalVMOptions", @@ -94,7 +94,7 @@ private static void testRange(String option, int min, int max) throws Exception output.shouldHaveExitValue(1); } { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-Xmx128m", "-XX:+UnlockDiagnosticVMOptions", "-XX:+UnlockExperimentalVMOptions", @@ -105,7 +105,7 @@ private static void testRange(String option, int min, int max) throws Exception output.shouldHaveExitValue(0); } { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-Xmx128m", "-XX:+UnlockDiagnosticVMOptions", "-XX:+UnlockExperimentalVMOptions", @@ -116,7 +116,7 @@ private static void testRange(String option, int min, int max) throws Exception output.shouldHaveExitValue(1); } { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-Xmx128m", "-XX:+UnlockDiagnosticVMOptions", "-XX:+UnlockExperimentalVMOptions", diff --git a/test/hotspot/jtreg/gc/shenandoah/options/TestClassUnloadingArguments.java b/test/hotspot/jtreg/gc/shenandoah/options/TestClassUnloadingArguments.java index 4ebdcc33d14..c575b51084c 100644 --- a/test/hotspot/jtreg/gc/shenandoah/options/TestClassUnloadingArguments.java +++ b/test/hotspot/jtreg/gc/shenandoah/options/TestClassUnloadingArguments.java @@ -43,7 +43,7 @@ public static void testWith(String msg, boolean cu, boolean cuConc, String... ar cmds[args.length] = "-Xmx128m"; cmds[args.length + 1] = "-XX:+PrintFlagsFinal"; cmds[args.length + 2] = "-version"; - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(cmds); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(cmds); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldHaveExitValue(0); output.shouldContain("ClassUnloading"); diff --git a/test/hotspot/jtreg/gc/shenandoah/options/TestExplicitGC.java b/test/hotspot/jtreg/gc/shenandoah/options/TestExplicitGC.java index 4e8d699ddee..49e7c417130 100644 --- a/test/hotspot/jtreg/gc/shenandoah/options/TestExplicitGC.java +++ b/test/hotspot/jtreg/gc/shenandoah/options/TestExplicitGC.java @@ -60,7 +60,7 @@ public static void main(String[] args) throws Exception { }; { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-Xmx128m", "-XX:+UnlockExperimentalVMOptions", "-XX:+UseShenandoahGC", @@ -77,7 +77,7 @@ public static void main(String[] args) throws Exception { } { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-Xmx128m", "-XX:+UnlockExperimentalVMOptions", "-XX:+UseShenandoahGC", @@ -95,7 +95,7 @@ public static void main(String[] args) throws Exception { } { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-Xmx128m", "-XX:+UnlockExperimentalVMOptions", "-XX:+UseShenandoahGC", @@ -113,7 +113,7 @@ public static void main(String[] args) throws Exception { } { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-Xmx128m", "-XX:+UnlockExperimentalVMOptions", "-XX:+UseShenandoahGC", @@ -131,7 +131,7 @@ public static void main(String[] args) throws Exception { } { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-Xmx128m", "-XX:+UnlockExperimentalVMOptions", "-XX:+UseShenandoahGC", diff --git a/test/hotspot/jtreg/gc/shenandoah/options/TestExplicitGCNoConcurrent.java b/test/hotspot/jtreg/gc/shenandoah/options/TestExplicitGCNoConcurrent.java index 70724658eb8..6499457b667 100644 --- a/test/hotspot/jtreg/gc/shenandoah/options/TestExplicitGCNoConcurrent.java +++ b/test/hotspot/jtreg/gc/shenandoah/options/TestExplicitGCNoConcurrent.java @@ -60,7 +60,7 @@ public static void main(String[] args) throws Exception { }; for (String opt : opts) { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-Xmx128m", "-XX:+UnlockExperimentalVMOptions", "-XX:+UseShenandoahGC", diff --git a/test/hotspot/jtreg/gc/shenandoah/options/TestHeuristicsUnlock.java b/test/hotspot/jtreg/gc/shenandoah/options/TestHeuristicsUnlock.java index f122cc55fcd..c9f1c75b4e1 100644 --- a/test/hotspot/jtreg/gc/shenandoah/options/TestHeuristicsUnlock.java +++ b/test/hotspot/jtreg/gc/shenandoah/options/TestHeuristicsUnlock.java @@ -52,7 +52,7 @@ public static void main(String[] args) throws Exception { private static void testWith(String h, Mode mode) throws Exception { { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-Xmx128m", "-XX:-UnlockDiagnosticVMOptions", "-XX:-UnlockExperimentalVMOptions", @@ -73,7 +73,7 @@ private static void testWith(String h, Mode mode) throws Exception { } { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-Xmx128m", "-XX:+UnlockDiagnosticVMOptions", "-XX:-UnlockExperimentalVMOptions", @@ -94,7 +94,7 @@ private static void testWith(String h, Mode mode) throws Exception { } { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-Xmx128m", "-XX:-UnlockDiagnosticVMOptions", "-XX:+UnlockExperimentalVMOptions", diff --git a/test/hotspot/jtreg/gc/shenandoah/options/TestHumongousThresholdArgs.java b/test/hotspot/jtreg/gc/shenandoah/options/TestHumongousThresholdArgs.java index 9c7ca182210..523f434dbbd 100644 --- a/test/hotspot/jtreg/gc/shenandoah/options/TestHumongousThresholdArgs.java +++ b/test/hotspot/jtreg/gc/shenandoah/options/TestHumongousThresholdArgs.java @@ -38,7 +38,7 @@ public class TestHumongousThresholdArgs { public static void main(String[] args) throws Exception { { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-Xmx128m", "-XX:+UnlockExperimentalVMOptions", "-XX:+UseShenandoahGC", @@ -51,7 +51,7 @@ public static void main(String[] args) throws Exception { int[] invalid = new int[] {-100, -1, 0, 101, 1000}; for (int v : valid) { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-Xmx128m", "-XX:+UnlockExperimentalVMOptions", "-XX:+UseShenandoahGC", @@ -62,7 +62,7 @@ public static void main(String[] args) throws Exception { } for (int v : invalid) { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-Xmx128m", "-XX:+UnlockExperimentalVMOptions", "-XX:+UseShenandoahGC", diff --git a/test/hotspot/jtreg/gc/shenandoah/options/TestLoopMiningArguments.java b/test/hotspot/jtreg/gc/shenandoah/options/TestLoopMiningArguments.java index f84e576f2f0..79452b6cbc5 100644 --- a/test/hotspot/jtreg/gc/shenandoah/options/TestLoopMiningArguments.java +++ b/test/hotspot/jtreg/gc/shenandoah/options/TestLoopMiningArguments.java @@ -44,7 +44,7 @@ public static void testWith(String msg, boolean cls, int iters, String... args) cmds[args.length] = "-Xmx128m"; cmds[args.length + 1] = "-XX:+PrintFlagsFinal"; cmds[args.length + 2] = "-version"; - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(cmds); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(cmds); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldHaveExitValue(0); output.shouldContain("UseCountedLoopSafepoints"); diff --git a/test/hotspot/jtreg/gc/shenandoah/options/TestModeUnlock.java b/test/hotspot/jtreg/gc/shenandoah/options/TestModeUnlock.java index 6c03281c3ca..0c8fea7f993 100644 --- a/test/hotspot/jtreg/gc/shenandoah/options/TestModeUnlock.java +++ b/test/hotspot/jtreg/gc/shenandoah/options/TestModeUnlock.java @@ -51,7 +51,7 @@ public static void main(String[] args) throws Exception { private static void testWith(String h, Mode mode) throws Exception { { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-Xmx128m", "-XX:-UnlockDiagnosticVMOptions", "-XX:-UnlockExperimentalVMOptions", @@ -72,7 +72,7 @@ private static void testWith(String h, Mode mode) throws Exception { } { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-Xmx128m", "-XX:+UnlockDiagnosticVMOptions", "-XX:-UnlockExperimentalVMOptions", @@ -93,7 +93,7 @@ private static void testWith(String h, Mode mode) throws Exception { } { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-Xmx128m", "-XX:-UnlockDiagnosticVMOptions", "-XX:+UnlockExperimentalVMOptions", diff --git a/test/hotspot/jtreg/gc/shenandoah/options/TestRegionSizeArgs.java b/test/hotspot/jtreg/gc/shenandoah/options/TestRegionSizeArgs.java index 17c8b1ed6e3..79d0b517e89 100644 --- a/test/hotspot/jtreg/gc/shenandoah/options/TestRegionSizeArgs.java +++ b/test/hotspot/jtreg/gc/shenandoah/options/TestRegionSizeArgs.java @@ -45,7 +45,7 @@ public static void main(String[] args) throws Exception { private static void testInvalidRegionSizes() throws Exception { { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-XX:+UnlockExperimentalVMOptions", + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:+UnlockExperimentalVMOptions", "-XX:+UseShenandoahGC", "-Xms4m", "-Xmx1g", @@ -55,7 +55,7 @@ private static void testInvalidRegionSizes() throws Exception { } { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-XX:+UnlockExperimentalVMOptions", + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:+UnlockExperimentalVMOptions", "-XX:+UseShenandoahGC", "-Xms8m", "-Xmx1g", @@ -65,7 +65,7 @@ private static void testInvalidRegionSizes() throws Exception { } { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-XX:+UnlockExperimentalVMOptions", + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:+UnlockExperimentalVMOptions", "-XX:+UseShenandoahGC", "-Xms100m", "-Xmx1g", @@ -77,7 +77,7 @@ private static void testInvalidRegionSizes() throws Exception { } { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-XX:+UnlockExperimentalVMOptions", + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:+UnlockExperimentalVMOptions", "-XX:+UseShenandoahGC", "-Xms100m", "-Xmx1g", @@ -88,7 +88,7 @@ private static void testInvalidRegionSizes() throws Exception { } { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-XX:+UnlockExperimentalVMOptions", + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:+UnlockExperimentalVMOptions", "-XX:+UseShenandoahGC", "-Xms100m", "-Xmx1g", @@ -100,7 +100,7 @@ private static void testInvalidRegionSizes() throws Exception { } { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-XX:+UnlockExperimentalVMOptions", + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:+UnlockExperimentalVMOptions", "-XX:+UseShenandoahGC", "-Xms100m", "-Xmx1g", @@ -111,7 +111,7 @@ private static void testInvalidRegionSizes() throws Exception { } { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-XX:+UnlockExperimentalVMOptions", + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:+UnlockExperimentalVMOptions", "-XX:+UseShenandoahGC", "-Xms1g", "-Xmx1g", @@ -122,7 +122,7 @@ private static void testInvalidRegionSizes() throws Exception { } { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-XX:+UnlockExperimentalVMOptions", + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:+UnlockExperimentalVMOptions", "-XX:+UseShenandoahGC", "-Xms1g", "-Xmx1g", @@ -134,7 +134,7 @@ private static void testInvalidRegionSizes() throws Exception { } { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-XX:+UnlockExperimentalVMOptions", + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:+UnlockExperimentalVMOptions", "-XX:+UseShenandoahGC", "-Xms1g", "-Xmx1g", @@ -145,7 +145,7 @@ private static void testInvalidRegionSizes() throws Exception { } { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-XX:+UnlockExperimentalVMOptions", + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:+UnlockExperimentalVMOptions", "-XX:+UseShenandoahGC", "-Xms1g", "-Xmx1g", @@ -160,7 +160,7 @@ private static void testInvalidRegionSizes() throws Exception { private static void testMinRegionSize() throws Exception { { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-XX:+UnlockExperimentalVMOptions", + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:+UnlockExperimentalVMOptions", "-XX:+UseShenandoahGC", "-Xms100m", "-Xmx1g", @@ -172,7 +172,7 @@ private static void testMinRegionSize() throws Exception { } { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-XX:+UnlockExperimentalVMOptions", + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:+UnlockExperimentalVMOptions", "-XX:+UseShenandoahGC", "-Xms100m", "-Xmx1g", @@ -184,7 +184,7 @@ private static void testMinRegionSize() throws Exception { output.shouldHaveExitValue(1); } { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-XX:+UnlockExperimentalVMOptions", + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:+UnlockExperimentalVMOptions", "-XX:+UseShenandoahGC", "-Xms100m", "-Xmx1g", @@ -196,7 +196,7 @@ private static void testMinRegionSize() throws Exception { } { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-XX:+UnlockExperimentalVMOptions", + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:+UnlockExperimentalVMOptions", "-XX:+UseShenandoahGC", "-Xms100m", "-Xmx1g", @@ -211,7 +211,7 @@ private static void testMinRegionSize() throws Exception { private static void testMaxRegionSize() throws Exception { { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-XX:+UnlockExperimentalVMOptions", + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:+UnlockExperimentalVMOptions", "-XX:+UseShenandoahGC", "-Xms100m", "-Xmx1g", @@ -223,7 +223,7 @@ private static void testMaxRegionSize() throws Exception { } { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-XX:+UnlockExperimentalVMOptions", + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:+UnlockExperimentalVMOptions", "-XX:+UseShenandoahGC", "-Xms100m", "-Xmx1g", diff --git a/test/hotspot/jtreg/gc/shenandoah/options/TestSelectiveBarrierFlags.java b/test/hotspot/jtreg/gc/shenandoah/options/TestSelectiveBarrierFlags.java index a8d5d2f33d2..de42a7507e5 100644 --- a/test/hotspot/jtreg/gc/shenandoah/options/TestSelectiveBarrierFlags.java +++ b/test/hotspot/jtreg/gc/shenandoah/options/TestSelectiveBarrierFlags.java @@ -29,7 +29,15 @@ * @library /test/lib * @run driver TestSelectiveBarrierFlags -Xint * @run driver TestSelectiveBarrierFlags -Xbatch -XX:CompileThreshold=100 -XX:TieredStopAtLevel=1 - * @run driver TestSelectiveBarrierFlags -Xbatch -XX:CompileThreshold=100 -XX:-TieredCompilation -XX:+IgnoreUnrecognizedVMOptions -XX:+ShenandoahVerifyOptoBarriers + */ + +/* @test + * @summary Test selective barrier enabling works, by aggressively compiling HelloWorld with combinations + * of barrier flags + * @requires vm.gc.Shenandoah + * @requires vm.debug + * @library /test/lib + * @run driver TestSelectiveBarrierFlags -Xbatch -XX:CompileThreshold=100 -XX:-TieredCompilation -XX:+ShenandoahVerifyOptoBarriers */ import java.util.*; @@ -83,7 +91,7 @@ public static void main(String[] args) throws Exception { pool.submit(() -> { try { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(conf.toArray(new String[0])); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(conf.toArray(new String[0])); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldHaveExitValue(0); } catch (Exception e) { diff --git a/test/hotspot/jtreg/gc/shenandoah/options/TestSoftMaxHeapSize.java b/test/hotspot/jtreg/gc/shenandoah/options/TestSoftMaxHeapSize.java index cd1e3591fe0..78bbf75189c 100644 --- a/test/hotspot/jtreg/gc/shenandoah/options/TestSoftMaxHeapSize.java +++ b/test/hotspot/jtreg/gc/shenandoah/options/TestSoftMaxHeapSize.java @@ -38,7 +38,7 @@ public class TestSoftMaxHeapSize { public static void main(String[] args) throws Exception { { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-XX:+UnlockExperimentalVMOptions", + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:+UnlockExperimentalVMOptions", "-XX:+UseShenandoahGC", "-Xms4m", "-Xmx128m", @@ -49,7 +49,7 @@ public static void main(String[] args) throws Exception { } { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-XX:+UnlockExperimentalVMOptions", + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:+UnlockExperimentalVMOptions", "-XX:+UseShenandoahGC", "-Xms4m", "-Xmx128m", @@ -60,7 +60,7 @@ public static void main(String[] args) throws Exception { } { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-XX:+UnlockExperimentalVMOptions", + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:+UnlockExperimentalVMOptions", "-XX:+UseShenandoahGC", "-Xms4m", "-Xmx128m", diff --git a/test/hotspot/jtreg/gc/shenandoah/options/TestThreadCounts.java b/test/hotspot/jtreg/gc/shenandoah/options/TestThreadCounts.java index 8100ff57c05..f7f9ee56b59 100644 --- a/test/hotspot/jtreg/gc/shenandoah/options/TestThreadCounts.java +++ b/test/hotspot/jtreg/gc/shenandoah/options/TestThreadCounts.java @@ -45,7 +45,7 @@ public static void main(String[] args) throws Exception { } private static void testWith(int conc, int par) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-Xmx128m", "-XX:+UnlockDiagnosticVMOptions", "-XX:+UnlockExperimentalVMOptions", diff --git a/test/hotspot/jtreg/gc/shenandoah/options/TestThreadCountsOverride.java b/test/hotspot/jtreg/gc/shenandoah/options/TestThreadCountsOverride.java index c8c876c23e5..5e63595e726 100644 --- a/test/hotspot/jtreg/gc/shenandoah/options/TestThreadCountsOverride.java +++ b/test/hotspot/jtreg/gc/shenandoah/options/TestThreadCountsOverride.java @@ -38,7 +38,7 @@ public class TestThreadCountsOverride { public static void main(String[] args) throws Exception { { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-Xmx128m", "-XX:+UnlockDiagnosticVMOptions", "-XX:+UnlockExperimentalVMOptions", @@ -53,7 +53,7 @@ public static void main(String[] args) throws Exception { } { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-Xmx128m", "-XX:+UnlockDiagnosticVMOptions", "-XX:+UnlockExperimentalVMOptions", diff --git a/test/hotspot/jtreg/gc/shenandoah/options/TestWrongBarrierDisable.java b/test/hotspot/jtreg/gc/shenandoah/options/TestWrongBarrierDisable.java index 3fb16fc37a2..1fcc03def08 100644 --- a/test/hotspot/jtreg/gc/shenandoah/options/TestWrongBarrierDisable.java +++ b/test/hotspot/jtreg/gc/shenandoah/options/TestWrongBarrierDisable.java @@ -65,7 +65,7 @@ public static void main(String[] args) throws Exception { private static void shouldFailAll(String h, String[] barriers) throws Exception { for (String b : barriers) { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-Xmx128m", "-XX:+UnlockDiagnosticVMOptions", "-XX:+UnlockExperimentalVMOptions", @@ -83,7 +83,7 @@ private static void shouldFailAll(String h, String[] barriers) throws Exception private static void shouldPassAll(String h, String[] barriers) throws Exception { for (String b : barriers) { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-Xmx128m", "-XX:+UnlockDiagnosticVMOptions", "-XX:+UnlockExperimentalVMOptions", diff --git a/test/hotspot/jtreg/gc/shenandoah/options/TestWrongBarrierEnable.java b/test/hotspot/jtreg/gc/shenandoah/options/TestWrongBarrierEnable.java index bf37e8db1b3..84645621eb4 100644 --- a/test/hotspot/jtreg/gc/shenandoah/options/TestWrongBarrierEnable.java +++ b/test/hotspot/jtreg/gc/shenandoah/options/TestWrongBarrierEnable.java @@ -55,7 +55,7 @@ public static void main(String[] args) throws Exception { private static void shouldFailAll(String h, String[] barriers) throws Exception { for (String b : barriers) { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-Xmx128m", "-XX:+UnlockDiagnosticVMOptions", "-XX:+UnlockExperimentalVMOptions", @@ -73,7 +73,7 @@ private static void shouldFailAll(String h, String[] barriers) throws Exception private static void shouldPassAll(String h, String[] barriers) throws Exception { for (String b : barriers) { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-Xmx128m", "-XX:+UnlockDiagnosticVMOptions", "-XX:+UnlockExperimentalVMOptions", diff --git a/test/hotspot/jtreg/gc/startup_warnings/TestG1.java b/test/hotspot/jtreg/gc/startup_warnings/TestG1.java index c0a06f41bc6..5846639d071 100644 --- a/test/hotspot/jtreg/gc/startup_warnings/TestG1.java +++ b/test/hotspot/jtreg/gc/startup_warnings/TestG1.java @@ -40,7 +40,7 @@ public class TestG1 { public static void main(String args[]) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-XX:+UseG1GC", "-version"); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:+UseG1GC", "-version"); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldNotContain("deprecated"); output.shouldNotContain("error"); diff --git a/test/hotspot/jtreg/gc/startup_warnings/TestParallelGC.java b/test/hotspot/jtreg/gc/startup_warnings/TestParallelGC.java index 964a73eee6d..a34dac14e65 100644 --- a/test/hotspot/jtreg/gc/startup_warnings/TestParallelGC.java +++ b/test/hotspot/jtreg/gc/startup_warnings/TestParallelGC.java @@ -41,7 +41,7 @@ public class TestParallelGC { public static void main(String args[]) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-XX:+UseParallelGC", "-version"); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:+UseParallelGC", "-version"); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldNotContain("deprecated"); output.shouldNotContain("error"); diff --git a/test/hotspot/jtreg/gc/startup_warnings/TestSerialGC.java b/test/hotspot/jtreg/gc/startup_warnings/TestSerialGC.java index 681812a0e22..d4ae6de077a 100644 --- a/test/hotspot/jtreg/gc/startup_warnings/TestSerialGC.java +++ b/test/hotspot/jtreg/gc/startup_warnings/TestSerialGC.java @@ -40,7 +40,7 @@ public class TestSerialGC { public static void main(String args[]) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-XX:+UseSerialGC", "-version"); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:+UseSerialGC", "-version"); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldNotContain("deprecated"); output.shouldNotContain("error"); diff --git a/test/hotspot/jtreg/gc/startup_warnings/TestShenandoah.java b/test/hotspot/jtreg/gc/startup_warnings/TestShenandoah.java index a9cff8e41a5..1ab02b2998a 100644 --- a/test/hotspot/jtreg/gc/startup_warnings/TestShenandoah.java +++ b/test/hotspot/jtreg/gc/startup_warnings/TestShenandoah.java @@ -40,7 +40,7 @@ public class TestShenandoah { public static void main(String args[]) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-XX:+UnlockExperimentalVMOptions", "-XX:+UseShenandoahGC", "-version"); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:+UnlockExperimentalVMOptions", "-XX:+UseShenandoahGC", "-version"); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldNotContain("deprecated"); output.shouldNotContain("error"); diff --git a/test/hotspot/jtreg/gc/stress/TestReclaimStringsLeaksMemory.java b/test/hotspot/jtreg/gc/stress/TestReclaimStringsLeaksMemory.java index aac4e3d02c9..3114117a1ef 100644 --- a/test/hotspot/jtreg/gc/stress/TestReclaimStringsLeaksMemory.java +++ b/test/hotspot/jtreg/gc/stress/TestReclaimStringsLeaksMemory.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2023, Oracle and/or its affiliates. All rights reserved. * 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,7 @@ public static void main(String[] args) throws Exception { "-XX:+PrintNMTStatistics" )); baseargs.addAll(Arrays.asList(args)); baseargs.add(GCTest.class.getName()); - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(baseargs); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(baseargs); verifySymbolMemoryUsageNotTooHigh(new OutputAnalyzer(pb.start())); } diff --git a/test/hotspot/jtreg/gc/stress/TestStressG1Humongous.java b/test/hotspot/jtreg/gc/stress/TestStressG1Humongous.java index 983b9f6c33f..2a02039c60e 100644 --- a/test/hotspot/jtreg/gc/stress/TestStressG1Humongous.java +++ b/test/hotspot/jtreg/gc/stress/TestStressG1Humongous.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -101,7 +101,7 @@ public static void main(String[] args) throws Exception { "-Dregionsize=" + regionSize, TestStressG1HumongousImpl.class.getName() ); - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(options); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(options); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldHaveExitValue(0); } diff --git a/test/hotspot/jtreg/gc/stress/TestStressG1Uncommit.java b/test/hotspot/jtreg/gc/stress/TestStressG1Uncommit.java index e256ea405c2..2f61c166cb8 100644 --- a/test/hotspot/jtreg/gc/stress/TestStressG1Uncommit.java +++ b/test/hotspot/jtreg/gc/stress/TestStressG1Uncommit.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2020, 2023, Oracle and/or its affiliates. All rights reserved. * 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,7 +59,7 @@ public static void main(String[] args) throws Exception { "-XX:+UseG1GC", StressUncommit.class.getName() ); - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(options); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(options); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldHaveExitValue(0); output.shouldMatch("Uncommit regions"); diff --git a/test/hotspot/jtreg/gc/stringdedup/TestStringDeduplicationTools.java b/test/hotspot/jtreg/gc/stringdedup/TestStringDeduplicationTools.java index 27256facaf6..41d4e157bac 100644 --- a/test/hotspot/jtreg/gc/stringdedup/TestStringDeduplicationTools.java +++ b/test/hotspot/jtreg/gc/stringdedup/TestStringDeduplicationTools.java @@ -277,7 +277,7 @@ private static OutputAnalyzer runTest(String... extraArgs) throws Exception { args.addAll(Arrays.asList(defaultArgs)); args.addAll(Arrays.asList(extraArgs)); - ProcessBuilder pb = ProcessTools.createTestJvm(args); + ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder(args); OutputAnalyzer output = new OutputAnalyzer(pb.start()); System.err.println(output.getStderr()); System.out.println(output.getStdout()); diff --git a/test/hotspot/jtreg/gc/whitebox/TestWBGC.java b/test/hotspot/jtreg/gc/whitebox/TestWBGC.java index c2cb35d4f9d..c2fe2633e4e 100644 --- a/test/hotspot/jtreg/gc/whitebox/TestWBGC.java +++ b/test/hotspot/jtreg/gc/whitebox/TestWBGC.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -43,7 +43,7 @@ public class TestWBGC { public static void main(String args[]) throws Exception { - ProcessBuilder pb = ProcessTools.createTestJvm( + ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder( "-Xbootclasspath/a:.", "-XX:+UnlockDiagnosticVMOptions", "-XX:+WhiteBoxAPI", diff --git a/test/hotspot/jtreg/gc/z/TestAllocateHeapAt.java b/test/hotspot/jtreg/gc/z/TestAllocateHeapAt.java index eed7426f791..17f335be33b 100644 --- a/test/hotspot/jtreg/gc/z/TestAllocateHeapAt.java +++ b/test/hotspot/jtreg/gc/z/TestAllocateHeapAt.java @@ -41,7 +41,7 @@ public static void main(String[] args) throws Exception { final String heapBackingFile = "Heap Backing File: " + directory; final String failedToCreateFile = "Failed to create file " + directory; - ProcessTools.executeProcess(ProcessTools.createJavaProcessBuilder( + ProcessTools.executeProcess(ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:+UseZGC", "-Xlog:gc*", "-Xms32M", diff --git a/test/hotspot/jtreg/gc/z/TestGarbageCollectorMXBean.java b/test/hotspot/jtreg/gc/z/TestGarbageCollectorMXBean.java index 07d3f3dadc7..944cdea514a 100644 --- a/test/hotspot/jtreg/gc/z/TestGarbageCollectorMXBean.java +++ b/test/hotspot/jtreg/gc/z/TestGarbageCollectorMXBean.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2020, 2022, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,14 +21,16 @@ * questions. */ +package gc.z; + /** * @test TestGarbageCollectorMXBean * @requires vm.gc.Z * @summary Test ZGC garbage collector MXBean * @modules java.management * @requires vm.compMode != "Xcomp" - * @run main/othervm -XX:+UseZGC -Xms256M -Xmx512M -Xlog:gc TestGarbageCollectorMXBean 256 512 - * @run main/othervm -XX:+UseZGC -Xms512M -Xmx512M -Xlog:gc TestGarbageCollectorMXBean 512 512 + * @run main/othervm -XX:+UseZGC -Xms256M -Xmx512M -Xlog:gc gc.z.TestGarbageCollectorMXBean 256 512 + * @run main/othervm -XX:+UseZGC -Xms512M -Xmx512M -Xlog:gc gc.z.TestGarbageCollectorMXBean 512 512 */ import java.lang.management.ManagementFactory; diff --git a/test/hotspot/jtreg/gc/z/TestMemoryMXBean.java b/test/hotspot/jtreg/gc/z/TestMemoryMXBean.java index 47545d1bcf5..18c18985759 100644 --- a/test/hotspot/jtreg/gc/z/TestMemoryMXBean.java +++ b/test/hotspot/jtreg/gc/z/TestMemoryMXBean.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2020, 2022, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,13 +21,15 @@ * questions. */ +package gc.z; + /** * @test TestMemoryMXBean * @requires vm.gc.Z * @summary Test ZGC heap memory MXBean * @modules java.management - * @run main/othervm -XX:+UseZGC -Xms128M -Xmx256M -Xlog:gc* TestMemoryMXBean 128 256 - * @run main/othervm -XX:+UseZGC -Xms256M -Xmx256M -Xlog:gc* TestMemoryMXBean 256 256 + * @run main/othervm -XX:+UseZGC -Xms128M -Xmx256M -Xlog:gc* gc.z.TestMemoryMXBean 128 256 + * @run main/othervm -XX:+UseZGC -Xms256M -Xmx256M -Xlog:gc* gc.z.TestMemoryMXBean 256 256 */ import java.lang.management.ManagementFactory; diff --git a/test/hotspot/jtreg/gc/z/TestMemoryManagerMXBean.java b/test/hotspot/jtreg/gc/z/TestMemoryManagerMXBean.java index a5c5c1367e7..803201d576e 100644 --- a/test/hotspot/jtreg/gc/z/TestMemoryManagerMXBean.java +++ b/test/hotspot/jtreg/gc/z/TestMemoryManagerMXBean.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2020, 2022, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,12 +21,14 @@ * questions. */ +package gc.z; + /** * @test TestMemoryManagerMXBean * @requires vm.gc.Z * @summary Test ZGC memory manager MXBean * @modules java.management - * @run main/othervm -XX:+UseZGC -Xmx128M TestMemoryManagerMXBean + * @run main/othervm -XX:+UseZGC -Xmx128M gc.z.TestMemoryManagerMXBean */ import java.lang.management.ManagementFactory; diff --git a/test/hotspot/jtreg/gc/z/TestPageCacheFlush.java b/test/hotspot/jtreg/gc/z/TestPageCacheFlush.java index 67e4461c130..52faeaf406d 100644 --- a/test/hotspot/jtreg/gc/z/TestPageCacheFlush.java +++ b/test/hotspot/jtreg/gc/z/TestPageCacheFlush.java @@ -68,7 +68,7 @@ public static void main(String[] args) throws Exception { } public static void main(String[] args) throws Exception { - ProcessTools.executeProcess(ProcessTools.createJavaProcessBuilder( + ProcessTools.executeProcess(ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:+UseZGC", "-Xms128M", "-Xmx128M", diff --git a/test/hotspot/jtreg/gc/z/TestSmallHeap.java b/test/hotspot/jtreg/gc/z/TestSmallHeap.java index e30e859f571..7c02c2cbec5 100644 --- a/test/hotspot/jtreg/gc/z/TestSmallHeap.java +++ b/test/hotspot/jtreg/gc/z/TestSmallHeap.java @@ -53,7 +53,7 @@ public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception { for (var maxCapacity: args) { - ProcessTools.executeProcess(ProcessTools.createJavaProcessBuilder( + ProcessTools.executeProcess(ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:+UseZGC", "-Xlog:gc,gc+init,gc+reloc,gc+heap", "-Xmx" + maxCapacity, diff --git a/test/hotspot/jtreg/resourcehogs/serviceability/jvmti/GetObjectSizeOverflow.java b/test/hotspot/jtreg/resourcehogs/serviceability/jvmti/GetObjectSizeOverflow.java index b423453ce77..236d2eb9486 100644 --- a/test/hotspot/jtreg/resourcehogs/serviceability/jvmti/GetObjectSizeOverflow.java +++ b/test/hotspot/jtreg/resourcehogs/serviceability/jvmti/GetObjectSizeOverflow.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -56,7 +56,7 @@ public static void main(String[] args) throws Exception { var jar = new ProcessBuilder(JDKToolFinder.getJDKTool("jar"), "cmf", "MANIFEST.MF", "agent.jar", "GetObjectSizeOverflowAgent.class"); new OutputAnalyzer(jar.start()).shouldHaveExitValue(0); - ProcessBuilder pt = ProcessTools.createTestJvm("-Xmx4000m", "-javaagent:agent.jar", "GetObjectSizeOverflowAgent"); + ProcessBuilder pt = ProcessTools.createTestJavaProcessBuilder("-Xmx4000m", "-javaagent:agent.jar", "GetObjectSizeOverflowAgent"); OutputAnalyzer output = new OutputAnalyzer(pt.start()); output.stdoutShouldContain("GetObjectSizeOverflow passed"); output.shouldHaveExitValue(0); diff --git a/test/hotspot/jtreg/runtime/7162488/TestUnrecognizedVmOption.java b/test/hotspot/jtreg/runtime/7162488/TestUnrecognizedVmOption.java index 7de7245d862..db7cfebfd90 100644 --- a/test/hotspot/jtreg/runtime/7162488/TestUnrecognizedVmOption.java +++ b/test/hotspot/jtreg/runtime/7162488/TestUnrecognizedVmOption.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2020, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -35,7 +35,7 @@ public class TestUnrecognizedVmOption { static final String OPTION="this_is_not_an_option"; public static void main(String[] args) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-showversion", "-XX:" + OPTION); new OutputAnalyzer(pb.start()) .shouldNotHaveExitValue(0) diff --git a/test/hotspot/jtreg/runtime/8176717/TestInheritFD.java b/test/hotspot/jtreg/runtime/8176717/TestInheritFD.java index 37c5280d236..ebbae35e4e0 100644 --- a/test/hotspot/jtreg/runtime/8176717/TestInheritFD.java +++ b/test/hotspot/jtreg/runtime/8176717/TestInheritFD.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,13 +21,14 @@ * questions. */ +import static java.lang.Character.isDigit; import static java.lang.Long.parseLong; import static java.lang.System.getProperty; import static java.nio.file.Files.readAllBytes; import static java.util.Arrays.stream; import static java.util.stream.Collectors.joining; import static java.util.stream.Collectors.toList; -import static jdk.test.lib.process.ProcessTools.createJavaProcessBuilder; +import static jdk.test.lib.process.ProcessTools.createLimitedTestJavaProcessBuilder; import static jdk.test.lib.Platform.isWindows; import jdk.test.lib.Utils; import jdk.test.lib.Platform; @@ -40,6 +41,7 @@ import java.io.IOException; import java.io.InputStreamReader; import java.util.Collection; +import java.util.concurrent.TimeUnit; import java.util.Optional; import java.util.stream.Stream; @@ -60,17 +62,18 @@ * * This test is performed in three steps. The first VM starts a second VM with * gc logging enabled. The second VM starts a third VM and redirects the third - * VMs output to the first VM, it then exits and hopefully closes its log file. + * VMs output to the first VM. The second VM then exits and hopefully closes + * its log file. * - * The third VM waits for the second to exit and close its log file. After that, - * the third VM tries to rename the log file of the second VM. If it succeeds in - * doing so it means that the third VM did not inherit the open log file - * (windows can not rename opened files easily) + * The third VM waits for the second to exit and close its log file. + * On Windows, the third VM tries to rename the log file of the second VM. + * If it succeeds in doing so it means that the third VM did not inherit + * the open log file (windows cannot rename opened files easily). + * On unix like systems, the third VM uses "lsof" for verification. * - * The third VM communicates the success to rename the file by printing "CLOSED - * FD". The first VM checks that the string was printed by the third VM. - * - * On unix like systems "lsof" is used. + * The third VM communicates success by printing "RETAINS FD". The first VM + * waits for the third VM to exit and checks that the string was printed by + * the third VM. */ public class TestInheritFD { @@ -80,9 +83,145 @@ public class TestInheritFD { public static final String EXIT = "VM RESULT => VM EXIT"; public static final String LOG_SUFFIX = ".strangelogsuffixthatcanbecheckedfor"; public static final String USER_DIR = System.getProperty("user.dir"); + public static final String LSOF_PID_PREFIX = " VM lsof pid="; + public static final String SECOND_VM_PID_PREFIX = "Second VM pid="; + public static final String THIRD_VM_PID_PREFIX = "Third VM pid="; + public static final String THIRD_VM_WAITING_PREFIX = "Third VM waiting for second VM pid="; + + public static float timeoutFactor = Float.parseFloat(System.getProperty("test.timeout.factor", "1.0")); + public static long subProcessTimeout = (long)(15L * timeoutFactor); + + // Extract a pid from the specified String at the specified start offset. + private static long extractPidFromStringOffset(String str, int start) { + int end; + for (end = start; end < str.length(); end++) { + if (!isDigit(str.charAt(end))) { + break; + } + } + if (start == end) { // no digits at all + return -1; + } + return parseLong(str.substring(start, end)); + } + + // Wait for the sub-process pids identified in commFile to finish executing. + // Returns true if RETAINS_FD was found in the commFile and false otherwise. + private static boolean waitForSubPids(File commFile) throws Exception { + String out = ""; + int sleepCnt = 0; + long secondVMPID = -1; + long secondVMlsofPID = -1; + long thirdVMPID = -1; + long thirdVMlsofPID = -1; + // Only have to gather info until the doneWithPattern shows up in the output: + String doneWithPattern; + if (isWindows()) { + doneWithPattern = THIRD_VM_PID_PREFIX; + } else { + doneWithPattern = "Third" + LSOF_PID_PREFIX; + } + do { + out = new String(readAllBytes(commFile.toPath())); + if (secondVMPID == -1) { + int ind = out.indexOf(SECOND_VM_PID_PREFIX); + if (ind != -1) { + int startPid = ind + SECOND_VM_PID_PREFIX.length(); + secondVMPID = extractPidFromStringOffset(out, startPid); + System.out.println("secondVMPID=" + secondVMPID); + } + } + if (!isWindows() && secondVMlsofPID == -1) { + String prefix = "Second" + LSOF_PID_PREFIX; + int ind = out.indexOf(prefix); + if (ind != -1) { + int startPid = ind + prefix.length(); + secondVMlsofPID = extractPidFromStringOffset(out, startPid); + System.out.println("secondVMlsofPID=" + secondVMlsofPID); + } + } + if (thirdVMPID == -1) { + int ind = out.indexOf(THIRD_VM_PID_PREFIX); + if (ind != -1) { + int startPid = ind + THIRD_VM_PID_PREFIX.length(); + thirdVMPID = extractPidFromStringOffset(out, startPid); + System.out.println("thirdVMPID=" + thirdVMPID); + } + } + if (!isWindows() && thirdVMlsofPID == -1) { + String prefix = "Third" + LSOF_PID_PREFIX; + int ind = out.indexOf(prefix); + if (ind != -1) { + int startPid = ind + prefix.length(); + thirdVMlsofPID = extractPidFromStringOffset(out, startPid); + System.out.println("thirdVMlsofPID=" + thirdVMlsofPID); + } + } + Thread.sleep(100); + sleepCnt++; + } while (!out.contains(doneWithPattern) && !out.contains(EXIT)); + + System.out.println("Called Thread.sleep(100) " + sleepCnt + " times."); + + long subPids[] = new long[4]; // At most 4 pids to check. + String subNames[] = new String[4]; // At most 4 names for those pids. + int ind = 0; + if (!isWindows() && secondVMlsofPID != -1) { + // The second VM's lsof cmd should be the first non-windows sub-process to finish: + subPids[ind] = secondVMlsofPID; + subNames[ind] = "second VM lsof"; + ind++; + } + // The second VM should the second non-windows or first windows sub-process to finish: + subPids[ind] = secondVMPID; + subNames[ind] = "second VM"; + ind++; + if (!isWindows() && thirdVMlsofPID != -1) { + // The third VM's lsof cmd should be the third non-windows sub-process to finish: + subPids[ind] = thirdVMlsofPID; + subNames[ind] = "third VM lsof"; + ind++; + } + // The third VM should the last sub-process to finish: + subPids[ind] = thirdVMPID; + subNames[ind] = "third VM"; + ind++; + if (isWindows()) { + // No lsof pids on windows so we use fewer array slots. + // Make sure they are marked as not used. + for (; ind < subPids.length; ind++) { + subPids[ind] = -1; + } + } + + try { + for (ind = 0; ind < subPids.length; ind++) { + if (subPids[ind] == -1) { + continue; + } + System.out.print("subs[" + ind + "]={pid=" + subPids[ind] + ", name=" + subNames[ind] + "}"); + ProcessHandle.of(subPids[ind]).ifPresent(handle -> handle.onExit().orTimeout(subProcessTimeout, TimeUnit.SECONDS).join()); + System.out.println(" finished."); + } + } catch (Exception e) { + // Terminate the "subs" line from above: + System.out.println(" Exception was thrown while trying to join() subPids: " + e.toString()); + throw e; + } finally { + // Reread to get everything in the commFile: + out = new String(readAllBytes(commFile.toPath())); + System.out.println(""); + System.out.println(out); + System.out.println(""); + } + + return out.contains(RETAINS_FD); + } // first VM public static void main(String[] args) throws Exception { + System.out.println("subProcessTimeout=" + subProcessTimeout + " seconds."); + System.out.println("First VM starts."); String logPath = Utils.createTempFile("logging", LOG_SUFFIX).toFile().getName(); File commFile = Utils.createTempFile("communication", ".txt").toFile(); @@ -90,7 +229,7 @@ public static void main(String[] args) throws Exception { throw new SkippedException("Could not find lsof like command"); } - ProcessBuilder pb = createJavaProcessBuilder( + ProcessBuilder pb = createLimitedTestJavaProcessBuilder( "-Xlog:gc:\"" + logPath + "\"", "-Dtest.jdk=" + getProperty("test.jdk"), VMStartedWithLogging.class.getName(), @@ -99,25 +238,19 @@ public static void main(String[] args) throws Exception { pb.redirectOutput(commFile); // use temp file to communicate between processes pb.start(); - String out = ""; - do { - out = new String(readAllBytes(commFile.toPath())); - Thread.sleep(100); - System.out.println("SLEEP 100 millis"); - } while (!out.contains(EXIT)); - - System.out.println(out); - if (out.contains(RETAINS_FD)) { - System.out.println("Log file was not inherited by third VM"); + if (waitForSubPids(commFile)) { + System.out.println("Log file was not inherited by third VM."); } else { - throw new RuntimeException("could not match: " + RETAINS_FD); + throw new RuntimeException("Log file was leaked to the third VM."); } + System.out.println("First VM ends."); } static class VMStartedWithLogging { // second VM public static void main(String[] args) throws IOException, InterruptedException { - ProcessBuilder pb = createJavaProcessBuilder( + System.out.println(SECOND_VM_PID_PREFIX + ProcessHandle.current().pid()); + ProcessBuilder pb = createLimitedTestJavaProcessBuilder( "-Dtest.jdk=" + getProperty("test.jdk"), VMShouldNotInheritFileDescriptors.class.getName(), args[0], @@ -126,30 +259,43 @@ public static void main(String[] args) throws IOException, InterruptedException pb.start(); if (!isWindows()) { - System.out.println("(Second VM) Open file descriptors:\n" + outputContainingFilenames().stream().collect(joining("\n"))); + System.out.println("(Second VM) Open file descriptors:\n" + outputContainingFilenames("Second").stream().collect(joining("\n"))); + } + if (false) { // Enable to simulate a timeout in the second VM. + Thread.sleep(300 * 1000); } + System.out.println("Second VM ends."); } } static class VMShouldNotInheritFileDescriptors { // third VM public static void main(String[] args) throws InterruptedException { + System.out.println(THIRD_VM_PID_PREFIX + ProcessHandle.current().pid()); try { File logFile = new File(args[0]); long parentPid = parseLong(args[1]); fakeLeakyJVM(false); // for debugging of test case + System.out.println(THIRD_VM_WAITING_PREFIX + parentPid); + ProcessHandle.of(parentPid).ifPresent(handle -> handle.onExit().orTimeout(subProcessTimeout, TimeUnit.SECONDS).join()); + if (isWindows()) { - windows(logFile, parentPid); + windows(logFile); } else { - Collection output = outputContainingFilenames(); + Collection output = outputContainingFilenames("Third"); System.out.println("(Third VM) Open file descriptors:\n" + output.stream().collect(joining("\n"))); System.out.println(findOpenLogFile(output) ? LEAKS_FD : RETAINS_FD); } + if (false) { // Enable to simulate a timeout in the third VM. + Thread.sleep(300 * 1000); + } } catch (Exception e) { - System.out.println(e.toString()); + System.out.println("Exception was thrown: " + e.toString()); + throw e; } finally { System.out.println(EXIT); + System.out.println("Third VM ends."); } } } @@ -165,9 +311,11 @@ static void fakeLeakyJVM(boolean fake) { } } - static Stream run(String... args){ + static Stream runLsof(String whichVM, String... args){ try { - return new BufferedReader(new InputStreamReader(new ProcessBuilder(args).start().getInputStream())).lines(); + Process lsof = new ProcessBuilder(args).start(); + System.out.println(whichVM + LSOF_PID_PREFIX + lsof.pid()); + return new BufferedReader(new InputStreamReader(lsof.getInputStream())).lines(); } catch (IOException e) { throw new RuntimeException(e); } @@ -186,12 +334,12 @@ static Optional lsofCommand() { return lsofCommandCache; } - static Collection outputContainingFilenames() { + static Collection outputContainingFilenames(String whichVM) { long pid = ProcessHandle.current().pid(); String[] command = lsofCommand().orElseThrow(() -> new RuntimeException("lsof like command not found")); // Only search the directory in which the VM is running (user.dir property). System.out.println("using command: " + command[0] + " -a +d " + USER_DIR + " " + command[1] + " " + pid); - return run(command[0], "-a", "+d", USER_DIR, command[1], "" + pid).collect(toList()); + return runLsof(whichVM, command[0], "-a", "+d", USER_DIR, command[1], "" + pid).collect(toList()); } static boolean findOpenLogFile(Collection fileNames) { @@ -208,9 +356,7 @@ static boolean findOpenLogFile(Collection fileNames) { .isPresent(); } - static void windows(File f, long parentPid) throws InterruptedException { - System.out.println("waiting for pid: " + parentPid); - ProcessHandle.of(parentPid).ifPresent(handle -> handle.onExit().join()); + static void windows(File f) throws InterruptedException { System.out.println("trying to rename file to the same name: " + f); System.out.println(f.renameTo(f) ? RETAINS_FD : LEAKS_FD); // this parts communicates a closed file descriptor by printing "VM RESULT => RETAINS FD" } diff --git a/test/hotspot/jtreg/runtime/BadObjectClass/BootstrapRedefine.java b/test/hotspot/jtreg/runtime/BadObjectClass/BootstrapRedefine.java index c4dd815cc4a..d94dd1fb927 100644 --- a/test/hotspot/jtreg/runtime/BadObjectClass/BootstrapRedefine.java +++ b/test/hotspot/jtreg/runtime/BadObjectClass/BootstrapRedefine.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -51,7 +51,7 @@ public static void main(String[] args) throws Exception { "--patch-module=java.base"), "mods/java.base"); - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("--patch-module=java.base=mods/java.base", "-version"); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("--patch-module=java.base=mods/java.base", "-version"); new OutputAnalyzer(pb.start()) .shouldContain("Incompatible definition of java.lang.Object") .shouldHaveExitValue(1); diff --git a/test/hotspot/jtreg/runtime/BadObjectClass/TestUnloadClassError.java b/test/hotspot/jtreg/runtime/BadObjectClass/TestUnloadClassError.java index 59aa8e9ac6e..a2a75dc3155 100644 --- a/test/hotspot/jtreg/runtime/BadObjectClass/TestUnloadClassError.java +++ b/test/hotspot/jtreg/runtime/BadObjectClass/TestUnloadClassError.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2022, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -32,7 +32,9 @@ * @library /test/lib * @modules java.base/jdk.internal.misc * java.compiler - * @run main TestUnloadClassError + * @build jdk.test.whitebox.WhiteBox + * @run driver jdk.test.lib.helpers.ClassFileInstaller jdk.test.whitebox.WhiteBox + * @run main/othervm -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI TestUnloadClassError */ import jdk.test.lib.compiler.InMemoryJavaCompiler; diff --git a/test/hotspot/jtreg/runtime/BootClassAppendProp/BootClassPathAppend.java b/test/hotspot/jtreg/runtime/BootClassAppendProp/BootClassPathAppend.java index 8d6f0fddacd..67c6ca493df 100644 --- a/test/hotspot/jtreg/runtime/BootClassAppendProp/BootClassPathAppend.java +++ b/test/hotspot/jtreg/runtime/BootClassAppendProp/BootClassPathAppend.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2023, Oracle and/or its affiliates. All rights reserved. * 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,7 +38,7 @@ public class BootClassPathAppend { public static void main(String[] args) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:+PrintCompilation", "-Xcomp", "-version"); OutputAnalyzer output = new OutputAnalyzer(pb.start()); diff --git a/test/hotspot/jtreg/runtime/BootstrapMethod/BSMCalledTwice.java b/test/hotspot/jtreg/runtime/BootstrapMethod/BSMCalledTwice.java index a8a8aa060bf..fb00abb3d18 100644 --- a/test/hotspot/jtreg/runtime/BootstrapMethod/BSMCalledTwice.java +++ b/test/hotspot/jtreg/runtime/BootstrapMethod/BSMCalledTwice.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2023, Oracle and/or its affiliates. All rights reserved. * 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,7 +107,7 @@ public Class loadClass(String name) throws ClassNotFoundException { }; cl.loadClass(classTestCName); - ProcessBuilder pb = ProcessTools.createTestJvm("-cp", ".", classTestCName); + ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder("-cp", ".", classTestCName); OutputAnalyzer output = new OutputAnalyzer(pb.start()); String test_output = output.getOutput(); if (test_output == null) { diff --git a/test/hotspot/jtreg/runtime/BootstrapMethod/TestLambdaExceptionInInitializer.java b/test/hotspot/jtreg/runtime/BootstrapMethod/TestLambdaExceptionInInitializer.java index bc59c08854a..cda23793fbf 100644 --- a/test/hotspot/jtreg/runtime/BootstrapMethod/TestLambdaExceptionInInitializer.java +++ b/test/hotspot/jtreg/runtime/BootstrapMethod/TestLambdaExceptionInInitializer.java @@ -37,7 +37,7 @@ public class TestLambdaExceptionInInitializer { public static void main(String args[]) throws Throwable { // Run Lamba class - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("TestPkg.Lambda"); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("TestPkg.Lambda"); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldContain("Exception in thread \"main\" java.lang.ExceptionInInitializerError"); diff --git a/test/hotspot/jtreg/runtime/CDSCompressedKPtrs/CDSCompressedKPtrs.java b/test/hotspot/jtreg/runtime/CDSCompressedKPtrs/CDSCompressedKPtrs.java index be97d1cf056..51b0469ce46 100644 --- a/test/hotspot/jtreg/runtime/CDSCompressedKPtrs/CDSCompressedKPtrs.java +++ b/test/hotspot/jtreg/runtime/CDSCompressedKPtrs/CDSCompressedKPtrs.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -42,7 +42,7 @@ public class CDSCompressedKPtrs { public static void main(String[] args) throws Exception { ProcessBuilder pb; - pb = ProcessTools.createJavaProcessBuilder( + pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:+UseCompressedClassPointers", "-XX:+UseCompressedOops", "-XX:+UnlockDiagnosticVMOptions", "-XX:SharedArchiveFile=./CDSCompressedKPtrs.jsa", "-Xshare:dump", "-Xlog:cds"); OutputAnalyzer output = new OutputAnalyzer(pb.start()); @@ -50,7 +50,7 @@ public static void main(String[] args) throws Exception { output.shouldContain("Loading classes to share"); output.shouldHaveExitValue(0); - pb = ProcessTools.createJavaProcessBuilder( + pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:+UseCompressedClassPointers", "-XX:+UseCompressedOops", "-XX:+UnlockDiagnosticVMOptions", "-XX:SharedArchiveFile=./CDSCompressedKPtrs.jsa", "-Xshare:on", "-version"); output = new OutputAnalyzer(pb.start()); diff --git a/test/hotspot/jtreg/runtime/CDSCompressedKPtrs/XShareAuto.java b/test/hotspot/jtreg/runtime/CDSCompressedKPtrs/XShareAuto.java index 19c4128f460..e53758a671a 100644 --- a/test/hotspot/jtreg/runtime/CDSCompressedKPtrs/XShareAuto.java +++ b/test/hotspot/jtreg/runtime/CDSCompressedKPtrs/XShareAuto.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2023, Oracle and/or its affiliates. All rights reserved. * 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,7 +39,7 @@ public class XShareAuto { public static void main(String[] args) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-server", "-XX:+UnlockDiagnosticVMOptions", "-XX:SharedArchiveFile=./XShareAuto.jsa", "-Xshare:dump", "-Xlog:cds"); OutputAnalyzer output = new OutputAnalyzer(pb.start()); @@ -55,7 +55,7 @@ public static void main(String[] args) throws Exception { }; for (String x : cases) { - pb = ProcessTools.createJavaProcessBuilder( + pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:+UnlockDiagnosticVMOptions", "-XX:SharedArchiveFile=./XShareAuto.jsa", "-Xlog:cds", diff --git a/test/hotspot/jtreg/runtime/ClassFile/FormatCheckingTest.java b/test/hotspot/jtreg/runtime/ClassFile/FormatCheckingTest.java index 0ff1f0a65be..8ab2d2252a8 100644 --- a/test/hotspot/jtreg/runtime/ClassFile/FormatCheckingTest.java +++ b/test/hotspot/jtreg/runtime/ClassFile/FormatCheckingTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2023, Oracle and/or its affiliates. All rights reserved. * 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,7 +38,7 @@ public class FormatCheckingTest { public static void main(String args[]) throws Throwable { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("BadHelloWorld"); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("BadHelloWorld"); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldContain("java.lang.ClassFormatError: Illegal class name"); output.shouldHaveExitValue(1); diff --git a/test/hotspot/jtreg/runtime/ClassFile/JsrRewriting.java b/test/hotspot/jtreg/runtime/ClassFile/JsrRewriting.java index 92a9c74c276..36c23ac1f08 100644 --- a/test/hotspot/jtreg/runtime/ClassFile/JsrRewriting.java +++ b/test/hotspot/jtreg/runtime/ClassFile/JsrRewriting.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -68,7 +68,7 @@ public static void main(String[] args) throws Exception { output.shouldHaveExitValue(0); // ======= execute the test - pb = ProcessTools.createJavaProcessBuilder( + pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-cp", ".", "-XX:+UnlockDiagnosticVMOptions", "-XX:MallocMaxTestWords=" + mallocMaxTestWords, diff --git a/test/hotspot/jtreg/runtime/ClassFile/OomWhileParsingRepeatedJsr.java b/test/hotspot/jtreg/runtime/ClassFile/OomWhileParsingRepeatedJsr.java index 3f1d04c3d6d..516416d40a1 100644 --- a/test/hotspot/jtreg/runtime/ClassFile/OomWhileParsingRepeatedJsr.java +++ b/test/hotspot/jtreg/runtime/ClassFile/OomWhileParsingRepeatedJsr.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -67,7 +67,7 @@ public static void main(String[] args) throws Exception { output.shouldHaveExitValue(0); // ======= execute the test - pb = ProcessTools.createJavaProcessBuilder( + pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-cp", ".", "-XX:+UnlockDiagnosticVMOptions", "-XX:MallocMaxTestWords=" + mallocMaxTestWords, diff --git a/test/hotspot/jtreg/runtime/ClassFile/PreviewVersion.java b/test/hotspot/jtreg/runtime/ClassFile/PreviewVersion.java index 160d0559fbe..9e3ae8de832 100644 --- a/test/hotspot/jtreg/runtime/ClassFile/PreviewVersion.java +++ b/test/hotspot/jtreg/runtime/ClassFile/PreviewVersion.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -54,21 +54,21 @@ public static void main(String args[]) throws Throwable { // Run the test. This should fail because --enable-preview is not specified. ClassFileInstaller.writeClassToDisk("PVTest", klassbuf, System.getProperty("test.classes")); - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-cp", "." + File.pathSeparator + System.getProperty("test.classes"), "PVTest"); OutputAnalyzer oa = new OutputAnalyzer(pb.start()); oa.shouldContain("Preview features are not enabled"); oa.shouldHaveExitValue(1); // This should be successful because --enable-preview is specified. - pb = ProcessTools.createJavaProcessBuilder("--enable-preview", + pb = ProcessTools.createLimitedTestJavaProcessBuilder("--enable-preview", "-cp", "." + File.pathSeparator + System.getProperty("test.classes"), "PVTest"); oa = new OutputAnalyzer(pb.start()); oa.shouldContain("Hi!"); oa.shouldHaveExitValue(0); // Test -Xlog:class+preview - pb = ProcessTools.createJavaProcessBuilder("--enable-preview", "-Xlog:class+preview", + pb = ProcessTools.createLimitedTestJavaProcessBuilder("--enable-preview", "-Xlog:class+preview", "-cp", "." + File.pathSeparator + System.getProperty("test.classes"), "PVTest"); oa = new OutputAnalyzer(pb.start()); oa.shouldContain("[info][class,preview] Loading class PVTest that depends on preview features"); diff --git a/test/hotspot/jtreg/runtime/ClassFile/TestCheckedExceptions.java b/test/hotspot/jtreg/runtime/ClassFile/TestCheckedExceptions.java index a6f64e96bb6..3c041ed2536 100644 --- a/test/hotspot/jtreg/runtime/ClassFile/TestCheckedExceptions.java +++ b/test/hotspot/jtreg/runtime/ClassFile/TestCheckedExceptions.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2020, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -42,7 +42,7 @@ public class TestCheckedExceptions { public static void main(String... args) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-Xlog:exceptions=warning", "CheckedExceptions"); OutputAnalyzer output = new OutputAnalyzer(pb.start()); diff --git a/test/hotspot/jtreg/runtime/ClassFile/UnsupportedClassFileVersion.java b/test/hotspot/jtreg/runtime/ClassFile/UnsupportedClassFileVersion.java index 3ac53335ea4..c61f46c3ecd 100644 --- a/test/hotspot/jtreg/runtime/ClassFile/UnsupportedClassFileVersion.java +++ b/test/hotspot/jtreg/runtime/ClassFile/UnsupportedClassFileVersion.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2023, Oracle and/or its affiliates. All rights reserved. * 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,7 +41,7 @@ public class UnsupportedClassFileVersion implements Opcodes { public static void main(String... args) throws Exception { writeClassFile(); - ProcessBuilder pb = ProcessTools.createTestJvm("-cp", ".", "ClassFile"); + ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder("-cp", ".", "ClassFile"); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldContain("ClassFile has been compiled by a more recent version of the " + "Java Runtime (class file version 99.0), this version of " + diff --git a/test/hotspot/jtreg/runtime/CommandLine/BooleanFlagWithInvalidValue.java b/test/hotspot/jtreg/runtime/CommandLine/BooleanFlagWithInvalidValue.java index 0c59079bb8e..f57ca729980 100644 --- a/test/hotspot/jtreg/runtime/CommandLine/BooleanFlagWithInvalidValue.java +++ b/test/hotspot/jtreg/runtime/CommandLine/BooleanFlagWithInvalidValue.java @@ -36,14 +36,14 @@ public class BooleanFlagWithInvalidValue { public static void main(String[] args) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:+PrintWarnings=8", "-version"); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldContain("Improperly specified VM option 'PrintWarnings=8'"); output.shouldHaveExitValue(1); - pb = ProcessTools.createJavaProcessBuilder( + pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:-PrintWarnings=8", "-version"); output = new OutputAnalyzer(pb.start()); diff --git a/test/hotspot/jtreg/runtime/CommandLine/CompilerConfigFileWarning.java b/test/hotspot/jtreg/runtime/CommandLine/CompilerConfigFileWarning.java index 24738786115..0917832aef0 100644 --- a/test/hotspot/jtreg/runtime/CommandLine/CompilerConfigFileWarning.java +++ b/test/hotspot/jtreg/runtime/CommandLine/CompilerConfigFileWarning.java @@ -46,7 +46,7 @@ public static void main(String[] args) throws Exception { pw.println("aaa, aaa"); pw.close(); - pb = ProcessTools.createJavaProcessBuilder("-XX:CompileCommandFile=hs_comp.txt", "-version"); + pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:CompileCommandFile=hs_comp.txt", "-version"); output = new OutputAnalyzer(pb.start()); // problems in CompileCommandFile are treated as warnings output.shouldHaveExitValue(0); @@ -60,7 +60,7 @@ public static void main(String[] args) throws Exception { pw.println("aa"); pw.close(); - pb = ProcessTools.createJavaProcessBuilder("-version"); + pb = ProcessTools.createLimitedTestJavaProcessBuilder("-version"); output = new OutputAnalyzer(pb.start()); output.shouldHaveExitValue(0); output.shouldContain("warning: .hotspot_compiler file is present but has been ignored. Run with -XX:CompileCommandFile=.hotspot_compiler to load the file."); diff --git a/test/hotspot/jtreg/runtime/CommandLine/ConfigFileParsing.java b/test/hotspot/jtreg/runtime/CommandLine/ConfigFileParsing.java index b2b31ce6f75..218fd2ce1fe 100644 --- a/test/hotspot/jtreg/runtime/CommandLine/ConfigFileParsing.java +++ b/test/hotspot/jtreg/runtime/CommandLine/ConfigFileParsing.java @@ -50,7 +50,7 @@ public static void main(String[] args) throws Exception { pw.close(); // start VM - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:+IgnoreUnrecognizedVMOptions", "-XX:Flags=.hotspotrc", "-version"); OutputAnalyzer output = new OutputAnalyzer(pb.start()); diff --git a/test/hotspot/jtreg/runtime/CommandLine/ConfigFileWarning.java b/test/hotspot/jtreg/runtime/CommandLine/ConfigFileWarning.java index 862ef4c9ce0..df643b13d64 100644 --- a/test/hotspot/jtreg/runtime/CommandLine/ConfigFileWarning.java +++ b/test/hotspot/jtreg/runtime/CommandLine/ConfigFileWarning.java @@ -46,7 +46,7 @@ public static void main(String[] args) throws Exception { pw.println("aaa"); pw.close(); - pb = ProcessTools.createJavaProcessBuilder("-XX:Flags=hs_flags.txt","-version"); + pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:Flags=hs_flags.txt","-version"); output = new OutputAnalyzer(pb.start()); output.shouldContain("Unrecognized VM option 'aaa'"); output.shouldHaveExitValue(1); @@ -57,7 +57,7 @@ public static void main(String[] args) throws Exception { pw.println("aa"); pw.close(); - pb = ProcessTools.createJavaProcessBuilder("-version"); + pb = ProcessTools.createLimitedTestJavaProcessBuilder("-version"); output = new OutputAnalyzer(pb.start()); output.shouldHaveExitValue(0); output.shouldContain("warning: .hotspotrc file is present but has been ignored. Run with -XX:Flags=.hotspotrc to load the file."); diff --git a/test/hotspot/jtreg/runtime/CommandLine/DoubleFlagWithIntegerValue.java b/test/hotspot/jtreg/runtime/CommandLine/DoubleFlagWithIntegerValue.java index f26b7399671..69dd553e8b9 100644 --- a/test/hotspot/jtreg/runtime/CommandLine/DoubleFlagWithIntegerValue.java +++ b/test/hotspot/jtreg/runtime/CommandLine/DoubleFlagWithIntegerValue.java @@ -36,7 +36,7 @@ public class DoubleFlagWithIntegerValue { public static void testDoubleFlagWithValue(String value) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-XX:SweeperThreshold=" + value, "-version"); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:SweeperThreshold=" + value, "-version"); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldNotContain("Improperly specified VM option"); output.shouldHaveExitValue(0); diff --git a/test/hotspot/jtreg/runtime/CommandLine/FlagWithInvalidValue.java b/test/hotspot/jtreg/runtime/CommandLine/FlagWithInvalidValue.java index 053aa1c850d..175cefcad6a 100644 --- a/test/hotspot/jtreg/runtime/CommandLine/FlagWithInvalidValue.java +++ b/test/hotspot/jtreg/runtime/CommandLine/FlagWithInvalidValue.java @@ -36,7 +36,7 @@ public class FlagWithInvalidValue { public static void main(String[] args) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:MaxRAMPercentage=v", "-version"); OutputAnalyzer output = new OutputAnalyzer(pb.start()); diff --git a/test/hotspot/jtreg/runtime/CommandLine/IgnoreUnrecognizedVMOptions.java b/test/hotspot/jtreg/runtime/CommandLine/IgnoreUnrecognizedVMOptions.java index 0ebfdb56c4a..727fb1bd0a1 100644 --- a/test/hotspot/jtreg/runtime/CommandLine/IgnoreUnrecognizedVMOptions.java +++ b/test/hotspot/jtreg/runtime/CommandLine/IgnoreUnrecognizedVMOptions.java @@ -38,7 +38,7 @@ public class IgnoreUnrecognizedVMOptions { private static void runJavaAndCheckExitValue(boolean shouldSucceed, String... args) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(args); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(args); OutputAnalyzer output = new OutputAnalyzer(pb.start()); if (shouldSucceed) { output.shouldHaveExitValue(0); diff --git a/test/hotspot/jtreg/runtime/CommandLine/NonBooleanFlagWithInvalidBooleanPrefix.java b/test/hotspot/jtreg/runtime/CommandLine/NonBooleanFlagWithInvalidBooleanPrefix.java index b1fff188907..a6aca1ebf0e 100644 --- a/test/hotspot/jtreg/runtime/CommandLine/NonBooleanFlagWithInvalidBooleanPrefix.java +++ b/test/hotspot/jtreg/runtime/CommandLine/NonBooleanFlagWithInvalidBooleanPrefix.java @@ -36,14 +36,14 @@ public class NonBooleanFlagWithInvalidBooleanPrefix { public static void main(String[] args) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:-MaxRAMPercentage=1", "-version"); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldContain("Unexpected +/- setting in VM option 'MaxRAMPercentage=1'"); output.shouldHaveExitValue(1); - pb = ProcessTools.createJavaProcessBuilder( + pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:+MaxRAMPercentage=1", "-version"); output = new OutputAnalyzer(pb.start()); diff --git a/test/hotspot/jtreg/runtime/CommandLine/ObsoleteFlagErrorMessage.java b/test/hotspot/jtreg/runtime/CommandLine/ObsoleteFlagErrorMessage.java index 485d3cc57f5..5f697bdeb44 100644 --- a/test/hotspot/jtreg/runtime/CommandLine/ObsoleteFlagErrorMessage.java +++ b/test/hotspot/jtreg/runtime/CommandLine/ObsoleteFlagErrorMessage.java @@ -40,7 +40,7 @@ public static void main(String[] args) throws Exception { String flag = "DummyObsoleteTestFlag"; // Case 1: Newly obsolete flags with extra junk appended should not be treated as newly obsolete (8060449) - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:" + flag + "PlusJunk", "-version"); OutputAnalyzer output = new OutputAnalyzer(pb.start()); @@ -48,7 +48,7 @@ public static void main(String[] args) throws Exception { output.shouldHaveExitValue(1); // Case 2: Newly obsolete flags should be recognized as newly obsolete (8073989) - ProcessBuilder pb2 = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb2 = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:+" + flag, "-version"); OutputAnalyzer output2 = new OutputAnalyzer(pb2.start()); diff --git a/test/hotspot/jtreg/runtime/CommandLine/OptionsValidation/TestJcmdOutput.java b/test/hotspot/jtreg/runtime/CommandLine/OptionsValidation/TestJcmdOutput.java index b946945a800..e7f59481478 100644 --- a/test/hotspot/jtreg/runtime/CommandLine/OptionsValidation/TestJcmdOutput.java +++ b/test/hotspot/jtreg/runtime/CommandLine/OptionsValidation/TestJcmdOutput.java @@ -50,7 +50,7 @@ public static void main(String[] args) throws Exception { OutputAnalyzer output; System.out.println("Verify jcmd error message and that jcmd does not write errors to the target process output"); - output = new OutputAnalyzer((ProcessTools.createJavaProcessBuilder( + output = new OutputAnalyzer((ProcessTools.createLimitedTestJavaProcessBuilder( "-Dtest.jdk=" + System.getProperty("test.jdk"), "-XX:MinHeapFreeRatio=20", "-XX:MaxHeapFreeRatio=80", runJcmd.class.getName())).start()); diff --git a/test/hotspot/jtreg/runtime/CommandLine/OptionsValidation/common/optionsvalidation/JVMOption.java b/test/hotspot/jtreg/runtime/CommandLine/OptionsValidation/common/optionsvalidation/JVMOption.java index ed37cc65601..78a508343d6 100644 --- a/test/hotspot/jtreg/runtime/CommandLine/OptionsValidation/common/optionsvalidation/JVMOption.java +++ b/test/hotspot/jtreg/runtime/CommandLine/OptionsValidation/common/optionsvalidation/JVMOption.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -417,7 +417,7 @@ private boolean runJavaWithParam(String optionValue, boolean valid) throws Excep runJava.add(optionValue); runJava.add(JVMStartup.class.getName()); - out = new OutputAnalyzer(ProcessTools.createJavaProcessBuilder(runJava).start()); + out = new OutputAnalyzer(ProcessTools.createLimitedTestJavaProcessBuilder(runJava).start()); exitCode = out.getExitValue(); String exitCodeString = null; diff --git a/test/hotspot/jtreg/runtime/CommandLine/OptionsValidation/common/optionsvalidation/JVMOptionsUtils.java b/test/hotspot/jtreg/runtime/CommandLine/OptionsValidation/common/optionsvalidation/JVMOptionsUtils.java index ba0b2f7d61f..031d30bf2bd 100644 --- a/test/hotspot/jtreg/runtime/CommandLine/OptionsValidation/common/optionsvalidation/JVMOptionsUtils.java +++ b/test/hotspot/jtreg/runtime/CommandLine/OptionsValidation/common/optionsvalidation/JVMOptionsUtils.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -469,7 +469,7 @@ private static Map getOptionsAsMap(boolean withRanges, Predic runJava.add(PRINT_FLAGS_RANGES); runJava.add("-version"); - p = ProcessTools.createJavaProcessBuilder(runJava).start(); + p = ProcessTools.createLimitedTestJavaProcessBuilder(runJava).start(); result = getJVMOptions(new InputStreamReader(p.getInputStream()), withRanges, acceptOrigin); diff --git a/test/hotspot/jtreg/runtime/CommandLine/PrintTouchedMethods.java b/test/hotspot/jtreg/runtime/CommandLine/PrintTouchedMethods.java index a5900132b75..61e802679d6 100644 --- a/test/hotspot/jtreg/runtime/CommandLine/PrintTouchedMethods.java +++ b/test/hotspot/jtreg/runtime/CommandLine/PrintTouchedMethods.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2024, Oracle and/or its affiliates. All rights reserved. * 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,7 +40,7 @@ public class PrintTouchedMethods { public static void main(String args[]) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:-UnlockDiagnosticVMOptions", "-XX:+LogTouchedMethods", "-XX:+PrintTouchedMethodsAtExit", @@ -52,7 +52,7 @@ public static void main(String args[]) throws Exception { output.shouldContain("Error: VM option 'LogTouchedMethods' is diagnostic and must be enabled via -XX:+UnlockDiagnosticVMOptions."); output.shouldContain("Error: Could not create the Java Virtual Machine."); - pb = ProcessTools.createJavaProcessBuilder( + pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:+UnlockDiagnosticVMOptions", "-XX:+LogTouchedMethods", "-XX:+PrintTouchedMethodsAtExit", @@ -78,7 +78,7 @@ public static void main(String args[]) throws Exception { output.shouldNotContain("TestLogTouchedMethods.methodB:()V"); output.shouldHaveExitValue(0); - pb = ProcessTools.createJavaProcessBuilder( + pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:+UnlockDiagnosticVMOptions", "-Xint", "-XX:+LogTouchedMethods", @@ -100,7 +100,7 @@ public static void main(String args[]) throws Exception { output.shouldNotContain("TestLogTouchedMethods.methodB:()V"); output.shouldHaveExitValue(0); - pb = ProcessTools.createJavaProcessBuilder( + pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:+UnlockDiagnosticVMOptions", "-Xint", "-XX:+LogTouchedMethods", diff --git a/test/hotspot/jtreg/runtime/CommandLine/TestHexArguments.java b/test/hotspot/jtreg/runtime/CommandLine/TestHexArguments.java index 9d864610c57..b9261151d82 100644 --- a/test/hotspot/jtreg/runtime/CommandLine/TestHexArguments.java +++ b/test/hotspot/jtreg/runtime/CommandLine/TestHexArguments.java @@ -38,13 +38,13 @@ public class TestHexArguments { public static void main(String args[]) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:SharedBaseAddress=0x1D000000", "-version"); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldNotContain("Could not create the Java Virtual Machine"); output.shouldHaveExitValue(0); - pb = ProcessTools.createJavaProcessBuilder( + pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:SharedBaseAddress=1D000000", "-version"); output = new OutputAnalyzer(pb.start()); output.shouldNotHaveExitValue(0); diff --git a/test/hotspot/jtreg/runtime/CommandLine/TestLongUnrecognizedVMOption.java b/test/hotspot/jtreg/runtime/CommandLine/TestLongUnrecognizedVMOption.java index 26fd50b6bfe..90b28512bd5 100644 --- a/test/hotspot/jtreg/runtime/CommandLine/TestLongUnrecognizedVMOption.java +++ b/test/hotspot/jtreg/runtime/CommandLine/TestLongUnrecognizedVMOption.java @@ -42,7 +42,7 @@ public class TestLongUnrecognizedVMOption { public static void main(String[] args) throws Exception { OutputAnalyzer output; - output = new OutputAnalyzer(ProcessTools.createJavaProcessBuilder("-XX:" + VERY_LONG_OPTION, "-version").start()); + output = new OutputAnalyzer(ProcessTools.createLimitedTestJavaProcessBuilder("-XX:" + VERY_LONG_OPTION, "-version").start()); output.shouldHaveExitValue(1); output.shouldContain(String.format("Unrecognized VM option '%s'", VERY_LONG_OPTION)); } diff --git a/test/hotspot/jtreg/runtime/CommandLine/TestNullTerminatedFlags.java b/test/hotspot/jtreg/runtime/CommandLine/TestNullTerminatedFlags.java index cc1b09d6442..aa79f1a252d 100644 --- a/test/hotspot/jtreg/runtime/CommandLine/TestNullTerminatedFlags.java +++ b/test/hotspot/jtreg/runtime/CommandLine/TestNullTerminatedFlags.java @@ -57,7 +57,7 @@ public static void main(String args[]) throws Exception{ for (String option : options) { String testOption = option + "junk"; ProcessBuilder pb = - ProcessTools.createJavaProcessBuilder(testOption, "-version"); + ProcessTools.createLimitedTestJavaProcessBuilder(testOption, "-version"); new OutputAnalyzer(pb.start()) .shouldContain("Unrecognized option: " + testOption) .shouldHaveExitValue(1); diff --git a/test/hotspot/jtreg/runtime/CommandLine/TestVMOptions.java b/test/hotspot/jtreg/runtime/CommandLine/TestVMOptions.java index 8d13e1ab50d..673272f17b1 100644 --- a/test/hotspot/jtreg/runtime/CommandLine/TestVMOptions.java +++ b/test/hotspot/jtreg/runtime/CommandLine/TestVMOptions.java @@ -37,7 +37,7 @@ public class TestVMOptions { public static void main(String[] args) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:bogus", "-XX:+IgnoreUnrecognizedVMOptions", "-XX:+PrintFlagsInitial"); @@ -45,7 +45,7 @@ public static void main(String[] args) throws Exception { output.shouldHaveExitValue(0); output.shouldContain("bool UseSerialGC"); - pb = ProcessTools.createJavaProcessBuilder( + pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:-PrintVMOptions", "-version"); output = new OutputAnalyzer(pb.start()); output.shouldHaveExitValue(0); @@ -54,7 +54,7 @@ public static void main(String[] args) throws Exception { File dir = new File(System.getProperty("test.src", ".")); File file = new File(dir, "flagfile.txt"); String s = file.getAbsolutePath(); - pb = ProcessTools.createJavaProcessBuilder("-XX:Flags="+s); + pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:Flags="+s); output = new OutputAnalyzer(pb.start()); output.shouldNotHaveExitValue(0); output.shouldContain("VM option '-IgnoreUnrecognizedVMOptions'"); diff --git a/test/hotspot/jtreg/runtime/CommandLine/TraceExceptionsTest.java b/test/hotspot/jtreg/runtime/CommandLine/TraceExceptionsTest.java index 5a363114882..5d16bd7b9c3 100644 --- a/test/hotspot/jtreg/runtime/CommandLine/TraceExceptionsTest.java +++ b/test/hotspot/jtreg/runtime/CommandLine/TraceExceptionsTest.java @@ -37,7 +37,7 @@ public class TraceExceptionsTest { public static void main(String[] args) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-Xlog:exceptions=info", "NoClassFound"); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldContain(""); diff --git a/test/hotspot/jtreg/runtime/CommandLine/UnrecognizedVMOption.java b/test/hotspot/jtreg/runtime/CommandLine/UnrecognizedVMOption.java index 9c1cd8cb254..120a7c90181 100644 --- a/test/hotspot/jtreg/runtime/CommandLine/UnrecognizedVMOption.java +++ b/test/hotspot/jtreg/runtime/CommandLine/UnrecognizedVMOption.java @@ -43,7 +43,7 @@ public static void main(String[] args) throws Exception { "bogus_option", }; for (String option : badOptions) { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:" + option, "-version"); OutputAnalyzer output = new OutputAnalyzer(pb.start()); diff --git a/test/hotspot/jtreg/runtime/CommandLine/VMDeprecatedOptions.java b/test/hotspot/jtreg/runtime/CommandLine/VMDeprecatedOptions.java index 79f02e4368e..f2abbaa872e 100644 --- a/test/hotspot/jtreg/runtime/CommandLine/VMDeprecatedOptions.java +++ b/test/hotspot/jtreg/runtime/CommandLine/VMDeprecatedOptions.java @@ -80,7 +80,7 @@ static void testDeprecated(String[][] optionInfo) throws Throwable { // command line by -XX:+UnlockDiagnosticVMOptions. static void testDeprecatedDiagnostic(String option, String value) throws Throwable { String XXoption = CommandLineOptionTest.prepareFlag(option, value); - ProcessBuilder processBuilder = ProcessTools.createJavaProcessBuilder( + ProcessBuilder processBuilder = ProcessTools.createLimitedTestJavaProcessBuilder( CommandLineOptionTest.UNLOCK_DIAGNOSTIC_VM_OPTIONS, XXoption, "-version"); OutputAnalyzer output = new OutputAnalyzer(processBuilder.start()); // check for option deprecation message: @@ -93,7 +93,7 @@ static void testDeprecatedDiagnostic(String option, String value) throws Throwa // command line by -XX:+UnlockExperimentalVMOption. static void testDeprecatedExperimental(String option, String value) throws Throwable { String XXoption = CommandLineOptionTest.prepareFlag(option, value); - ProcessBuilder processBuilder = ProcessTools.createJavaProcessBuilder( + ProcessBuilder processBuilder = ProcessTools.createLimitedTestJavaProcessBuilder( CommandLineOptionTest.UNLOCK_EXPERIMENTAL_VM_OPTIONS, XXoption, "-version"); OutputAnalyzer output = new OutputAnalyzer(processBuilder.start()); // check for option deprecation message: diff --git a/test/hotspot/jtreg/runtime/CommandLine/VMOptionWarning.java b/test/hotspot/jtreg/runtime/CommandLine/VMOptionWarning.java index 01305cc9162..d4e0df49ece 100644 --- a/test/hotspot/jtreg/runtime/CommandLine/VMOptionWarning.java +++ b/test/hotspot/jtreg/runtime/CommandLine/VMOptionWarning.java @@ -37,7 +37,7 @@ public class VMOptionWarning { public static void main(String[] args) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-XX:+AlwaysSafeConstructors", "-version"); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:+AlwaysSafeConstructors", "-version"); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldNotHaveExitValue(0); output.shouldContain("Error: VM option 'AlwaysSafeConstructors' is experimental and must be enabled via -XX:+UnlockExperimentalVMOptions."); @@ -47,17 +47,17 @@ public static void main(String[] args) throws Exception { return; } - pb = ProcessTools.createJavaProcessBuilder("-XX:+PrintInlining", "-version"); + pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:+PrintInlining", "-version"); output = new OutputAnalyzer(pb.start()); output.shouldNotHaveExitValue(0); output.shouldContain("Error: VM option 'PrintInlining' is diagnostic and must be enabled via -XX:+UnlockDiagnosticVMOptions."); - pb = ProcessTools.createJavaProcessBuilder("-XX:+VerifyStack", "-version"); + pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:+VerifyStack", "-version"); output = new OutputAnalyzer(pb.start()); output.shouldNotHaveExitValue(0); output.shouldContain("Error: VM option 'VerifyStack' is develop and is available only in debug version of VM."); - pb = ProcessTools.createJavaProcessBuilder("-XX:+CheckCompressedOops", "-version"); + pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:+CheckCompressedOops", "-version"); output = new OutputAnalyzer(pb.start()); output.shouldNotHaveExitValue(0); output.shouldContain("Error: VM option 'CheckCompressedOops' is notproduct and is available only in debug version of VM."); diff --git a/test/hotspot/jtreg/runtime/CommandLine/VMOptionsFile/TestVMOptionsFile.java b/test/hotspot/jtreg/runtime/CommandLine/VMOptionsFile/TestVMOptionsFile.java index 24d84a03f93..c22656724c2 100644 --- a/test/hotspot/jtreg/runtime/CommandLine/VMOptionsFile/TestVMOptionsFile.java +++ b/test/hotspot/jtreg/runtime/CommandLine/VMOptionsFile/TestVMOptionsFile.java @@ -247,7 +247,7 @@ private static ProcessBuilder createProcessBuilder() throws Exception { runJava.add(PrintPropertyAndOptions.class.getName()); runJava.addAll(appParams); - pb = ProcessTools.createJavaProcessBuilder(runJava); + pb = ProcessTools.createLimitedTestJavaProcessBuilder(runJava); VMParams.clear(); appParams.clear(); diff --git a/test/hotspot/jtreg/runtime/CompressedOops/CompressedClassPointers.java b/test/hotspot/jtreg/runtime/CompressedOops/CompressedClassPointers.java index 8e2033e7329..00712c29be3 100644 --- a/test/hotspot/jtreg/runtime/CompressedOops/CompressedClassPointers.java +++ b/test/hotspot/jtreg/runtime/CompressedOops/CompressedClassPointers.java @@ -55,7 +55,7 @@ static boolean testNarrowKlassBase() { // CDS off, small heap, ccs size default (1G) // A small heap should allow us to place the ccs within the lower 32G and thus allow zero based encoding. public static void smallHeapTest() throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:+UnlockDiagnosticVMOptions", "-XX:SharedBaseAddress=8g", "-Xmx128m", @@ -72,7 +72,7 @@ public static void smallHeapTest() throws Exception { // CDS off, small heap, ccs size explicitely set to 1G // A small heap should allow us to place the ccs within the lower 32G and thus allow zero based encoding. public static void smallHeapTestWith1G() throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:+UnlockDiagnosticVMOptions", "-XX:CompressedClassSpaceSize=1g", "-Xmx128m", @@ -90,7 +90,7 @@ public static void smallHeapTestWith1G() throws Exception { // We expect the ccs to be mapped somewhere far beyond the heap, such that it is not possible // to use zero based encoding. public static void largeHeapTest() throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:+UnlockDiagnosticVMOptions", "-XX:+UnlockExperimentalVMOptions", "-Xmx30g", @@ -115,7 +115,7 @@ public static void largeHeapTest() throws Exception { // for compressed oops. // We expect a zerobased ccs. public static void largeHeapAbove32GTest() throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:+UnlockDiagnosticVMOptions", "-XX:+UnlockExperimentalVMOptions", "-Xmx31g", @@ -136,7 +136,7 @@ public static void largeHeapAbove32GTest() throws Exception { // Using large paged heap, metaspace uses small pages. public static void largePagesForHeapTest() throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:+UnlockDiagnosticVMOptions", "-Xmx128m", "-XX:+UseLargePages", @@ -150,7 +150,7 @@ public static void largePagesForHeapTest() throws Exception { } public static void heapBaseMinAddressTest() throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:HeapBaseMinAddress=1m", "-Xlog:gc+heap+coops=debug", "-version"); @@ -161,7 +161,7 @@ public static void heapBaseMinAddressTest() throws Exception { public static void sharingTest() throws Exception { // Test small heaps - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:+UnlockDiagnosticVMOptions", "-XX:SharedArchiveFile=./CompressedClassPointers.jsa", "-Xmx128m", @@ -177,7 +177,7 @@ public static void sharingTest() throws Exception { output.shouldContain("Loading classes to share"); output.shouldHaveExitValue(0); - pb = ProcessTools.createJavaProcessBuilder( + pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:+UnlockDiagnosticVMOptions", "-XX:SharedArchiveFile=./CompressedClassPointers.jsa", "-Xmx128m", @@ -196,7 +196,7 @@ public static void sharingTest() throws Exception { } public static void smallHeapTestNoCoop() throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:-UseCompressedOops", "-XX:+UseCompressedClassPointers", "-XX:+UnlockDiagnosticVMOptions", @@ -212,7 +212,7 @@ public static void smallHeapTestNoCoop() throws Exception { } public static void smallHeapTestWith1GNoCoop() throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:-UseCompressedOops", "-XX:+UseCompressedClassPointers", "-XX:+UnlockDiagnosticVMOptions", @@ -232,7 +232,7 @@ public static void smallHeapTestWith1GNoCoop() throws Exception { } public static void largeHeapTestNoCoop() throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:-UseCompressedOops", "-XX:+UseCompressedClassPointers", "-XX:+UnlockDiagnosticVMOptions", @@ -252,7 +252,7 @@ public static void largeHeapTestNoCoop() throws Exception { } public static void largePagesTestNoCoop() throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:-UseCompressedOops", "-XX:+UseCompressedClassPointers", "-XX:+UnlockDiagnosticVMOptions", @@ -266,7 +266,7 @@ public static void largePagesTestNoCoop() throws Exception { } public static void heapBaseMinAddressTestNoCoop() throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:-UseCompressedOops", "-XX:+UseCompressedClassPointers", "-XX:HeapBaseMinAddress=1m", @@ -279,7 +279,7 @@ public static void heapBaseMinAddressTestNoCoop() throws Exception { public static void sharingTestNoCoop() throws Exception { // Test small heaps - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:-UseCompressedOops", "-XX:+UseCompressedClassPointers", "-XX:+UnlockDiagnosticVMOptions", @@ -297,7 +297,7 @@ public static void sharingTestNoCoop() throws Exception { output.shouldContain("Loading classes to share"); output.shouldHaveExitValue(0); - pb = ProcessTools.createJavaProcessBuilder( + pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:-UseCompressedOops", "-XX:+UseCompressedClassPointers", "-XX:+UnlockDiagnosticVMOptions", diff --git a/test/hotspot/jtreg/runtime/CompressedOops/CompressedClassSpaceSize.java b/test/hotspot/jtreg/runtime/CompressedOops/CompressedClassSpaceSize.java index 5eaced668f0..e0ec1271346 100644 --- a/test/hotspot/jtreg/runtime/CompressedOops/CompressedClassSpaceSize.java +++ b/test/hotspot/jtreg/runtime/CompressedOops/CompressedClassSpaceSize.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2023, Oracle and/or its affiliates. All rights reserved. * 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,23 +42,23 @@ public static void main(String[] args) throws Exception { ProcessBuilder pb; OutputAnalyzer output; // Minimum size is 1MB - pb = ProcessTools.createJavaProcessBuilder("-XX:CompressedClassSpaceSize=0", - "-version"); + pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:CompressedClassSpaceSize=0", + "-version"); output = new OutputAnalyzer(pb.start()); output.shouldContain("outside the allowed range") .shouldHaveExitValue(1); // Invalid size of -1 should be handled correctly - pb = ProcessTools.createJavaProcessBuilder("-XX:CompressedClassSpaceSize=-1", - "-version"); + pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:CompressedClassSpaceSize=-1", + "-version"); output = new OutputAnalyzer(pb.start()); output.shouldContain("Improperly specified VM option 'CompressedClassSpaceSize=-1'") .shouldHaveExitValue(1); // Maximum size is 3GB - pb = ProcessTools.createJavaProcessBuilder("-XX:CompressedClassSpaceSize=4g", - "-version"); + pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:CompressedClassSpaceSize=4g", + "-version"); output = new OutputAnalyzer(pb.start()); output.shouldContain("outside the allowed range") .shouldHaveExitValue(1); @@ -67,28 +67,28 @@ public static void main(String[] args) throws Exception { // Make sure the minimum size is set correctly and printed // (Note: ccs size are rounded up to the next larger root chunk boundary (16m). // Note that this is **reserved** size and does not affect rss. - pb = ProcessTools.createJavaProcessBuilder("-XX:+UnlockDiagnosticVMOptions", - "-XX:CompressedClassSpaceSize=1m", - "-Xlog:gc+metaspace=trace", - "-version"); + pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:+UnlockDiagnosticVMOptions", + "-XX:CompressedClassSpaceSize=1m", + "-Xlog:gc+metaspace=trace", + "-version"); output = new OutputAnalyzer(pb.start()); output.shouldMatch("Compressed class space.*16777216") .shouldHaveExitValue(0); // Make sure the maximum size is set correctly and printed - pb = ProcessTools.createJavaProcessBuilder("-XX:+UnlockDiagnosticVMOptions", - "-XX:CompressedClassSpaceSize=3g", - "-Xlog:gc+metaspace=trace", - "-version"); + pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:+UnlockDiagnosticVMOptions", + "-XX:CompressedClassSpaceSize=3g", + "-Xlog:gc+metaspace=trace", + "-version"); output = new OutputAnalyzer(pb.start()); output.shouldMatch("Compressed class space.*3221225472") .shouldHaveExitValue(0); - pb = ProcessTools.createJavaProcessBuilder("-XX:-UseCompressedClassPointers", - "-XX:CompressedClassSpaceSize=1m", - "-version"); + pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:-UseCompressedClassPointers", + "-XX:CompressedClassSpaceSize=1m", + "-version"); output = new OutputAnalyzer(pb.start()); output.shouldContain("Setting CompressedClassSpaceSize has no effect when compressed class pointers are not used") .shouldHaveExitValue(0); diff --git a/test/hotspot/jtreg/runtime/CompressedOops/CompressedKlassPointerAndOops.java b/test/hotspot/jtreg/runtime/CompressedOops/CompressedKlassPointerAndOops.java index 28c517bbca9..403654d1cc8 100644 --- a/test/hotspot/jtreg/runtime/CompressedOops/CompressedKlassPointerAndOops.java +++ b/test/hotspot/jtreg/runtime/CompressedOops/CompressedKlassPointerAndOops.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2023, Oracle and/or its affiliates. All rights reserved. * 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,7 +50,7 @@ private static void runWithAlignment(int alignment) throws Exception { ProcessBuilder pb; OutputAnalyzer output; - pb = ProcessTools.createJavaProcessBuilder( + pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:+UseCompressedClassPointers", "-XX:+UseCompressedOops", "-XX:ObjectAlignmentInBytes=" + alignment, diff --git a/test/hotspot/jtreg/runtime/CompressedOops/ObjectAlignment.java b/test/hotspot/jtreg/runtime/CompressedOops/ObjectAlignment.java index f9c6d6921aa..0cf4a72f519 100644 --- a/test/hotspot/jtreg/runtime/CompressedOops/ObjectAlignment.java +++ b/test/hotspot/jtreg/runtime/CompressedOops/ObjectAlignment.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -74,8 +74,8 @@ public static void main(String[] args) throws Exception { } private static OutputAnalyzer testObjectAlignment(int alignment) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-XX:ObjectAlignmentInBytes=" + alignment, - "-version"); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:ObjectAlignmentInBytes=" + alignment, + "-version"); return new OutputAnalyzer(pb.start()); } } diff --git a/test/hotspot/jtreg/runtime/CompressedOops/UseCompressedOops.java b/test/hotspot/jtreg/runtime/CompressedOops/UseCompressedOops.java index bf4d58232a8..3d118bf73b1 100644 --- a/test/hotspot/jtreg/runtime/CompressedOops/UseCompressedOops.java +++ b/test/hotspot/jtreg/runtime/CompressedOops/UseCompressedOops.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -189,7 +189,7 @@ private static OutputAnalyzer testCompressedOops(ArrayList flags1, Strin args.add("-version"); - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(args); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(args); return new OutputAnalyzer(pb.start()); } } diff --git a/test/hotspot/jtreg/runtime/Dictionary/CleanProtectionDomain.java b/test/hotspot/jtreg/runtime/Dictionary/CleanProtectionDomain.java index 493f02f3036..4e4a9329f5d 100644 --- a/test/hotspot/jtreg/runtime/Dictionary/CleanProtectionDomain.java +++ b/test/hotspot/jtreg/runtime/Dictionary/CleanProtectionDomain.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -43,7 +43,7 @@ public class CleanProtectionDomain { public static void main(String args[]) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-Xlog:protectiondomain+table=debug", "--add-exports=java.base/jdk.internal.misc=ALL-UNNAMED", "-XX:+UnlockDiagnosticVMOptions", diff --git a/test/hotspot/jtreg/runtime/Dictionary/ProtectionDomainCacheTest.java b/test/hotspot/jtreg/runtime/Dictionary/ProtectionDomainCacheTest.java index 756bff98ffb..423fba7d221 100644 --- a/test/hotspot/jtreg/runtime/Dictionary/ProtectionDomainCacheTest.java +++ b/test/hotspot/jtreg/runtime/Dictionary/ProtectionDomainCacheTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -98,7 +98,7 @@ public static void main(final String[] args) throws Exception { } public static void main(String args[]) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-Djava.security.policy==" + System.getProperty("test.src") + File.separator + "test.policy", "-Dtest.classes=" + System.getProperty("test.classes", "."), "-XX:+UnlockDiagnosticVMOptions", diff --git a/test/hotspot/jtreg/runtime/EnclosingMethodAttr/EnclMethodAttr.java b/test/hotspot/jtreg/runtime/EnclosingMethodAttr/EnclMethodAttr.java index db6b924078b..9b9acdce023 100644 --- a/test/hotspot/jtreg/runtime/EnclosingMethodAttr/EnclMethodAttr.java +++ b/test/hotspot/jtreg/runtime/EnclosingMethodAttr/EnclMethodAttr.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -42,7 +42,7 @@ public class EnclMethodAttr { public static void main(String args[]) throws Throwable { System.out.println("Regression test for bug 8044738"); - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("EnclMethTest"); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("EnclMethTest"); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldNotHaveExitValue(0); output.shouldContain("java.lang.ClassFormatError: Wrong EnclosingMethod"); diff --git a/test/hotspot/jtreg/runtime/ErrorHandling/BadNativeStackInErrorHandlingTest.java b/test/hotspot/jtreg/runtime/ErrorHandling/BadNativeStackInErrorHandlingTest.java index a51a891b031..6c26139cc7e 100644 --- a/test/hotspot/jtreg/runtime/ErrorHandling/BadNativeStackInErrorHandlingTest.java +++ b/test/hotspot/jtreg/runtime/ErrorHandling/BadNativeStackInErrorHandlingTest.java @@ -45,7 +45,7 @@ // This test was adapted from SafeFetchInErrorHandlingTest.java. public class BadNativeStackInErrorHandlingTest { public static void main(String[] args) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:+UnlockDiagnosticVMOptions", "-Xmx100M", "-XX:ErrorHandlerTest=14", diff --git a/test/hotspot/jtreg/runtime/ErrorHandling/ClassPathEnvVar.java b/test/hotspot/jtreg/runtime/ErrorHandling/ClassPathEnvVar.java new file mode 100644 index 00000000000..4b4e41944de --- /dev/null +++ b/test/hotspot/jtreg/runtime/ErrorHandling/ClassPathEnvVar.java @@ -0,0 +1,85 @@ +/* + * Copyright (c) 2021, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute 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 8271003 + * @summary CLASSPATH env variable setting should not be truncated in a hs err log. + * @requires vm.flagless + * @requires vm.debug + * @library /test/lib + * @run driver ClassPathEnvVar + */ +import java.io.File; +import java.util.Map; + +import jdk.test.lib.process.ProcessTools; +import jdk.test.lib.process.OutputAnalyzer; + +public class ClassPathEnvVar { + private static final String pathSep = File.pathSeparator; + private static final String sep = File.separator; + private static final String classPathEnv = "CLASSPATH"; + private static final String endPath = "end-path"; + + public static void main(String[] args) throws Exception { + OutputAnalyzer output = runCrasher().shouldContain("CreateCoredumpOnCrash turned off, no core file dumped") + .shouldNotHaveExitValue(0); + + checkErrorLog(output); + + } + private static OutputAnalyzer runCrasher() throws Exception { + ProcessBuilder pb = + ProcessTools.createLimitedTestJavaProcessBuilder("-XX:-CreateCoredumpOnCrash", + "-XX:ErrorHandlerTest=14", + "-XX:+ErrorFileToStdout"); + + // Obtain the CLASSPATH setting and expand it to more than 2000 chars. + Map envMap = pb.environment(); + String cp = envMap.get(classPathEnv); + if (cp == null) { + cp = "this" + sep + "is" + sep + "dummy" + sep + "path"; + } + while (cp.length() < 2000) { + cp += pathSep + cp; + } + cp += pathSep + endPath; + envMap.put(classPathEnv, cp); + + return new OutputAnalyzer(pb.start()); + } + + private static void checkErrorLog(OutputAnalyzer output) throws Exception { + String classPathLine = output.firstMatch("CLASSPATH=.*"); + + if (classPathLine == null) { + throw new RuntimeException("CLASSPATH setting not found in hs err log."); + } + + // Check if the CLASSPATH line has been truncated. + if (!classPathLine.endsWith(endPath)) { + throw new RuntimeException("CLASSPATH was truncated in the hs err log."); + } + } +} diff --git a/test/hotspot/jtreg/runtime/ErrorHandling/CreateCoredumpOnCrash.java b/test/hotspot/jtreg/runtime/ErrorHandling/CreateCoredumpOnCrash.java index 36502046570..73efc0e5e46 100644 --- a/test/hotspot/jtreg/runtime/ErrorHandling/CreateCoredumpOnCrash.java +++ b/test/hotspot/jtreg/runtime/ErrorHandling/CreateCoredumpOnCrash.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2023, Oracle and/or its affiliates. All rights reserved. * 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,7 +59,7 @@ public static void main(String[] args) throws Exception { } public static OutputAnalyzer runTest(String option) throws Exception { return new OutputAnalyzer( - ProcessTools.createJavaProcessBuilder( + ProcessTools.createLimitedTestJavaProcessBuilder( "-Xmx128m", "--add-exports=java.base/jdk.internal.misc=ALL-UNNAMED", option, Crasher.class.getName()) .start()); } diff --git a/test/hotspot/jtreg/runtime/ErrorHandling/ErrorFileOverwriteTest.java b/test/hotspot/jtreg/runtime/ErrorHandling/ErrorFileOverwriteTest.java index ea8e944aebb..5fcb4ec5f9e 100644 --- a/test/hotspot/jtreg/runtime/ErrorHandling/ErrorFileOverwriteTest.java +++ b/test/hotspot/jtreg/runtime/ErrorHandling/ErrorFileOverwriteTest.java @@ -97,7 +97,7 @@ public static void do_test(boolean with_percent_p) throws Exception { System.out.println("First crash..."); - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-Xmx64M", "-XX:-CreateCoredumpOnCrash", "-XX:ErrorHandlerTest=1", @@ -123,7 +123,7 @@ public static void do_test(boolean with_percent_p) throws Exception { System.out.println("Second crash..."); - pb = ProcessTools.createJavaProcessBuilder( + pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-Xmx64M", "-XX:-CreateCoredumpOnCrash", "-XX:ErrorHandlerTest=2", // << now 2 diff --git a/test/hotspot/jtreg/runtime/ErrorHandling/ErrorFileRedirectTest.java b/test/hotspot/jtreg/runtime/ErrorHandling/ErrorFileRedirectTest.java index 3c32c6f8141..0e03317d640 100644 --- a/test/hotspot/jtreg/runtime/ErrorHandling/ErrorFileRedirectTest.java +++ b/test/hotspot/jtreg/runtime/ErrorHandling/ErrorFileRedirectTest.java @@ -48,7 +48,7 @@ public class ErrorFileRedirectTest { public static void do_test(boolean redirectStdout, boolean redirectStderr) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-Xmx64M", "-XX:-CreateCoredumpOnCrash", "-XX:ErrorHandlerTest=14", diff --git a/test/hotspot/jtreg/runtime/ErrorHandling/MachCodeFramesInErrorFile.java b/test/hotspot/jtreg/runtime/ErrorHandling/MachCodeFramesInErrorFile.java index 1e91c2529f5..57d18cf8c16 100644 --- a/test/hotspot/jtreg/runtime/ErrorHandling/MachCodeFramesInErrorFile.java +++ b/test/hotspot/jtreg/runtime/ErrorHandling/MachCodeFramesInErrorFile.java @@ -113,7 +113,7 @@ public static void main(String[] args) throws Exception { * expected to have a min number of MachCode sections. */ private static void run(boolean crashInJava) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-Xmx64m", "--add-exports=java.base/jdk.internal.misc=ALL-UNNAMED", "-XX:-CreateCoredumpOnCrash", "-Xcomp", diff --git a/test/hotspot/jtreg/runtime/ErrorHandling/NestedThreadsListHandleInErrorHandlingTest.java b/test/hotspot/jtreg/runtime/ErrorHandling/NestedThreadsListHandleInErrorHandlingTest.java index c897de4fa45..a9b804c3dce 100644 --- a/test/hotspot/jtreg/runtime/ErrorHandling/NestedThreadsListHandleInErrorHandlingTest.java +++ b/test/hotspot/jtreg/runtime/ErrorHandling/NestedThreadsListHandleInErrorHandlingTest.java @@ -53,7 +53,7 @@ public static void main(String[] args) throws Exception { // Need to disable ShowRegistersOnAssert: that flag causes registers to be shown, which calls os::print_location, // which - as part of its checks - will iterate the threads list under a ThreadListHandle, changing the max nesting // counters and confusing this test. - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:+UnlockDiagnosticVMOptions", "-XX:+EnableThreadSMRStatistics", "-Xmx100M", diff --git a/test/hotspot/jtreg/runtime/ErrorHandling/ProblematicFrameTest.java b/test/hotspot/jtreg/runtime/ErrorHandling/ProblematicFrameTest.java index dc54b09156c..e3d9c90408d 100644 --- a/test/hotspot/jtreg/runtime/ErrorHandling/ProblematicFrameTest.java +++ b/test/hotspot/jtreg/runtime/ErrorHandling/ProblematicFrameTest.java @@ -47,7 +47,7 @@ public static void main(String[] args) { } public static void main(String[] args) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-Xmx64m", "--add-exports=java.base/jdk.internal.misc=ALL-UNNAMED", "-XX:-CreateCoredumpOnCrash", Crasher.class.getName()); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldNotContain("Exception in thread"); diff --git a/test/hotspot/jtreg/runtime/ErrorHandling/SafeFetchInErrorHandlingTest.java b/test/hotspot/jtreg/runtime/ErrorHandling/SafeFetchInErrorHandlingTest.java index 241d41878fe..a3b5b9c6b6a 100644 --- a/test/hotspot/jtreg/runtime/ErrorHandling/SafeFetchInErrorHandlingTest.java +++ b/test/hotspot/jtreg/runtime/ErrorHandling/SafeFetchInErrorHandlingTest.java @@ -46,7 +46,7 @@ public class SafeFetchInErrorHandlingTest { public static void main(String[] args) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:+UnlockDiagnosticVMOptions", "-Xmx100M", "-XX:ErrorHandlerTest=14", diff --git a/test/hotspot/jtreg/runtime/ErrorHandling/SecondaryErrorTest.java b/test/hotspot/jtreg/runtime/ErrorHandling/SecondaryErrorTest.java index 8fa7fd5c6be..d91a5423167 100644 --- a/test/hotspot/jtreg/runtime/ErrorHandling/SecondaryErrorTest.java +++ b/test/hotspot/jtreg/runtime/ErrorHandling/SecondaryErrorTest.java @@ -49,7 +49,7 @@ public class SecondaryErrorTest { public static void main(String[] args) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:+UnlockDiagnosticVMOptions", "-Xmx100M", "-XX:-CreateCoredumpOnCrash", diff --git a/test/hotspot/jtreg/runtime/ErrorHandling/ShowRegistersOnAssertTest.java b/test/hotspot/jtreg/runtime/ErrorHandling/ShowRegistersOnAssertTest.java index 098818e6676..d771e55a464 100644 --- a/test/hotspot/jtreg/runtime/ErrorHandling/ShowRegistersOnAssertTest.java +++ b/test/hotspot/jtreg/runtime/ErrorHandling/ShowRegistersOnAssertTest.java @@ -55,7 +55,7 @@ private static void do_test(boolean do_assert, // true - assert, false - guarant { System.out.println("Testing " + (suppress_assert ? "suppressed" : "normal") + " " + (do_assert ? "assert" : "guarantee") + " with " + (show_registers_on_assert ? "-XX:+ShowRegistersOnAssert" : "-XX:-ShowRegistersOnAssert") + "..."); - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:+UnlockDiagnosticVMOptions", "-Xmx100M", "-XX:-CreateCoredumpOnCrash", "-XX:ErrorHandlerTest=" + (do_assert ? "1" : "2"), (suppress_assert ? "-XX:SuppressErrorAt=/vmError.cpp" : ""), diff --git a/test/hotspot/jtreg/runtime/ErrorHandling/TestCrashOnOutOfMemoryError.java b/test/hotspot/jtreg/runtime/ErrorHandling/TestCrashOnOutOfMemoryError.java index 2b33f4ffb53..c23adbd8955 100644 --- a/test/hotspot/jtreg/runtime/ErrorHandling/TestCrashOnOutOfMemoryError.java +++ b/test/hotspot/jtreg/runtime/ErrorHandling/TestCrashOnOutOfMemoryError.java @@ -53,7 +53,7 @@ public static void main(String[] args) throws Exception { } } // else this is the main test - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-XX:+CrashOnOutOfMemoryError", + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:+CrashOnOutOfMemoryError", "-XX:-CreateCoredumpOnCrash", "-Xmx128m", TestCrashOnOutOfMemoryError.class.getName(),"throwOOME"); OutputAnalyzer output = new OutputAnalyzer(pb.start()); int exitValue = output.getExitValue(); diff --git a/test/hotspot/jtreg/runtime/ErrorHandling/TestExitOnOutOfMemoryError.java b/test/hotspot/jtreg/runtime/ErrorHandling/TestExitOnOutOfMemoryError.java index e56ed4a1b03..145dd4aadc9 100644 --- a/test/hotspot/jtreg/runtime/ErrorHandling/TestExitOnOutOfMemoryError.java +++ b/test/hotspot/jtreg/runtime/ErrorHandling/TestExitOnOutOfMemoryError.java @@ -49,7 +49,7 @@ public static void main(String[] args) throws Exception { } // else this is the main test - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-XX:+ExitOnOutOfMemoryError", + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:+ExitOnOutOfMemoryError", "-Xmx128m", TestExitOnOutOfMemoryError.class.getName(), "throwOOME"); OutputAnalyzer output = new OutputAnalyzer(pb.start()); diff --git a/test/hotspot/jtreg/runtime/ErrorHandling/TestGZippedHeapDumpOnOutOfMemoryError.java b/test/hotspot/jtreg/runtime/ErrorHandling/TestGZippedHeapDumpOnOutOfMemoryError.java index a2a0154f0b3..5f4c1dd9b1a 100644 --- a/test/hotspot/jtreg/runtime/ErrorHandling/TestGZippedHeapDumpOnOutOfMemoryError.java +++ b/test/hotspot/jtreg/runtime/ErrorHandling/TestGZippedHeapDumpOnOutOfMemoryError.java @@ -63,7 +63,7 @@ public static void main(String[] args) throws Exception { } static void test(int level) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:+HeapDumpOnOutOfMemoryError", "-XX:HeapDumpGzipLevel=" + level, "-Xmx128M", diff --git a/test/hotspot/jtreg/runtime/ErrorHandling/TestHeapDumpOnOutOfMemoryError.java b/test/hotspot/jtreg/runtime/ErrorHandling/TestHeapDumpOnOutOfMemoryError.java index 9324adbb2e0..fb098bd27fe 100644 --- a/test/hotspot/jtreg/runtime/ErrorHandling/TestHeapDumpOnOutOfMemoryError.java +++ b/test/hotspot/jtreg/runtime/ErrorHandling/TestHeapDumpOnOutOfMemoryError.java @@ -75,7 +75,7 @@ public static void main(String[] args) throws Exception { static void test(String type) throws Exception { String heapdumpFilename = type + ".hprof"; - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-XX:+HeapDumpOnOutOfMemoryError", + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:+HeapDumpOnOutOfMemoryError", "-XX:HeapDumpPath=" + heapdumpFilename, // Note: When trying to provoke a metaspace OOM we may generate a lot of classes. In debug VMs this // can cause considerable wait times since: diff --git a/test/hotspot/jtreg/runtime/ErrorHandling/TestHeapDumpPath.java b/test/hotspot/jtreg/runtime/ErrorHandling/TestHeapDumpPath.java index 0cc6dbc765f..167b94e1fe1 100644 --- a/test/hotspot/jtreg/runtime/ErrorHandling/TestHeapDumpPath.java +++ b/test/hotspot/jtreg/runtime/ErrorHandling/TestHeapDumpPath.java @@ -54,7 +54,7 @@ static void testHeapDumpPath() throws Exception { String heapdumpPath = "dumps"; File dumpDirectory = new File(heapdumpPath); dumpDirectory.mkdir(); - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-XX:+HeapDumpOnOutOfMemoryError", + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:+HeapDumpOnOutOfMemoryError", "-Xmx64m", "-XX:HeapDumpPath=" + heapdumpPath, TestHeapDumpPath.class.getName(), "OOME"); OutputAnalyzer output = new OutputAnalyzer(pb.start()); diff --git a/test/hotspot/jtreg/runtime/ErrorHandling/TestOnError.java b/test/hotspot/jtreg/runtime/ErrorHandling/TestOnError.java index 00475f8bdd7..53410c5379c 100644 --- a/test/hotspot/jtreg/runtime/ErrorHandling/TestOnError.java +++ b/test/hotspot/jtreg/runtime/ErrorHandling/TestOnError.java @@ -41,7 +41,7 @@ public class TestOnError { public static void main(String[] args) throws Exception { String msg = "Test Succeeded"; - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:-CreateCoredumpOnCrash", "-XX:ErrorHandlerTest=14", // trigger potential SEGV "-XX:OnError=echo " + msg, diff --git a/test/hotspot/jtreg/runtime/ErrorHandling/TestOnOutOfMemoryError.java b/test/hotspot/jtreg/runtime/ErrorHandling/TestOnOutOfMemoryError.java index fe3c5c34f80..f498caa2bff 100644 --- a/test/hotspot/jtreg/runtime/ErrorHandling/TestOnOutOfMemoryError.java +++ b/test/hotspot/jtreg/runtime/ErrorHandling/TestOnOutOfMemoryError.java @@ -47,12 +47,12 @@ public static void main(String[] args) throws Exception { // else this is the main test String msg1 = "Test1 Succeeded"; String msg2 = "Test2 Succeeded"; - ProcessBuilder pb_single = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb_single = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:OnOutOfMemoryError=echo " + msg1, TestOnOutOfMemoryError.class.getName(), "throwOOME"); - ProcessBuilder pb_multiple = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb_multiple = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:OnOutOfMemoryError=echo " + msg1, "-XX:OnOutOfMemoryError=echo " + msg2, TestOnOutOfMemoryError.class.getName(), diff --git a/test/hotspot/jtreg/runtime/ErrorHandling/ThreadsListHandleInErrorHandlingTest.java b/test/hotspot/jtreg/runtime/ErrorHandling/ThreadsListHandleInErrorHandlingTest.java index 968337984e1..7a60fd64da0 100644 --- a/test/hotspot/jtreg/runtime/ErrorHandling/ThreadsListHandleInErrorHandlingTest.java +++ b/test/hotspot/jtreg/runtime/ErrorHandling/ThreadsListHandleInErrorHandlingTest.java @@ -53,7 +53,7 @@ public static void main(String[] args) throws Exception { // Need to disable ShowRegistersOnAssert: that flag causes registers to be shown, which calls os::print_location, // which - as part of its checks - will iterate the threads list under a ThreadListHandle, changing the max nesting // counters and confusing this test. - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:+UnlockDiagnosticVMOptions", "-XX:+EnableThreadSMRStatistics", "-Xmx100M", diff --git a/test/hotspot/jtreg/runtime/ErrorHandling/TimeoutInErrorHandlingTest.java b/test/hotspot/jtreg/runtime/ErrorHandling/TimeoutInErrorHandlingTest.java index 5111a229dbc..36107f01de9 100644 --- a/test/hotspot/jtreg/runtime/ErrorHandling/TimeoutInErrorHandlingTest.java +++ b/test/hotspot/jtreg/runtime/ErrorHandling/TimeoutInErrorHandlingTest.java @@ -107,7 +107,7 @@ public static void main(String[] args) throws Exception { arguments.add("-XX:OnError=echo hi"); } arguments.add("-version"); - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(arguments); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(arguments); OutputAnalyzer output_detail = new OutputAnalyzer(pb.start()); diff --git a/test/hotspot/jtreg/runtime/ErrorHandling/VeryEarlyAssertTest.java b/test/hotspot/jtreg/runtime/ErrorHandling/VeryEarlyAssertTest.java index 4395775c872..c2225a59193 100644 --- a/test/hotspot/jtreg/runtime/ErrorHandling/VeryEarlyAssertTest.java +++ b/test/hotspot/jtreg/runtime/ErrorHandling/VeryEarlyAssertTest.java @@ -50,7 +50,7 @@ public class VeryEarlyAssertTest { public static void main(String[] args) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-version"); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-version"); Map env = pb.environment(); env.put("HOTSPOT_FATAL_ERROR_DURING_DYNAMIC_INITIALIZATION", "1"); diff --git a/test/hotspot/jtreg/runtime/GenerateOopMap/TestGenerateOopMapCrash.java b/test/hotspot/jtreg/runtime/GenerateOopMap/TestGenerateOopMapCrash.java index b556e0d0211..559c6145cb6 100644 --- a/test/hotspot/jtreg/runtime/GenerateOopMap/TestGenerateOopMapCrash.java +++ b/test/hotspot/jtreg/runtime/GenerateOopMap/TestGenerateOopMapCrash.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2023, Oracle and/or its affiliates. All rights reserved. * 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,7 +40,7 @@ public class TestGenerateOopMapCrash { public static void main(String args[]) throws Exception { if (args.length == 0) { // Spawn new VM instance to execute test - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:-TieredCompilation", "-XX:CompileCommand=dontinline,if_icmpleIsLastOpcode.m*", "-Xmx64m", diff --git a/test/hotspot/jtreg/runtime/InvocationTests/invocationC1Tests.java b/test/hotspot/jtreg/runtime/InvocationTests/invocationC1Tests.java index a5fe4b2a148..57df6306276 100644 --- a/test/hotspot/jtreg/runtime/InvocationTests/invocationC1Tests.java +++ b/test/hotspot/jtreg/runtime/InvocationTests/invocationC1Tests.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 2023, Oracle and/or its affiliates. All rights reserved. * 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 class invocationC1Tests { public static void runTest(String whichTests, String classFileVersion) throws Throwable { System.out.println("\nC1 invocation tests, Tests: " + whichTests + ", class file version: " + classFileVersion); - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-Xmx128M", + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-Xmx128M", "-Xcomp", "-XX:TieredStopAtLevel=1", "--add-exports", "java.base/jdk.internal.org.objectweb.asm=ALL-UNNAMED", whichTests, "--classfile_version=" + classFileVersion); diff --git a/test/hotspot/jtreg/runtime/InvocationTests/invocationOldCHATests.java b/test/hotspot/jtreg/runtime/InvocationTests/invocationOldCHATests.java index 2d4c2a38b21..415cd105ee9 100644 --- a/test/hotspot/jtreg/runtime/InvocationTests/invocationOldCHATests.java +++ b/test/hotspot/jtreg/runtime/InvocationTests/invocationOldCHATests.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -67,7 +67,7 @@ public class invocationOldCHATests { public static void runTest(String whichTests, String classFileVersion) throws Throwable { System.out.println("\nOld CHA invocation tests, Tests: " + whichTests + ", class file version: " + classFileVersion); - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-Xmx128M", + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-Xmx128M", "-Xcomp", "-XX:+UnlockDiagnosticVMOptions", "-XX:-UseVtableBasedCHA", "--add-exports", "java.base/jdk.internal.org.objectweb.asm=ALL-UNNAMED", whichTests, "--classfile_version=" + classFileVersion); diff --git a/test/hotspot/jtreg/runtime/InvocationTests/invokeinterfaceTests.java b/test/hotspot/jtreg/runtime/InvocationTests/invokeinterfaceTests.java index 9d8a164637e..9b72899d138 100644 --- a/test/hotspot/jtreg/runtime/InvocationTests/invokeinterfaceTests.java +++ b/test/hotspot/jtreg/runtime/InvocationTests/invokeinterfaceTests.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -73,7 +73,7 @@ public class invokeinterfaceTests { public static void runTest(String classFileVersion, String option) throws Throwable { System.out.println("\ninvokeinterface invocation tests, option: " + option + ", class file version: " + classFileVersion); - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-Xmx128M", option, + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-Xmx128M", option, "--add-exports", "java.base/jdk.internal.org.objectweb.asm=ALL-UNNAMED", "invokeinterface.Generator", "--classfile_version=" + classFileVersion); OutputAnalyzer output = new OutputAnalyzer(pb.start()); diff --git a/test/hotspot/jtreg/runtime/InvocationTests/invokespecialTests.java b/test/hotspot/jtreg/runtime/InvocationTests/invokespecialTests.java index 564f83d822e..817e5da9616 100644 --- a/test/hotspot/jtreg/runtime/InvocationTests/invokespecialTests.java +++ b/test/hotspot/jtreg/runtime/InvocationTests/invokespecialTests.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 2023, Oracle and/or its affiliates. All rights reserved. * 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 class invokespecialTests { public static void runTest(String classFileVersion, String option) throws Throwable { System.out.println("\ninvokespecial invocation tests, option: " + option + ", class file version: " + classFileVersion); - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-Xmx128M", option, + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-Xmx128M", option, "--add-exports", "java.base/jdk.internal.org.objectweb.asm=ALL-UNNAMED", "invokespecial.Generator", "--classfile_version=" + classFileVersion); OutputAnalyzer output = new OutputAnalyzer(pb.start()); diff --git a/test/hotspot/jtreg/runtime/InvocationTests/invokevirtualTests.java b/test/hotspot/jtreg/runtime/InvocationTests/invokevirtualTests.java index 9cc19b6081c..5f998a6029e 100644 --- a/test/hotspot/jtreg/runtime/InvocationTests/invokevirtualTests.java +++ b/test/hotspot/jtreg/runtime/InvocationTests/invokevirtualTests.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 2023, Oracle and/or its affiliates. All rights reserved. * 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 class invokevirtualTests { public static void runTest(String classFileVersion, String option) throws Throwable { System.out.println("\ninvokevirtual invocation tests, option: " + option + ", class file version: " + classFileVersion); - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-Xmx128M", option, + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-Xmx128M", option, "--add-exports", "java.base/jdk.internal.org.objectweb.asm=ALL-UNNAMED", "invokevirtual.Generator", "--classfile_version=" + classFileVersion); OutputAnalyzer output = new OutputAnalyzer(pb.start()); diff --git a/test/hotspot/jtreg/runtime/LoadClass/LoadClassNegative.java b/test/hotspot/jtreg/runtime/LoadClass/LoadClassNegative.java index c9d8c6f9453..94c2bde6e76 100644 --- a/test/hotspot/jtreg/runtime/LoadClass/LoadClassNegative.java +++ b/test/hotspot/jtreg/runtime/LoadClass/LoadClassNegative.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2023, Oracle and/or its affiliates. All rights reserved. * 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,6 +25,7 @@ * @test * @bug 8020675 * @summary make sure there is no fatal error if a class is loaded from an invalid jar file which is in the bootclasspath + * @requires vm.flagless * @library /test/lib * @modules java.base/jdk.internal.misc * java.management @@ -41,7 +42,7 @@ public class LoadClassNegative { public static void main(String args[]) throws Exception { String bootCP = "-Xbootclasspath/a:" + System.getProperty("test.src") + File.separator + "dummy.jar"; - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( bootCP, "TestForName"); diff --git a/test/hotspot/jtreg/runtime/LoadClass/LongBCP.java b/test/hotspot/jtreg/runtime/LoadClass/LongBCP.java index 51f397c6b40..aa4c559ff64 100644 --- a/test/hotspot/jtreg/runtime/LoadClass/LongBCP.java +++ b/test/hotspot/jtreg/runtime/LoadClass/LongBCP.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,6 +26,7 @@ * @summary JVM should be able to handle full path (directory path plus * class name) or directory path longer than MAX_PATH specified * in -Xbootclasspath/a on windows. + * @requires vm.flagless * @library /test/lib * @modules java.base/jdk.internal.misc * java.management @@ -69,7 +70,7 @@ public static void main(String args[]) throws Exception { CompilerUtils.compile(sourceDir, destDir); String bootCP = "-Xbootclasspath/a:" + destDir.toString(); - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( bootCP, "Hello"); OutputAnalyzer output = new OutputAnalyzer(pb.start()); @@ -81,7 +82,7 @@ public static void main(String args[]) throws Exception { CompilerUtils.compile(sourceDir, destDir); bootCP = "-Xbootclasspath/a:" + destDir.toString(); - pb = ProcessTools.createJavaProcessBuilder( + pb = ProcessTools.createLimitedTestJavaProcessBuilder( bootCP, "Hello"); output = new OutputAnalyzer(pb.start()); @@ -96,7 +97,7 @@ public static void main(String args[]) throws Exception { // run with long bootclasspath to hello.jar bootCP = "-Xbootclasspath/a:" + helloJar; - pb = ProcessTools.createJavaProcessBuilder( + pb = ProcessTools.createLimitedTestJavaProcessBuilder( bootCP, "Hello"); output = new OutputAnalyzer(pb.start()); @@ -121,7 +122,7 @@ public static void main(String args[]) throws Exception { CompilerUtils.compile(sourceDir, destDir); bootCP = "-Xbootclasspath/a:" + destDir.toString(); - pb = ProcessTools.createJavaProcessBuilder( + pb = ProcessTools.createLimitedTestJavaProcessBuilder( bootCP, "Hello"); output = new OutputAnalyzer(pb.start()); @@ -138,7 +139,7 @@ public static void main(String args[]) throws Exception { Path jarPath = jarDir.resolve("hello.jar"); Files.copy(Paths.get(helloJar), jarPath); bootCP = "-Xbootclasspath/a:" + jarPath.toString(); - pb = ProcessTools.createJavaProcessBuilder(bootCP, "Hello"); + pb = ProcessTools.createLimitedTestJavaProcessBuilder(bootCP, "Hello"); output = new OutputAnalyzer(pb.start()); output.shouldContain("Hello World") @@ -150,7 +151,7 @@ public static void main(String args[]) throws Exception { CompilerUtils.compile(sourceDir, destDir); bootCP = "-Xbootclasspath/a:" + destDir.toString(); - pb = ProcessTools.createJavaProcessBuilder( + pb = ProcessTools.createLimitedTestJavaProcessBuilder( bootCP, "Hello"); output = new OutputAnalyzer(pb.start()); diff --git a/test/hotspot/jtreg/runtime/LoadClass/TestResize.java b/test/hotspot/jtreg/runtime/LoadClass/TestResize.java index 609f3ab890d..0c1e33bce97 100644 --- a/test/hotspot/jtreg/runtime/LoadClass/TestResize.java +++ b/test/hotspot/jtreg/runtime/LoadClass/TestResize.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,6 +26,7 @@ * @bug 8184765 * @summary make sure the SystemDictionary gets resized when load factor is too high * @requires vm.debug + * @requires vm.flagless * @library /test/lib * @modules java.base/jdk.internal.misc * java.management @@ -116,10 +117,10 @@ public static void main(String[] args) throws Exception { // that will allow us to calculate the table's load factor. // -Xlog:safepoint+cleanup will print out cleanup details at safepoint // that will allow us to detect if the system dictionary resized. - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-XX:+PrintSystemDictionaryAtExit", - "-Xlog:safepoint+cleanup", - "TriggerResize", - "50000"); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:+PrintSystemDictionaryAtExit", + "-Xlog:safepoint+cleanup", + "TriggerResize", + "50000"); analyzeOutputOn(pb); } } diff --git a/test/hotspot/jtreg/runtime/LocalLong/LocalLongTest.java b/test/hotspot/jtreg/runtime/LocalLong/LocalLongTest.java index 2c1a0709b2a..8a03e08a531 100644 --- a/test/hotspot/jtreg/runtime/LocalLong/LocalLongTest.java +++ b/test/hotspot/jtreg/runtime/LocalLong/LocalLongTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2023, Oracle and/or its affiliates. All rights reserved. * 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,12 +37,12 @@ public class LocalLongTest { public static void main(String... args) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-Xint", - "--add-opens", - "java.base/java.lang=ALL-UNNAMED", - "--add-opens", - "java.base/java.lang.invoke=ALL-UNNAMED", - "LocalLongHelper"); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-Xint", + "--add-opens", + "java.base/java.lang=ALL-UNNAMED", + "--add-opens", + "java.base/java.lang.invoke=ALL-UNNAMED", + "LocalLongHelper"); OutputAnalyzer o = new OutputAnalyzer(pb.start()); o.shouldHaveExitValue(0); }; diff --git a/test/hotspot/jtreg/runtime/LocalVariableTable/TestLVT.java b/test/hotspot/jtreg/runtime/LocalVariableTable/TestLVT.java index b1ed991b931..c84fef5c126 100644 --- a/test/hotspot/jtreg/runtime/LocalVariableTable/TestLVT.java +++ b/test/hotspot/jtreg/runtime/LocalVariableTable/TestLVT.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2023, Oracle and/or its affiliates. All rights reserved. * 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,17 +41,17 @@ public class TestLVT { public static void main(String[] args) throws Exception { test(); // Test good LVT in this test - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("DuplicateLVT"); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("DuplicateLVT"); new OutputAnalyzer(pb.start()) .shouldContain("Duplicated LocalVariableTable attribute entry for 'by' in class file DuplicateLVT") .shouldHaveExitValue(1); - pb = ProcessTools.createJavaProcessBuilder("DuplicateLVTT"); + pb = ProcessTools.createLimitedTestJavaProcessBuilder("DuplicateLVTT"); new OutputAnalyzer(pb.start()) .shouldContain("Duplicated LocalVariableTypeTable attribute entry for 'list' in class file DuplicateLVTT") .shouldHaveExitValue(1); - pb = ProcessTools.createJavaProcessBuilder("NotFoundLVTT"); + pb = ProcessTools.createLimitedTestJavaProcessBuilder("NotFoundLVTT"); new OutputAnalyzer(pb.start()) .shouldContain("LVTT entry for 'list' in class file NotFoundLVTT does not match any LVT entry") .shouldHaveExitValue(1); diff --git a/test/hotspot/jtreg/runtime/MemberName/MemberNameLeak.java b/test/hotspot/jtreg/runtime/MemberName/MemberNameLeak.java index ee1b10903a9..d2d000f7c7d 100644 --- a/test/hotspot/jtreg/runtime/MemberName/MemberNameLeak.java +++ b/test/hotspot/jtreg/runtime/MemberName/MemberNameLeak.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2023, Oracle and/or its affiliates. All rights reserved. * 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,7 +126,7 @@ public static void test(GC gc, boolean doConcurrent) throws Throwable { Path gcLogPath = createGcLogPath("gc." + gc + "." + doConcurrent); System.err.println("test(" + gc + ", " + doConcurrent + ")" + " " + dateFormat.format(new Date())); // Run this Leak class with logging - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-Xlog:membername+table=trace,gc+verify=debug,gc:" + gcLogPath + ":time,utctime,uptime,pid,level,tags", "-XX:+UnlockExperimentalVMOptions", "-XX:+UnlockDiagnosticVMOptions", diff --git a/test/hotspot/jtreg/runtime/Metaspace/MaxMetaspaceSizeEnvVarTest.java b/test/hotspot/jtreg/runtime/Metaspace/MaxMetaspaceSizeEnvVarTest.java index eb8698295f9..867257cba12 100644 --- a/test/hotspot/jtreg/runtime/Metaspace/MaxMetaspaceSizeEnvVarTest.java +++ b/test/hotspot/jtreg/runtime/Metaspace/MaxMetaspaceSizeEnvVarTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2021, 2023, Oracle and/or its affiliates. All rights reserved. * 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,7 +81,7 @@ public static void main(String... args) throws Exception { test++; report("Test " + test + ": normal command-line flag"); - pb = ProcessTools.createJavaProcessBuilder(flag, main, max); + pb = ProcessTools.createLimitedTestJavaProcessBuilder(flag, main, max); output = new OutputAnalyzer(pb.start()); output.shouldHaveExitValue(0); output.reportDiagnosticSummary(); @@ -96,7 +96,7 @@ public static void main(String... args) throws Exception { for (String envVar : envVars) { report("Test " + test + ": " + envVar + " env-var"); - pb = ProcessTools.createJavaProcessBuilder(main, max); + pb = ProcessTools.createLimitedTestJavaProcessBuilder(main, max); pb.environment().put(envVar, flag); output = new OutputAnalyzer(pb.start()); output.shouldHaveExitValue(0); @@ -112,7 +112,7 @@ public static void main(String... args) throws Exception { PrintWriter pw = new PrintWriter(rcFile); pw.println(flagRaw); pw.close(); - pb = ProcessTools.createJavaProcessBuilder(rcFileFlag, main, max); + pb = ProcessTools.createLimitedTestJavaProcessBuilder(rcFileFlag, main, max); output = new OutputAnalyzer(pb.start()); output.shouldHaveExitValue(0); output.reportDiagnosticSummary(); diff --git a/test/hotspot/jtreg/runtime/Metaspace/MaxMetaspaceSizeTest.java b/test/hotspot/jtreg/runtime/Metaspace/MaxMetaspaceSizeTest.java index 32aaa34db50..76c24eb1d25 100644 --- a/test/hotspot/jtreg/runtime/Metaspace/MaxMetaspaceSizeTest.java +++ b/test/hotspot/jtreg/runtime/Metaspace/MaxMetaspaceSizeTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -35,7 +35,7 @@ public class MaxMetaspaceSizeTest { public static void main(String... args) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-Xmx1g", "-XX:MaxMetaspaceSize=4K", "-XX:+UseCompressedClassPointers", diff --git a/test/hotspot/jtreg/runtime/MinimalVM/CDS.java b/test/hotspot/jtreg/runtime/MinimalVM/CDS.java index e166d961fac..84e0f47e9b8 100644 --- a/test/hotspot/jtreg/runtime/MinimalVM/CDS.java +++ b/test/hotspot/jtreg/runtime/MinimalVM/CDS.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -24,6 +24,7 @@ /* * @test * @requires vm.flavor == "minimal" + * @requires vm.flagless * @modules java.base/jdk.internal.misc * @library /test/lib * @run driver CDS @@ -37,17 +38,17 @@ public class CDS { public static void main(String args[]) throws Exception { ProcessBuilder pb; - pb = ProcessTools.createJavaProcessBuilder("-minimal", "-Xshare:dump"); + pb = ProcessTools.createLimitedTestJavaProcessBuilder("-minimal", "-Xshare:dump"); new OutputAnalyzer(pb.start()) .shouldContain("Shared spaces are not supported in this VM") .shouldHaveExitValue(1); - pb = ProcessTools.createJavaProcessBuilder("-minimal", "-Xshare:on"); + pb = ProcessTools.createLimitedTestJavaProcessBuilder("-minimal", "-Xshare:on"); new OutputAnalyzer(pb.start()) .shouldContain("Shared spaces are not supported in this VM") .shouldHaveExitValue(1); - pb = ProcessTools.createJavaProcessBuilder("-minimal", "-Xshare:auto", "-version"); + pb = ProcessTools.createLimitedTestJavaProcessBuilder("-minimal", "-Xshare:auto", "-version"); new OutputAnalyzer(pb.start()) .shouldContain("Shared spaces are not supported in this VM") .shouldHaveExitValue(0); diff --git a/test/hotspot/jtreg/runtime/MinimalVM/CheckJNI.java b/test/hotspot/jtreg/runtime/MinimalVM/CheckJNI.java index 14219653574..5a1ee499c60 100644 --- a/test/hotspot/jtreg/runtime/MinimalVM/CheckJNI.java +++ b/test/hotspot/jtreg/runtime/MinimalVM/CheckJNI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -24,6 +24,7 @@ /* * @test * @requires vm.flavor == "minimal" + * @requires vm.flagless * @modules java.base/jdk.internal.misc * @library /test/lib * @run driver CheckJNI @@ -35,7 +36,7 @@ public class CheckJNI { public static void main(String args[]) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-minimal", "-Xcheck:jni", "-version"); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-minimal", "-Xcheck:jni", "-version"); new OutputAnalyzer(pb.start()) .shouldContain("Minimal VM warning: JNI CHECKING is not supported in this VM") .shouldHaveExitValue(0); diff --git a/test/hotspot/jtreg/runtime/MinimalVM/Instrumentation.java b/test/hotspot/jtreg/runtime/MinimalVM/Instrumentation.java index c5c56cead35..c2b30fdd6a2 100644 --- a/test/hotspot/jtreg/runtime/MinimalVM/Instrumentation.java +++ b/test/hotspot/jtreg/runtime/MinimalVM/Instrumentation.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2023, Oracle and/or its affiliates. All rights reserved. * 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,6 +25,7 @@ * @test * @library /test/lib * @requires vm.flavor == "minimal" + * @requires vm.flagless * @modules java.base/jdk.internal.misc * java.instrument * @run driver Instrumentation @@ -36,7 +37,7 @@ public class Instrumentation { public static void main(String[] args) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-minimal", "-javaagent:redefineagent.jar", "-version"); new OutputAnalyzer(pb.start()) .shouldContain("Instrumentation agents are not supported in this VM") diff --git a/test/hotspot/jtreg/runtime/MinimalVM/JMX.java b/test/hotspot/jtreg/runtime/MinimalVM/JMX.java index 5a9dc20abf0..53ef41902ed 100644 --- a/test/hotspot/jtreg/runtime/MinimalVM/JMX.java +++ b/test/hotspot/jtreg/runtime/MinimalVM/JMX.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -24,6 +24,7 @@ /* * @test * @requires vm.flavor == "minimal" + * @requires vm.flagless * @library /test/lib * @run main/othervm JMX */ @@ -37,12 +38,12 @@ public class JMX { public static void main(String args[]) throws Exception { ProcessBuilder pb; - pb = ProcessTools.createJavaProcessBuilder("-minimal", "-XX:+ManagementServer", "-version"); + pb = ProcessTools.createLimitedTestJavaProcessBuilder("-minimal", "-XX:+ManagementServer", "-version"); new OutputAnalyzer(pb.start()) .shouldContain("ManagementServer is not supported in this VM.") .shouldHaveExitValue(1); - pb = ProcessTools.createJavaProcessBuilder("-minimal", "-Dcom.sun.management ", "-version"); + pb = ProcessTools.createLimitedTestJavaProcessBuilder("-minimal", "-Dcom.sun.management ", "-version"); new OutputAnalyzer(pb.start()) .shouldContain("-Dcom.sun.management is not supported in this VM.") .shouldHaveExitValue(1); diff --git a/test/hotspot/jtreg/runtime/MinimalVM/JVMTI.java b/test/hotspot/jtreg/runtime/MinimalVM/JVMTI.java index ef3f481d15d..1914aafcfd6 100644 --- a/test/hotspot/jtreg/runtime/MinimalVM/JVMTI.java +++ b/test/hotspot/jtreg/runtime/MinimalVM/JVMTI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -24,6 +24,7 @@ /* * @test * @requires vm.flavor == "minimal" + * @requires vm.flagless * @modules java.base/jdk.internal.misc * @library /test/lib * @run driver JVMTI @@ -35,7 +36,7 @@ public class JVMTI { public static void main(String args[]) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-minimal", "-agentlib:jdwp=server=y,transport=dt_socket,address=5000,suspend=n", "-version"); diff --git a/test/hotspot/jtreg/runtime/MinimalVM/NMT.java b/test/hotspot/jtreg/runtime/MinimalVM/NMT.java index 815fa6d0195..958ccc1758d 100644 --- a/test/hotspot/jtreg/runtime/MinimalVM/NMT.java +++ b/test/hotspot/jtreg/runtime/MinimalVM/NMT.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -24,6 +24,7 @@ /* * @test * @requires vm.flavor == "minimal" + * @requires vm.flagless * @modules java.base/jdk.internal.misc * @library /test/lib * @run driver NMT @@ -37,17 +38,17 @@ public class NMT { public static void main(String args[]) throws Exception { ProcessBuilder pb; - pb = ProcessTools.createJavaProcessBuilder("-minimal", "-XX:NativeMemoryTracking=detail", "-version"); + pb = ProcessTools.createLimitedTestJavaProcessBuilder("-minimal", "-XX:NativeMemoryTracking=detail", "-version"); new OutputAnalyzer(pb.start()) .shouldContain("Native Memory Tracking is not supported in this VM") .shouldHaveExitValue(1); - pb = ProcessTools.createJavaProcessBuilder("-minimal", "-XX:NativeMemoryTracking=summary", "-version"); + pb = ProcessTools.createLimitedTestJavaProcessBuilder("-minimal", "-XX:NativeMemoryTracking=summary", "-version"); new OutputAnalyzer(pb.start()) .shouldContain("Native Memory Tracking is not supported in this VM") .shouldHaveExitValue(1); - pb = ProcessTools.createJavaProcessBuilder("-minimal", "-XX:NativeMemoryTracking=off", "-version"); + pb = ProcessTools.createLimitedTestJavaProcessBuilder("-minimal", "-XX:NativeMemoryTracking=off", "-version"); new OutputAnalyzer(pb.start()) .shouldContain("Native Memory Tracking is not supported in this VM") .shouldHaveExitValue(1); diff --git a/test/hotspot/jtreg/runtime/Monitor/DeflationIntervalsTest.java b/test/hotspot/jtreg/runtime/Monitor/DeflationIntervalsTest.java index 8663989fd9e..eb394235196 100644 --- a/test/hotspot/jtreg/runtime/Monitor/DeflationIntervalsTest.java +++ b/test/hotspot/jtreg/runtime/Monitor/DeflationIntervalsTest.java @@ -272,7 +272,7 @@ public static void test(Disabled disabled, Guaranteed guaranteed, Threshold thre opts.addAll(Arrays.asList(args)); opts.add("DeflationIntervalsTest$Test"); - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(opts); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(opts); OutputAnalyzer oa = new OutputAnalyzer(pb.start()); oa.shouldHaveExitValue(0); diff --git a/test/hotspot/jtreg/runtime/Monitor/MonitorUnlinkBatchTest.java b/test/hotspot/jtreg/runtime/Monitor/MonitorUnlinkBatchTest.java index 03cca277a28..e7bbc33e27d 100644 --- a/test/hotspot/jtreg/runtime/Monitor/MonitorUnlinkBatchTest.java +++ b/test/hotspot/jtreg/runtime/Monitor/MonitorUnlinkBatchTest.java @@ -165,7 +165,7 @@ public static void test(String msg, String... args) throws Exception { opts.addAll(Arrays.asList(args)); opts.add("MonitorUnlinkBatchTest$Test"); - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(opts); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(opts); OutputAnalyzer oa = new OutputAnalyzer(pb.start()); if (msg.isEmpty()) { oa.shouldHaveExitValue(0); diff --git a/test/hotspot/jtreg/runtime/Monitor/MonitorUsedDeflationThresholdTest.java b/test/hotspot/jtreg/runtime/Monitor/MonitorUsedDeflationThresholdTest.java index 5dd01e4262b..41b86e0e19e 100644 --- a/test/hotspot/jtreg/runtime/Monitor/MonitorUsedDeflationThresholdTest.java +++ b/test/hotspot/jtreg/runtime/Monitor/MonitorUsedDeflationThresholdTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2021, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -73,7 +73,7 @@ public static void usage() { public static void main(String[] args) throws Exception { if (args.length == 0) { // Without args we invoke the test in a java sub-process: - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( // Test doesn't need much Java heap: "-Xmx100M", // AvgMonitorsPerThreadEstimate == 1 means we'll start with diff --git a/test/hotspot/jtreg/runtime/Monitor/SyncOnValueBasedClassTest.java b/test/hotspot/jtreg/runtime/Monitor/SyncOnValueBasedClassTest.java index 6caff48bd8f..5f541a8ba7b 100644 --- a/test/hotspot/jtreg/runtime/Monitor/SyncOnValueBasedClassTest.java +++ b/test/hotspot/jtreg/runtime/Monitor/SyncOnValueBasedClassTest.java @@ -87,14 +87,14 @@ private static void generateTests() { public static void main(String[] args) throws Exception { generateTests(); for (int i = 0; i < fatalTests.length; i++) { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(fatalTests[i]); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(fatalTests[i]); OutputAnalyzer output = ProcessTools.executeProcess(pb); output.shouldContain("fatal error: Synchronizing on object"); output.shouldNotContain("synchronization on value based class did not fail"); output.shouldNotHaveExitValue(0); } for (int i = 0; i < logTests.length; i++) { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(logTests[i]); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(logTests[i]); OutputAnalyzer output = ProcessTools.executeProcess(pb); output.shouldHaveExitValue(0); checkOutput(output); diff --git a/test/hotspot/jtreg/runtime/NMT/CheckForProperDetailStackTrace.java b/test/hotspot/jtreg/runtime/NMT/CheckForProperDetailStackTrace.java index 1606f7fea56..3799d283639 100644 --- a/test/hotspot/jtreg/runtime/NMT/CheckForProperDetailStackTrace.java +++ b/test/hotspot/jtreg/runtime/NMT/CheckForProperDetailStackTrace.java @@ -103,7 +103,7 @@ public static void main(String args[]) throws Exception { // If modules in the system image have been archived in CDS, they will not be // created again at run time. Explicitly use an external module to make sure // we have a runtime-defined ModuleEntry - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:+UnlockDiagnosticVMOptions", "-XX:NativeMemoryTracking=detail", "-XX:+PrintNMTStatistics", diff --git a/test/hotspot/jtreg/runtime/NMT/CommandLineDetail.java b/test/hotspot/jtreg/runtime/NMT/CommandLineDetail.java index 94bd1de830a..57f2302db30 100644 --- a/test/hotspot/jtreg/runtime/NMT/CommandLineDetail.java +++ b/test/hotspot/jtreg/runtime/NMT/CommandLineDetail.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2023, Oracle and/or its affiliates. All rights reserved. * 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,7 +37,7 @@ public class CommandLineDetail { public static void main(String args[]) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder( "-XX:NativeMemoryTracking=detail", "-version"); OutputAnalyzer output = new OutputAnalyzer(pb.start()); diff --git a/test/hotspot/jtreg/runtime/NMT/CommandLineEmptyArgument.java b/test/hotspot/jtreg/runtime/NMT/CommandLineEmptyArgument.java index e2d627ffded..2a0620b7bad 100644 --- a/test/hotspot/jtreg/runtime/NMT/CommandLineEmptyArgument.java +++ b/test/hotspot/jtreg/runtime/NMT/CommandLineEmptyArgument.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -24,6 +24,7 @@ /* * @test * @summary Empty argument to NMT should result in an informative error message + * @requires vm.flagless * @library /test/lib * @modules java.base/jdk.internal.misc * java.management @@ -36,7 +37,7 @@ public class CommandLineEmptyArgument { public static void main(String args[]) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-XX:NativeMemoryTracking="); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:NativeMemoryTracking="); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldContain("Syntax error, expecting -XX:NativeMemoryTracking=[off|summary|detail]"); output.shouldHaveExitValue(1); diff --git a/test/hotspot/jtreg/runtime/NMT/CommandLineInvalidArgument.java b/test/hotspot/jtreg/runtime/NMT/CommandLineInvalidArgument.java index 78eeb29222c..655fa140d35 100644 --- a/test/hotspot/jtreg/runtime/NMT/CommandLineInvalidArgument.java +++ b/test/hotspot/jtreg/runtime/NMT/CommandLineInvalidArgument.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -24,6 +24,7 @@ /* * @test * @summary Invalid argument to NMT should result in an informative error message + * @requires vm.flagless * @library /test/lib * @modules java.base/jdk.internal.misc * java.management @@ -36,7 +37,7 @@ public class CommandLineInvalidArgument { public static void main(String args[]) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-XX:NativeMemoryTracking=apa"); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:NativeMemoryTracking=apa"); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldContain("Syntax error, expecting -XX:NativeMemoryTracking=[off|summary|detail]"); output.shouldHaveExitValue(1); diff --git a/test/hotspot/jtreg/runtime/NMT/CommandLineSummary.java b/test/hotspot/jtreg/runtime/NMT/CommandLineSummary.java index 1efe805b457..02b37a40ef4 100644 --- a/test/hotspot/jtreg/runtime/NMT/CommandLineSummary.java +++ b/test/hotspot/jtreg/runtime/NMT/CommandLineSummary.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2023, Oracle and/or its affiliates. All rights reserved. * 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,7 +37,7 @@ public class CommandLineSummary { public static void main(String args[]) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder( "-XX:NativeMemoryTracking=summary", "-version"); OutputAnalyzer output = new OutputAnalyzer(pb.start()); diff --git a/test/hotspot/jtreg/runtime/NMT/CommandLineTurnOffNMT.java b/test/hotspot/jtreg/runtime/NMT/CommandLineTurnOffNMT.java index c2b784e383e..199a2957f61 100644 --- a/test/hotspot/jtreg/runtime/NMT/CommandLineTurnOffNMT.java +++ b/test/hotspot/jtreg/runtime/NMT/CommandLineTurnOffNMT.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -24,6 +24,7 @@ /* * @test * @summary Turning off NMT should not result in an error + * @requires vm.flagless * @library /test/lib * @modules java.base/jdk.internal.misc * java.management @@ -36,7 +37,7 @@ public class CommandLineTurnOffNMT { public static void main(String args[]) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:NativeMemoryTracking=off", "-version"); OutputAnalyzer output = new OutputAnalyzer(pb.start()); diff --git a/test/hotspot/jtreg/runtime/NMT/JcmdWithNMTDisabled.java b/test/hotspot/jtreg/runtime/NMT/JcmdWithNMTDisabled.java index da1dd497975..3b61a0be383 100644 --- a/test/hotspot/jtreg/runtime/NMT/JcmdWithNMTDisabled.java +++ b/test/hotspot/jtreg/runtime/NMT/JcmdWithNMTDisabled.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -24,6 +24,7 @@ /* * @test * @summary Verify that jcmd correctly reports that NMT is not enabled + * @requires vm.flagless * @library /test/lib * @modules java.base/jdk.internal.misc * java.management @@ -50,13 +51,13 @@ public static void main(String args[]) throws Exception { // First run without enabling NMT (not in debug, where NMT is by default on) if (!Platform.isDebugBuild()) { - pb = ProcessTools.createJavaProcessBuilder("-Dtest.jdk=" + testjdkPath, "JcmdWithNMTDisabled"); + pb = ProcessTools.createLimitedTestJavaProcessBuilder("-Dtest.jdk=" + testjdkPath, "JcmdWithNMTDisabled"); output = new OutputAnalyzer(pb.start()); output.shouldHaveExitValue(0); } // Then run with explicitly disabling NMT, should not be any difference - pb = ProcessTools.createJavaProcessBuilder("-Dtest.jdk=" + testjdkPath, "-XX:NativeMemoryTracking=off", "JcmdWithNMTDisabled"); + pb = ProcessTools.createLimitedTestJavaProcessBuilder("-Dtest.jdk=" + testjdkPath, "-XX:NativeMemoryTracking=off", "JcmdWithNMTDisabled"); output = new OutputAnalyzer(pb.start()); output.shouldHaveExitValue(0); diff --git a/test/hotspot/jtreg/runtime/NMT/NMTInitializationTest.java b/test/hotspot/jtreg/runtime/NMT/NMTInitializationTest.java index 896dcaa1f3c..69da913bd71 100644 --- a/test/hotspot/jtreg/runtime/NMT/NMTInitializationTest.java +++ b/test/hotspot/jtreg/runtime/NMT/NMTInitializationTest.java @@ -1,6 +1,6 @@ /* * Copyright (c) 2021 SAP SE. All rights reserved. - * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2021, 2023, Oracle and/or its affiliates. All rights reserved. * 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,7 +156,7 @@ public static void main(String args[]) throws Exception { } vmArgs.add("-version"); - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(vmArgs); + ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder(vmArgs); OutputAnalyzer output = new OutputAnalyzer(pb.start()); if (debug) { output.reportDiagnosticSummary(); diff --git a/test/hotspot/jtreg/runtime/NMT/NMTWithCDS.java b/test/hotspot/jtreg/runtime/NMT/NMTWithCDS.java index 777b08ce9ff..226626acb34 100644 --- a/test/hotspot/jtreg/runtime/NMT/NMTWithCDS.java +++ b/test/hotspot/jtreg/runtime/NMT/NMTWithCDS.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2023, Oracle and/or its affiliates. All rights reserved. * 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,14 +38,14 @@ public class NMTWithCDS { public static void main(String[] args) throws Exception { ProcessBuilder pb; - pb = ProcessTools.createJavaProcessBuilder( + pb = ProcessTools.createTestJavaProcessBuilder( "-XX:+UnlockDiagnosticVMOptions", "-XX:SharedArchiveFile=./NMTWithCDS.jsa", "-Xshare:dump", "-Xlog:cds"); OutputAnalyzer output = new OutputAnalyzer(pb.start()); try { output.shouldContain("Loading classes to share"); output.shouldHaveExitValue(0); - pb = ProcessTools.createJavaProcessBuilder( + pb = ProcessTools.createTestJavaProcessBuilder( "-XX:+UnlockDiagnosticVMOptions", "-XX:NativeMemoryTracking=detail", "-XX:SharedArchiveFile=./NMTWithCDS.jsa", "-Xshare:on", "-version"); output = new OutputAnalyzer(pb.start()); output.shouldContain("sharing"); diff --git a/test/hotspot/jtreg/runtime/NMT/PrintNMTStatistics.java b/test/hotspot/jtreg/runtime/NMT/PrintNMTStatistics.java index c59ce0315e8..389e6a25de5 100644 --- a/test/hotspot/jtreg/runtime/NMT/PrintNMTStatistics.java +++ b/test/hotspot/jtreg/runtime/NMT/PrintNMTStatistics.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2023, Oracle and/or its affiliates. All rights reserved. * 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,7 +37,7 @@ public class PrintNMTStatistics { public static void main(String args[]) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder( "-XX:+UnlockDiagnosticVMOptions", "-XX:+PrintNMTStatistics", "-XX:NativeMemoryTracking=detail", @@ -55,7 +55,7 @@ public static void main(String args[]) throws Exception { // Make sure memory reserved for Module processing is recorded. output_detail.shouldContain(" Module (reserved="); - ProcessBuilder pb1 = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb1 = ProcessTools.createTestJavaProcessBuilder( "-XX:+UnlockDiagnosticVMOptions", "-XX:+PrintNMTStatistics", "-XX:NativeMemoryTracking=summary", diff --git a/test/hotspot/jtreg/runtime/NMT/PrintNMTStatisticsWithNMTDisabled.java b/test/hotspot/jtreg/runtime/NMT/PrintNMTStatisticsWithNMTDisabled.java index 31ab2537fe1..897893c47ea 100644 --- a/test/hotspot/jtreg/runtime/NMT/PrintNMTStatisticsWithNMTDisabled.java +++ b/test/hotspot/jtreg/runtime/NMT/PrintNMTStatisticsWithNMTDisabled.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -24,6 +24,7 @@ /* * @test * @summary Trying to enable PrintNMTStatistics should result in a warning + * @requires vm.flagless * @library /test/lib * @modules java.base/jdk.internal.misc * java.management @@ -36,7 +37,7 @@ public class PrintNMTStatisticsWithNMTDisabled { public static void main(String args[]) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:+UnlockDiagnosticVMOptions", "-XX:+PrintNMTStatistics", "-XX:NativeMemoryTracking=off", "-version"); diff --git a/test/hotspot/jtreg/runtime/Nestmates/membership/TestNestHostErrorWithClassUnload.java b/test/hotspot/jtreg/runtime/Nestmates/membership/TestNestHostErrorWithClassUnload.java index 70c34e0a376..c65b4a17a66 100644 --- a/test/hotspot/jtreg/runtime/Nestmates/membership/TestNestHostErrorWithClassUnload.java +++ b/test/hotspot/jtreg/runtime/Nestmates/membership/TestNestHostErrorWithClassUnload.java @@ -34,8 +34,10 @@ * PackagedNestHost.java * PackagedNestHost2.java * @compile PackagedNestHost2Member.jcod - * - * @run main/othervm -Xlog:class+unload=trace TestNestHostErrorWithClassUnload + + * @build jdk.test.whitebox.WhiteBox + * @run driver jdk.test.lib.helpers.ClassFileInstaller jdk.test.whitebox.WhiteBox + * @run main/othervm -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI -Xlog:class+unload=trace TestNestHostErrorWithClassUnload */ // Test setup: diff --git a/test/hotspot/jtreg/runtime/PerfMemDestroy/PerfMemDestroy.java b/test/hotspot/jtreg/runtime/PerfMemDestroy/PerfMemDestroy.java index 2040c755576..1ee2f604df6 100644 --- a/test/hotspot/jtreg/runtime/PerfMemDestroy/PerfMemDestroy.java +++ b/test/hotspot/jtreg/runtime/PerfMemDestroy/PerfMemDestroy.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2023, Oracle and/or its affiliates. All rights reserved. * 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,7 +39,7 @@ public class PerfMemDestroy { public static void main(String args[]) throws Throwable { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-XX:+PerfAllowAtExitRegistration", "-version"); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:+PerfAllowAtExitRegistration", "-version"); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldHaveExitValue(0); } diff --git a/test/hotspot/jtreg/runtime/PrintStringTableStats/PrintStringTableStatsTest.java b/test/hotspot/jtreg/runtime/PrintStringTableStats/PrintStringTableStatsTest.java index 1425e3e6eb1..4dfde2f1d0b 100644 --- a/test/hotspot/jtreg/runtime/PrintStringTableStats/PrintStringTableStatsTest.java +++ b/test/hotspot/jtreg/runtime/PrintStringTableStats/PrintStringTableStatsTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -34,7 +34,7 @@ public class PrintStringTableStatsTest { public static void main(String... args) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:+PrintStringTableStatistics", "--version"); OutputAnalyzer output = new OutputAnalyzer(pb.start()); diff --git a/test/hotspot/jtreg/runtime/ReservedStack/ReservedStackTest.java b/test/hotspot/jtreg/runtime/ReservedStack/ReservedStackTest.java index 36f74d01b54..e75e6643809 100644 --- a/test/hotspot/jtreg/runtime/ReservedStack/ReservedStackTest.java +++ b/test/hotspot/jtreg/runtime/ReservedStack/ReservedStackTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -254,7 +254,7 @@ private static void initIsSupportedPlatform() throws Exception { // In order to dynamicaly determine if the platform supports the reserved // stack area, run with -XX:StackReservedPages=1 and see if we get the // expected warning message for platforms that don't support it. - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-XX:StackReservedPages=1", "-version"); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:StackReservedPages=1", "-version"); OutputAnalyzer output = new OutputAnalyzer(pb.start()); System.out.println("StackReservedPages=1 log: [" + output.getOutput() + "]"); if (output.getExitValue() != 0) { diff --git a/test/hotspot/jtreg/runtime/Safepoint/TestAbortOnVMOperationTimeout.java b/test/hotspot/jtreg/runtime/Safepoint/TestAbortOnVMOperationTimeout.java index 33de13f6c45..a2c3f944db8 100644 --- a/test/hotspot/jtreg/runtime/Safepoint/TestAbortOnVMOperationTimeout.java +++ b/test/hotspot/jtreg/runtime/Safepoint/TestAbortOnVMOperationTimeout.java @@ -63,7 +63,7 @@ public static void main(String[] args) throws Exception { } public static void testWith(int delay, boolean shouldPass) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:+UnlockDiagnosticVMOptions", "-XX:+AbortVMOnVMOperationTimeout", "-XX:AbortVMOnVMOperationTimeoutDelay=" + delay, diff --git a/test/hotspot/jtreg/runtime/Safepoint/TestAbortVMOnSafepointTimeout.java b/test/hotspot/jtreg/runtime/Safepoint/TestAbortVMOnSafepointTimeout.java index e7e3cfca781..e54f40e0893 100644 --- a/test/hotspot/jtreg/runtime/Safepoint/TestAbortVMOnSafepointTimeout.java +++ b/test/hotspot/jtreg/runtime/Safepoint/TestAbortVMOnSafepointTimeout.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2020, 2023, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2019 SAP SE. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -40,7 +40,7 @@ public class TestAbortVMOnSafepointTimeout { public static void main(String[] args) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-Xbootclasspath/a:.", "-XX:+UnlockDiagnosticVMOptions", "-XX:+WhiteBoxAPI", diff --git a/test/hotspot/jtreg/runtime/StackTrace/LargeClassTest.java b/test/hotspot/jtreg/runtime/StackTrace/LargeClassTest.java index 5ef84f9ca95..d82b4b1f195 100644 --- a/test/hotspot/jtreg/runtime/StackTrace/LargeClassTest.java +++ b/test/hotspot/jtreg/runtime/StackTrace/LargeClassTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2023, Oracle and/or its affiliates. All rights reserved. * 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 @@ public class LargeClassTest implements Opcodes { public static void main(String... args) throws Exception { writeClassFile(); - ProcessBuilder pb = ProcessTools.createTestJvm("-cp", ".", "Large"); + ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder("-cp", ".", "Large"); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldHaveExitValue(0); } diff --git a/test/hotspot/jtreg/runtime/Thread/TestBreakSignalThreadDump.java b/test/hotspot/jtreg/runtime/Thread/TestBreakSignalThreadDump.java index 1ad74dbec0f..aecf3fdb5a6 100644 --- a/test/hotspot/jtreg/runtime/Thread/TestBreakSignalThreadDump.java +++ b/test/hotspot/jtreg/runtime/Thread/TestBreakSignalThreadDump.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2023, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2022, Google and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -67,7 +67,7 @@ public static void main(String[] argv) throws Exception { public static void main(String[] argv) throws Exception { String main = "TestBreakSignalThreadDump$TestProcess"; - ProcessBuilder pb = ProcessTools.createTestJvm("-Djava.library.path=" + Utils.TEST_NATIVE_PATH, main); + ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder("-Djava.library.path=" + Utils.TEST_NATIVE_PATH, main); if (argv.length > 0 && argv[0].equals("load_libjsig")) { prepend_jsig_lib(pb.environment()); diff --git a/test/hotspot/jtreg/runtime/Thread/TooSmallStackSize.java b/test/hotspot/jtreg/runtime/Thread/TooSmallStackSize.java index 7841e822a3b..88e0e4d8d0b 100644 --- a/test/hotspot/jtreg/runtime/Thread/TooSmallStackSize.java +++ b/test/hotspot/jtreg/runtime/Thread/TooSmallStackSize.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -101,7 +101,7 @@ static String checkStack(String stackOption, String optionMesg, String stackSize System.out.println("*** Testing " + stackOption + stackSize); - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( stackOption + stackSize, // Uncomment the following to get log output // that shows actual thread creation sizes. @@ -144,7 +144,7 @@ static String checkStack(String stackOption, String optionMesg, String stackSize static void checkMinStackAllowed(String stackOption, String optionMesg, String stackSize) throws Exception { System.out.println("*** Testing " + stackOption + stackSize); - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( stackOption + stackSize, // Uncomment the following to get log output // that shows actual thread creation sizes. diff --git a/test/hotspot/jtreg/runtime/Throwable/StackTraceLogging.java b/test/hotspot/jtreg/runtime/Throwable/StackTraceLogging.java index 1482037b28f..ef63dc942f1 100644 --- a/test/hotspot/jtreg/runtime/Throwable/StackTraceLogging.java +++ b/test/hotspot/jtreg/runtime/Throwable/StackTraceLogging.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -51,11 +51,11 @@ static void analyzeOutputOn(ProcessBuilder pb) throws Exception { public static void main(String[] args) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-Xlog:stacktrace=info", - "-XX:MaxJavaStackTraceDepth=1024", - "--add-opens", - "java.base/java.lang=ALL-UNNAMED", - "TestThrowable"); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-Xlog:stacktrace=info", + "-XX:MaxJavaStackTraceDepth=1024", + "--add-opens", + "java.base/java.lang=ALL-UNNAMED", + "TestThrowable"); analyzeOutputOn(pb); } } diff --git a/test/hotspot/jtreg/runtime/Throwable/TestCatchThrowableOOM.java b/test/hotspot/jtreg/runtime/Throwable/TestCatchThrowableOOM.java index 36fedc0bd2d..b7c261afbd0 100644 --- a/test/hotspot/jtreg/runtime/Throwable/TestCatchThrowableOOM.java +++ b/test/hotspot/jtreg/runtime/Throwable/TestCatchThrowableOOM.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2021, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -43,10 +43,10 @@ public class TestCatchThrowableOOM { }; public static void main(String[] args) throws Throwable { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-Xmx64m", - "-Xlog:exceptions=trace", + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-Xmx64m", + "-Xlog:exceptions=trace", - "TestCatchThrowableOOM$OOM"); + "TestCatchThrowableOOM$OOM"); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldHaveExitValue(0); for (String msg : expected) { diff --git a/test/hotspot/jtreg/runtime/Throwable/TestMaxJavaStackTraceDepth.java b/test/hotspot/jtreg/runtime/Throwable/TestMaxJavaStackTraceDepth.java index 92e57718608..95f29ee2eb6 100644 --- a/test/hotspot/jtreg/runtime/Throwable/TestMaxJavaStackTraceDepth.java +++ b/test/hotspot/jtreg/runtime/Throwable/TestMaxJavaStackTraceDepth.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -79,11 +79,11 @@ public static void main(String args[]) throws Exception { int[] depths = {0, 20, 1024}; for (int d : depths) { System.out.println("running test with -XX:MaxJavaStackTraceDepth=" + d); - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-Xlog:stacktrace=info", - "-XX:MaxJavaStackTraceDepth=" + d, - "--add-opens", - "java.base/java.lang=ALL-UNNAMED", - "TestMaxJavaStackTraceDepth"); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-Xlog:stacktrace=info", + "-XX:MaxJavaStackTraceDepth=" + d, + "--add-opens", + "java.base/java.lang=ALL-UNNAMED", + "TestMaxJavaStackTraceDepth"); OutputAnalyzer output = new OutputAnalyzer(pb.start()); if (d == 0) { // Should get all the elements in stack trace diff --git a/test/hotspot/jtreg/runtime/Unsafe/RangeCheck.java b/test/hotspot/jtreg/runtime/Unsafe/RangeCheck.java index 2f9ae3fddff..788b96fb22e 100644 --- a/test/hotspot/jtreg/runtime/Unsafe/RangeCheck.java +++ b/test/hotspot/jtreg/runtime/Unsafe/RangeCheck.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2023, Oracle and/or its affiliates. All rights reserved. * 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,7 +40,7 @@ public class RangeCheck { public static void main(String args[]) throws Exception { - ProcessBuilder pb = ProcessTools.createTestJvm( + ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder( "-Xmx128m", "--add-exports=java.base/jdk.internal.misc=ALL-UNNAMED", "-XX:-CreateCoredumpOnCrash", diff --git a/test/hotspot/jtreg/runtime/XCheckJniJsig/XCheckJSig.java b/test/hotspot/jtreg/runtime/XCheckJniJsig/XCheckJSig.java index 03d5d885e45..aae401df963 100644 --- a/test/hotspot/jtreg/runtime/XCheckJniJsig/XCheckJSig.java +++ b/test/hotspot/jtreg/runtime/XCheckJniJsig/XCheckJSig.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2023, Oracle and/or its affiliates. All rights reserved. * 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,14 +61,14 @@ public static void main(String args[]) throws Throwable { throw new RuntimeException("File libjsig not found, path: " + libjsig); } - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-Xcheck:jni", "-version"); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-Xcheck:jni", "-version"); Map env = pb.environment(); env.put(env_var, libjsig); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldNotContain("libjsig is activated"); output.shouldHaveExitValue(0); - pb = ProcessTools.createJavaProcessBuilder("-Xcheck:jni", "-verbose:jni", "-version"); + pb = ProcessTools.createLimitedTestJavaProcessBuilder("-Xcheck:jni", "-verbose:jni", "-version"); env = pb.environment(); env.put(env_var, libjsig); output = new OutputAnalyzer(pb.start()); diff --git a/test/hotspot/jtreg/runtime/cds/DeterministicDump.java b/test/hotspot/jtreg/runtime/cds/DeterministicDump.java index 9cdba1fa922..852e20b0610 100644 --- a/test/hotspot/jtreg/runtime/cds/DeterministicDump.java +++ b/test/hotspot/jtreg/runtime/cds/DeterministicDump.java @@ -25,7 +25,7 @@ * @test * @bug 8241071 * @summary The same JDK build should always generate the same archive file (no randomness). - * @requires vm.cds + * @requires vm.cds & vm.flagless * @library /test/lib * @run driver DeterministicDump */ diff --git a/test/hotspot/jtreg/runtime/cds/MaxMetaspaceSize.java b/test/hotspot/jtreg/runtime/cds/MaxMetaspaceSize.java index c59449d6b1c..c021aa0cab9 100644 --- a/test/hotspot/jtreg/runtime/cds/MaxMetaspaceSize.java +++ b/test/hotspot/jtreg/runtime/cds/MaxMetaspaceSize.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -52,7 +52,7 @@ public static void main(String[] args) throws Exception { } String msg = "OutOfMemoryError: Metaspace"; - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(processArgs); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(processArgs); CDSTestUtils.executeAndLog(pb, "dump").shouldContain(msg).shouldHaveExitValue(1); } } diff --git a/test/hotspot/jtreg/runtime/cds/SharedStrings.java b/test/hotspot/jtreg/runtime/cds/SharedStrings.java index bda830401f0..33a041bb298 100644 --- a/test/hotspot/jtreg/runtime/cds/SharedStrings.java +++ b/test/hotspot/jtreg/runtime/cds/SharedStrings.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -44,7 +44,7 @@ public static void main(String[] args) throws Exception { // This also serves as a reference on how to use this feature, // hence the command lines are spelled out instead of using the // test utils methods. - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:+UnlockDiagnosticVMOptions", "-XX:SharedArchiveFile=./SharedStrings.jsa", "-Xlog:cds,cds+hashtables", @@ -56,7 +56,7 @@ public static void main(String[] args) throws Exception { CDSTestUtils.checkDump(out, "Shared string table stats"); - pb = ProcessTools.createJavaProcessBuilder( + pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:+UnlockDiagnosticVMOptions", "-XX:SharedArchiveFile=./SharedStrings.jsa", // needed for access to white box test API diff --git a/test/hotspot/jtreg/runtime/cds/TestCDSVMCrash.java b/test/hotspot/jtreg/runtime/cds/TestCDSVMCrash.java index 1a13e30f33a..183b1c3afcf 100644 --- a/test/hotspot/jtreg/runtime/cds/TestCDSVMCrash.java +++ b/test/hotspot/jtreg/runtime/cds/TestCDSVMCrash.java @@ -49,7 +49,7 @@ public static void main(String[] args) throws Exception { } } // else this is the main test - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-XX:+CrashOnOutOfMemoryError", + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:+CrashOnOutOfMemoryError", "-XX:-CreateCoredumpOnCrash", "-Xmx128m", "-Xshare:on", TestCDSVMCrash.class.getName(),"throwOOME"); OutputAnalyzer output = new OutputAnalyzer(pb.start()); // executeAndLog should throw an exception in the VM crashed diff --git a/test/hotspot/jtreg/runtime/cds/appcds/TestCommon.java b/test/hotspot/jtreg/runtime/cds/appcds/TestCommon.java index c540a23e01e..d668a0adcbf 100644 --- a/test/hotspot/jtreg/runtime/cds/appcds/TestCommon.java +++ b/test/hotspot/jtreg/runtime/cds/appcds/TestCommon.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2023, Oracle and/or its affiliates. All rights reserved. * 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,7 +156,7 @@ public static OutputAnalyzer dumpBaseArchive(String baseArchiveName, String ... // Create AppCDS archive using most common args - convenience method public static OutputAnalyzer createArchive(String appJar, String classList[], String... suffix) throws Exception { - AppCDSOptions opts = (new AppCDSOptions()).setAppJar(appJar); + CDSOptions opts = (new CDSOptions()).setAppJar(appJar); opts.setClassList(classList); opts.addSuffix(suffix); return createArchive(opts); @@ -164,7 +164,7 @@ public static OutputAnalyzer createArchive(String appJar, String classList[], public static OutputAnalyzer createArchive(String appJarDir, String appJar, String classList[], String... suffix) throws Exception { - AppCDSOptions opts = (new AppCDSOptions()).setAppJar(appJar); + CDSOptions opts = (new CDSOptions()).setAppJar(appJar); opts.setAppJarDir(appJarDir); opts.setClassList(classList); opts.addSuffix(suffix); @@ -194,7 +194,7 @@ private static void captureVerifyOpts(ArrayList opts, ArrayList } // Create AppCDS archive using appcds options - public static OutputAnalyzer createArchive(AppCDSOptions opts) + public static OutputAnalyzer createArchive(CDSOptions opts) throws Exception { ArrayList cmd = new ArrayList(); ArrayList verifyOpts = new ArrayList(); @@ -285,7 +285,7 @@ public static OutputAnalyzer createArchive(AppCDSOptions opts) } } - ProcessBuilder pb = ProcessTools.createTestJvm(cmd); + ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder(cmd); if (opts.appJarDir != null) { pb.directory(new File(opts.appJarDir)); } @@ -394,8 +394,8 @@ private static void patchJarForDynamicDump(String cp) throws Exception { } } - // Execute JVM using AppCDS archive with specified AppCDSOptions - public static OutputAnalyzer runWithArchive(AppCDSOptions opts) + // Execute JVM using AppCDS archive with specified CDSOptions + public static OutputAnalyzer runWithArchive(CDSOptions opts) throws Exception { ArrayList cmd = new ArrayList(); @@ -432,7 +432,7 @@ public static OutputAnalyzer runWithArchive(AppCDSOptions opts) } } - ProcessBuilder pb = ProcessTools.createTestJvm(cmd); + ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder(cmd); if (opts.appJarDir != null) { pb.directory(new File(opts.appJarDir)); } @@ -441,7 +441,7 @@ public static OutputAnalyzer runWithArchive(AppCDSOptions opts) public static OutputAnalyzer execCommon(String... suffix) throws Exception { - AppCDSOptions opts = (new AppCDSOptions()); + CDSOptions opts = (new CDSOptions()); opts.addSuffix(suffix); return runWithArchive(opts); } @@ -449,53 +449,53 @@ public static OutputAnalyzer execCommon(String... suffix) throws Exception { // This is the new API for running a Java process with CDS enabled. // See comments in the CDSTestUtils.Result class for how to use this method. public static Result run(String... suffix) throws Exception { - AppCDSOptions opts = (new AppCDSOptions()); + CDSOptions opts = (new CDSOptions()); opts.addSuffix(suffix); return new Result(opts, runWithArchive(opts)); } public static Result runWithoutCDS(String... suffix) throws Exception { - AppCDSOptions opts = (new AppCDSOptions()); + CDSOptions opts = (new CDSOptions()); opts.addSuffix(suffix).setXShareMode("off");; return new Result(opts, runWithArchive(opts)); } public static Result runWithRelativePath(String jarDir, String... suffix) throws Exception { - AppCDSOptions opts = (new AppCDSOptions()); + CDSOptions opts = (new CDSOptions()); opts.setAppJarDir(jarDir); opts.addSuffix(suffix); return new Result(opts, runWithArchive(opts)); } public static OutputAnalyzer exec(String appJar, String... suffix) throws Exception { - AppCDSOptions opts = (new AppCDSOptions()).setAppJar(appJar); + CDSOptions opts = (new CDSOptions()).setAppJar(appJar); opts.addSuffix(suffix); return runWithArchive(opts); } public static Result runWithModules(String prefix[], String upgrademodulepath, String modulepath, String mid, String... testClassArgs) throws Exception { - AppCDSOptions opts = makeModuleOptions(prefix, upgrademodulepath, modulepath, + CDSOptions opts = makeModuleOptions(prefix, upgrademodulepath, modulepath, mid, testClassArgs); return new Result(opts, runWithArchive(opts)); } public static OutputAnalyzer execAuto(String... suffix) throws Exception { - AppCDSOptions opts = (new AppCDSOptions()); + CDSOptions opts = (new CDSOptions()); opts.addSuffix(suffix).setXShareMode("auto"); return runWithArchive(opts); } public static OutputAnalyzer execOff(String... suffix) throws Exception { - AppCDSOptions opts = (new AppCDSOptions()); + CDSOptions opts = (new CDSOptions()); opts.addSuffix(suffix).setXShareMode("off"); return runWithArchive(opts); } - private static AppCDSOptions makeModuleOptions(String prefix[], String upgrademodulepath, String modulepath, + private static CDSOptions makeModuleOptions(String prefix[], String upgrademodulepath, String modulepath, String mid, String testClassArgs[]) { - AppCDSOptions opts = (new AppCDSOptions()); + CDSOptions opts = (new CDSOptions()); opts.addPrefix(prefix); if (upgrademodulepath == null) { @@ -511,7 +511,7 @@ private static AppCDSOptions makeModuleOptions(String prefix[], String upgrademo public static OutputAnalyzer execModule(String prefix[], String upgrademodulepath, String modulepath, String mid, String... testClassArgs) throws Exception { - AppCDSOptions opts = makeModuleOptions(prefix, upgrademodulepath, modulepath, + CDSOptions opts = makeModuleOptions(prefix, upgrademodulepath, modulepath, mid, testClassArgs); return runWithArchive(opts); } diff --git a/test/hotspot/jtreg/runtime/cds/appcds/VerifyWithDefaultArchive.java b/test/hotspot/jtreg/runtime/cds/appcds/VerifyWithDefaultArchive.java index aa65bb38b1c..6835adf33f3 100644 --- a/test/hotspot/jtreg/runtime/cds/appcds/VerifyWithDefaultArchive.java +++ b/test/hotspot/jtreg/runtime/cds/appcds/VerifyWithDefaultArchive.java @@ -37,7 +37,7 @@ public class VerifyWithDefaultArchive { public static void main(String... args) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-Xlog:cds", "-XX:+VerifySharedSpaces", "-version"); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-Xlog:cds", "-XX:+VerifySharedSpaces", "-version"); OutputAnalyzer out = new OutputAnalyzer(pb.start()); out.shouldNotContain("relocation bitmap CRC error"); out.shouldHaveExitValue(0); diff --git a/test/hotspot/jtreg/runtime/cds/appcds/dynamicArchive/DynamicArchiveTestBase.java b/test/hotspot/jtreg/runtime/cds/appcds/dynamicArchive/DynamicArchiveTestBase.java index 17efcaa1ea3..608f0d1847e 100644 --- a/test/hotspot/jtreg/runtime/cds/appcds/dynamicArchive/DynamicArchiveTestBase.java +++ b/test/hotspot/jtreg/runtime/cds/appcds/dynamicArchive/DynamicArchiveTestBase.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -242,7 +242,7 @@ private static Result execProcess(String mode, String jarDir, String[] cmdLine) if (!executedIn_run) { throw new Exception("Test error: dynamic archive tests must be executed via DynamicArchiveTestBase.run()"); } - ProcessBuilder pb = ProcessTools.createTestJvm(cmdLine); + ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder(cmdLine); if (jarDir != null) { pb.directory(new File(jarDir)); } diff --git a/test/hotspot/jtreg/runtime/cds/appcds/jcmd/JCmdTestDynamicDump.java b/test/hotspot/jtreg/runtime/cds/appcds/jcmd/JCmdTestDynamicDump.java index c745c866fbe..7b61df8f01b 100644 --- a/test/hotspot/jtreg/runtime/cds/appcds/jcmd/JCmdTestDynamicDump.java +++ b/test/hotspot/jtreg/runtime/cds/appcds/jcmd/JCmdTestDynamicDump.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2021, 2023, Oracle and/or its affiliates. All rights reserved. * 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 @@ static void test() throws Exception { private static void dumpStaticArchive(String archiveFile) throws Exception { String javapath = JDKToolFinder.getJDKTool("java"); String cmd[] = {javapath, "-Xshare:dump", "-XX:SharedArchiveFile=" + archiveFile}; - // Do not use ProcessTools.createTestJvm(cmd) here, it copies jtreg env. + // Do not use ProcessTools.createTestJavaProcessBuilder(cmd) here, it copies jtreg env. ProcessBuilder pb = new ProcessBuilder(cmd); CDSTestUtils.executeAndLog(pb, "dump") .shouldHaveExitValue(0); diff --git a/test/hotspot/jtreg/runtime/cds/appcds/sharedStrings/ResolvedReferencesNotNullTest.java b/test/hotspot/jtreg/runtime/cds/appcds/sharedStrings/ResolvedReferencesNotNullTest.java new file mode 100644 index 00000000000..bdd5ad9ec7e --- /dev/null +++ b/test/hotspot/jtreg/runtime/cds/appcds/sharedStrings/ResolvedReferencesNotNullTest.java @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute 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 ResolvedReferencesNotNullTest + * @bug 8313638 + * @summary Testing resolved references array to ensure elements are non-null + * @requires vm.cds.write.archived.java.heap + * @library /test/lib /test/hotspot/jtreg/runtime/cds/appcds + * @build jdk.test.whitebox.WhiteBox ResolvedReferencesWb ResolvedReferencesTestApp + * @run driver jdk.test.lib.helpers.ClassFileInstaller jdk.test.whitebox.WhiteBox + * @run driver ResolvedReferencesNotNullTest + */ + +import jdk.test.lib.process.OutputAnalyzer; +import jdk.test.lib.process.ProcessTools; +import jdk.test.whitebox.WhiteBox; + +public class ResolvedReferencesNotNullTest { + public static void main(String[] args) throws Exception { + SharedStringsUtils.buildJarAndWhiteBox("ResolvedReferencesWb", "ResolvedReferencesTestApp"); + String appJar = TestCommon.getTestJar(SharedStringsUtils.TEST_JAR_NAME_FULL); + String whiteboxParam = SharedStringsUtils.getWbParam(); + + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-cp", + appJar, + whiteboxParam, + "-XX:+UnlockDiagnosticVMOptions", + "-XX:+WhiteBoxAPI", + "ResolvedReferencesWb", + "false" // ResolvedReferencesTestApp is not archived + ); + OutputAnalyzer output = new OutputAnalyzer(pb.start()); + output.shouldHaveExitValue(0); + + TestCommon.dump(appJar, + TestCommon.list("ResolvedReferencesWb", "ResolvedReferencesTestApp"), + TestCommon.concat("-XX:SharedArchiveFile=ResolvedRef.jsa", + "-XX:+UnlockDiagnosticVMOptions", + "-XX:+WhiteBoxAPI", + whiteboxParam)); + + // Since ResolvedReferencesTestApp is now archived, all of the strings should be in the resolved + // references array + TestCommon.run("-cp", + appJar, + whiteboxParam, + "-XX:SharedArchiveFile=ResolvedRef.jsa", + "-XX:+UnlockDiagnosticVMOptions", + "-XX:+WhiteBoxAPI", + "ResolvedReferencesWb", + "true" // ResolvedReferencesTestApp is archived + ).assertNormalExit(); + } +} diff --git a/test/jdk/java/util/zip/ZipFile/Available.java b/test/hotspot/jtreg/runtime/cds/appcds/sharedStrings/ResolvedReferencesTestApp.java similarity index 65% rename from test/jdk/java/util/zip/ZipFile/Available.java rename to test/hotspot/jtreg/runtime/cds/appcds/sharedStrings/ResolvedReferencesTestApp.java index 364a3b02439..4b059485bc9 100644 --- a/test/jdk/java/util/zip/ZipFile/Available.java +++ b/test/hotspot/jtreg/runtime/cds/appcds/sharedStrings/ResolvedReferencesTestApp.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,17 +21,11 @@ * questions. */ -import java.util.zip.*; -import java.io.File; +public class ResolvedReferencesTestApp { + // These strings must be in the resolved references array + static String foo = "fooString"; + static String bar = "barString"; -public class Available -{ - public static void main (String argv[]) throws Exception { - ZipFile zf = new ZipFile(new File(System.getProperty("test.src"), - "input.jar")); - ZipEntry e = zf.getEntry("ReleaseInflater.java"); - if (e.getSize() != zf.getInputStream(e).available()) { - throw new Exception("wrong return value of available"); - } - } + // This method is never called so the string should not be added to the resolved references array + String qux() { return "quxString"; } } diff --git a/test/hotspot/jtreg/runtime/cds/appcds/sharedStrings/ResolvedReferencesWb.java b/test/hotspot/jtreg/runtime/cds/appcds/sharedStrings/ResolvedReferencesWb.java new file mode 100644 index 00000000000..d1e25936c3b --- /dev/null +++ b/test/hotspot/jtreg/runtime/cds/appcds/sharedStrings/ResolvedReferencesWb.java @@ -0,0 +1,83 @@ +/* + * Copyright (c) 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import jdk.test.whitebox.WhiteBox; + +public class ResolvedReferencesWb { + public static void main(String[] args) throws Exception { + WhiteBox wb = WhiteBox.getWhiteBox(); + + if (args.length < 1) { + throw new RuntimeException("Test requires arg: [true|false]"); + } + + if (!args[0].equals("true") && !args[0].equals("false")) { + throw new RuntimeException("Invalid argument: Test requires arg: [true|false]"); + } + + ResolvedReferencesTestApp t = new ResolvedReferencesTestApp(); + Object[] resolvedReferences = wb.getResolvedReferences(ResolvedReferencesTestApp.class); + boolean isArchived = (args[0].equals("true")); + + if (resolvedReferences.length <= 0) { + throw new RuntimeException("Resolved reference should not be null"); + } + + boolean foundFoo = false; + boolean foundBar = false; + boolean foundQux = false; + + for (Object o : resolvedReferences) { + if (o != null) { + foundFoo |= (o.equals("fooString")); + foundBar |= (o.equals("barString")); + foundQux |= (o.equals("quxString")); + } + } + + if (isArchived) { + // CDS eagerly resolves all the string literals in the ConstantPool. At this point, all + // three strings should be in the resolvedReferences array. + if (!foundFoo || !foundBar || !foundQux) { + throwException(resolvedReferences, "Incorrect resolved references array, all strings should be present"); + } + } else { + // If the class is not archived, the string literals in the ConstantPool are resolved + // on-demand. At this point, ResolvedReferencesTestApp:: has been executed + // so the two strings used there should be in the resolvedReferences array. + // ResolvedReferencesTestApp::qux() is not executed so "quxString" + // should not yet be resolved. + if (!foundFoo || !foundBar || foundQux) { + throwException(resolvedReferences, "Incorrect resolved references array, quxString should not be archived"); + } + } + } + + static void throwException(Object[] resolvedRefs, String errMsg) throws RuntimeException { + System.out.printf("Resolved References Array Length: %d\n", resolvedRefs.length); + for (Object o : resolvedRefs) { + System.out.println(o); + } + throw new RuntimeException(errMsg); + } +} diff --git a/test/jdk/java/util/zip/ZipFile/GetDirEntry.java b/test/hotspot/jtreg/runtime/classFileParserBug/Bad_NCDFE_Msg.java similarity index 52% rename from test/jdk/java/util/zip/ZipFile/GetDirEntry.java rename to test/hotspot/jtreg/runtime/classFileParserBug/Bad_NCDFE_Msg.java index e74fa6b3154..8f7a7c214b4 100644 --- a/test/jdk/java/util/zip/ZipFile/GetDirEntry.java +++ b/test/hotspot/jtreg/runtime/classFileParserBug/Bad_NCDFE_Msg.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,23 +21,29 @@ * questions. */ -/* @test - @bug 4206838 - @summary getEntry() will search for a directory - even without an ending '/'. +/* + * @test + * @bug 8288976 + * @library /test/lib + * @summary Check that the right message is displayed for NoClassDefFoundError exception. + * @requires vm.flagless + * @modules java.base/jdk.internal.misc + * java.management + * @compile C.java + * @run driver Bad_NCDFE_Msg */ -import java.io.*; -import java.util.zip.*; +import java.io.File; +import jdk.test.lib.process.ProcessTools; +import jdk.test.lib.process.OutputAnalyzer; + +public class Bad_NCDFE_Msg { -public class GetDirEntry { - public static void main(String args[]) throws Exception { - try (ZipFile zf = new ZipFile(new File(System.getProperty("test.src", "."), - "input.jar"))) { - ZipEntry ze = zf.getEntry("META-INF"); - if (ze == null) { - throw new Exception("failed to find a directory entry"); - } - } + public static void main(String args[]) throws Throwable { + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( + "-cp", System.getProperty("test.classes") + File.separator + "pkg", "C"); + OutputAnalyzer output = new OutputAnalyzer(pb.start()); + output.shouldContain("java.lang.NoClassDefFoundError: C (wrong name: pkg/C"); + output.shouldHaveExitValue(1); } } diff --git a/test/hotspot/jtreg/runtime/cds/appcds/AppCDSOptions.java b/test/hotspot/jtreg/runtime/classFileParserBug/C.java similarity index 63% rename from test/hotspot/jtreg/runtime/cds/appcds/AppCDSOptions.java rename to test/hotspot/jtreg/runtime/classFileParserBug/C.java index a4fee6bdd69..a8c8bfd6413 100644 --- a/test/hotspot/jtreg/runtime/cds/appcds/AppCDSOptions.java +++ b/test/hotspot/jtreg/runtime/classFileParserBug/C.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -19,24 +19,8 @@ * Please 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 jdk.test.lib.cds.CDSOptions; - -// This class represents options used for -// during creation of the archive and/or running JVM with archive - -public class AppCDSOptions extends CDSOptions { - public String appJar; - public String appJarDir; - - public AppCDSOptions setAppJar(String appJar) { - this.appJar = appJar; - return this; - } - public AppCDSOptions setAppJarDir(String appJarDir) { - this.appJarDir = appJarDir; - return this; - } -} +// class used by test Bad_NCDFE_Msg.java. +package pkg; +public class C { } diff --git a/test/hotspot/jtreg/runtime/classFileParserBug/ClassFileParserBug.java b/test/hotspot/jtreg/runtime/classFileParserBug/ClassFileParserBug.java index 31dde4d3adf..bac36378d2e 100644 --- a/test/hotspot/jtreg/runtime/classFileParserBug/ClassFileParserBug.java +++ b/test/hotspot/jtreg/runtime/classFileParserBug/ClassFileParserBug.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2023, Oracle and/or its affiliates. All rights reserved. * 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,7 +41,7 @@ public class ClassFileParserBug { public static void main(String args[]) throws Throwable { System.out.println("Regression test for bug 8040018"); - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("LambdaMath"); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("LambdaMath"); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldContain("java.lang.ClassFormatError: Bad length on BootstrapMethods"); output.shouldHaveExitValue(1); diff --git a/test/hotspot/jtreg/runtime/classFileParserBug/TestBadPackageWithInterface.java b/test/hotspot/jtreg/runtime/classFileParserBug/TestBadPackageWithInterface.java index f7028990b05..35abee5ce3e 100644 --- a/test/hotspot/jtreg/runtime/classFileParserBug/TestBadPackageWithInterface.java +++ b/test/hotspot/jtreg/runtime/classFileParserBug/TestBadPackageWithInterface.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2020, 2023, Oracle and/or its affiliates. All rights reserved. * 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,7 +38,7 @@ public class TestBadPackageWithInterface { public static void main(String args[]) throws Throwable { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-cp", System.getProperty("test.classes"), "-XX:+UnlockDiagnosticVMOptions", "-XX:+VerifyBeforeExit", MyLoader.class.getName()); diff --git a/test/hotspot/jtreg/runtime/classFileParserBug/TestEmptyBootstrapMethodsAttr.java b/test/hotspot/jtreg/runtime/classFileParserBug/TestEmptyBootstrapMethodsAttr.java index ea91f54da83..53c85d53c44 100644 --- a/test/hotspot/jtreg/runtime/classFileParserBug/TestEmptyBootstrapMethodsAttr.java +++ b/test/hotspot/jtreg/runtime/classFileParserBug/TestEmptyBootstrapMethodsAttr.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2023, Oracle and/or its affiliates. All rights reserved. * 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,7 +50,7 @@ public static void main(String args[]) throws Throwable { // ======= execute test case #1 // Expect a lack of main method, this implies that the class loaded correctly // with an empty bootstrap_methods and did not generate a ClassFormatError. - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-Duser.language=en", "-Duser.country=US", className); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldNotContain("java.lang.ClassFormatError"); @@ -65,7 +65,7 @@ public static void main(String args[]) throws Throwable { // ======= execute test case #2 // Expect a lack of main method, this implies that the class loaded correctly // with an empty bootstrap_methods and did not generate ClassFormatError. - pb = ProcessTools.createJavaProcessBuilder( + pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-Duser.language=en", "-Duser.country=US", className); output = new OutputAnalyzer(pb.start()); output.shouldNotContain("java.lang.ClassFormatError"); diff --git a/test/hotspot/jtreg/runtime/condy/BadBSMUseTest.java b/test/hotspot/jtreg/runtime/condy/BadBSMUseTest.java index 4ae0eaa0df3..a07c98caa66 100644 --- a/test/hotspot/jtreg/runtime/condy/BadBSMUseTest.java +++ b/test/hotspot/jtreg/runtime/condy/BadBSMUseTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -42,7 +42,7 @@ public class BadBSMUseTest { public static void main(String args[]) throws Throwable { // 1. Test a CONSTANT_Dynamic_info's bootstrap_method_attr_index points // at a BSM meant for a CONSTANT_InvokeDynamic_info - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("CondyUsesIndyBSM"); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("CondyUsesIndyBSM"); OutputAnalyzer oa = new OutputAnalyzer(pb.start()); oa.shouldContain("In Indybsm target CallSite method foo"); oa.shouldContain("BootstrapMethodError: bootstrap method initialization exception"); @@ -50,7 +50,7 @@ public static void main(String args[]) throws Throwable { // 2. Test a CONSTANT_InvokeDynamic_info's bootstrap_method_attr_index points // at a BSM meant for a CONSTANT_Dynamic_info - pb = ProcessTools.createJavaProcessBuilder("IndyUsesCondyBSM"); + pb = ProcessTools.createLimitedTestJavaProcessBuilder("IndyUsesCondyBSM"); oa = new OutputAnalyzer(pb.start()); oa.shouldContain("In Condybsm"); oa.shouldContain("BootstrapMethodError: bootstrap method initialization exception"); diff --git a/test/hotspot/jtreg/runtime/condy/CondyLDCTest.java b/test/hotspot/jtreg/runtime/condy/CondyLDCTest.java index ef26a6bf674..22cfb727eb8 100644 --- a/test/hotspot/jtreg/runtime/condy/CondyLDCTest.java +++ b/test/hotspot/jtreg/runtime/condy/CondyLDCTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2023, Oracle and/or its affiliates. All rights reserved. * 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,16 +42,16 @@ public class CondyLDCTest { public static void main(String args[]) throws Throwable { // 1. Test a ldc_w instruction can be used with condy's which generate // loadable constants of the following types: byte, char, short, float, integer, boolean. - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-Xverify:all", - "CondyUseLDC_W"); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-Xverify:all", + "CondyUseLDC_W"); OutputAnalyzer oa = new OutputAnalyzer(pb.start()); oa.shouldNotContain("VerifyError"); oa.shouldHaveExitValue(0); // 2. Test ldc2_w of a condy which returns a dynamically generated // float constant, generates a VerifyError. - pb = ProcessTools.createJavaProcessBuilder("-Xverify:all", - "CondyBadLDC2_W"); + pb = ProcessTools.createLimitedTestJavaProcessBuilder("-Xverify:all", + "CondyBadLDC2_W"); oa = new OutputAnalyzer(pb.start()); oa.shouldContain("java.lang.VerifyError: Illegal type at constant pool entry"); oa.shouldContain("CondyBadLDC2_W.F()F @0: ldc2_w"); @@ -59,8 +59,8 @@ public static void main(String args[]) throws Throwable { // 3. Test a ldc of a condy which returns a dynamically generated // double constant, generates a VerifyError. - pb = ProcessTools.createJavaProcessBuilder("-Xverify:all", - "CondyBadLDC"); + pb = ProcessTools.createLimitedTestJavaProcessBuilder("-Xverify:all", + "CondyBadLDC"); oa = new OutputAnalyzer(pb.start()); oa.shouldContain("java.lang.VerifyError: Illegal type at constant pool entry"); oa.shouldContain("CondyBadLDC.D()D @0: ldc"); diff --git a/test/hotspot/jtreg/runtime/condy/CondyNewInvokeSpecialTest.java b/test/hotspot/jtreg/runtime/condy/CondyNewInvokeSpecialTest.java index 2de9e728666..6e810d0d3b8 100644 --- a/test/hotspot/jtreg/runtime/condy/CondyNewInvokeSpecialTest.java +++ b/test/hotspot/jtreg/runtime/condy/CondyNewInvokeSpecialTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2023, Oracle and/or its affiliates. All rights reserved. * 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,8 +38,8 @@ public class CondyNewInvokeSpecialTest { public static void main(String args[]) throws Throwable { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-Xverify:all", - "CondyNewInvokeSpecial"); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-Xverify:all", + "CondyNewInvokeSpecial"); OutputAnalyzer oa = new OutputAnalyzer(pb.start()); oa.shouldContain("In CondyNewInvokeSpecial method"); oa.shouldHaveExitValue(0); diff --git a/test/hotspot/jtreg/runtime/condy/escapeAnalysis/TestEscapeCondy.java b/test/hotspot/jtreg/runtime/condy/escapeAnalysis/TestEscapeCondy.java index cb4b6960cf9..877a805c445 100644 --- a/test/hotspot/jtreg/runtime/condy/escapeAnalysis/TestEscapeCondy.java +++ b/test/hotspot/jtreg/runtime/condy/escapeAnalysis/TestEscapeCondy.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -43,7 +43,7 @@ public class TestEscapeCondy { public static void main(String args[]) throws Throwable { // 1. Test escape analysis of a method that contains // a ldc instruction of a condy whose return type is an array of boolean - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:CompileCommand=dontinline,runtime.condy.TestEscapeThroughInvokeWithCondy::create", "runtime.condy.TestEscapeThroughInvokeWithCondy"); OutputAnalyzer oa = new OutputAnalyzer(pb.start()); diff --git a/test/hotspot/jtreg/runtime/condy/staticInit/TestInitException.java b/test/hotspot/jtreg/runtime/condy/staticInit/TestInitException.java index c8b8aeba22e..2b572edb66f 100644 --- a/test/hotspot/jtreg/runtime/condy/staticInit/TestInitException.java +++ b/test/hotspot/jtreg/runtime/condy/staticInit/TestInitException.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 2023, Oracle and/or its affiliates. All rights reserved. * 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,7 +38,7 @@ public class TestInitException { public static void main(java.lang.String[] unused) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("Example"); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("Example"); OutputAnalyzer oa = new OutputAnalyzer(pb.start()); // First call stack trace // shouldMatch is used to workaround CODETOOLS-7902686 diff --git a/test/hotspot/jtreg/runtime/contended/Options.java b/test/hotspot/jtreg/runtime/contended/Options.java index ea7261c229a..f646b152921 100644 --- a/test/hotspot/jtreg/runtime/contended/Options.java +++ b/test/hotspot/jtreg/runtime/contended/Options.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2023, Oracle and/or its affiliates. All rights reserved. * 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,59 +40,59 @@ public static void main(String[] args) throws Exception { ProcessBuilder pb; OutputAnalyzer output; - pb = ProcessTools.createJavaProcessBuilder("-XX:ContendedPaddingWidth=-128", "-version"); + pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:ContendedPaddingWidth=-128", "-version"); output = new OutputAnalyzer(pb.start()); output.shouldContain("ContendedPaddingWidth"); output.shouldContain("outside the allowed range"); output.shouldHaveExitValue(1); - pb = ProcessTools.createJavaProcessBuilder("-XX:ContendedPaddingWidth=-8", "-version"); + pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:ContendedPaddingWidth=-8", "-version"); output = new OutputAnalyzer(pb.start()); output.shouldContain("ContendedPaddingWidth"); output.shouldContain("outside the allowed range"); output.shouldHaveExitValue(1); - pb = ProcessTools.createJavaProcessBuilder("-XX:ContendedPaddingWidth=-1", "-version"); + pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:ContendedPaddingWidth=-1", "-version"); output = new OutputAnalyzer(pb.start()); output.shouldContain("ContendedPaddingWidth"); output.shouldContain("outside the allowed range"); output.shouldHaveExitValue(1); - pb = ProcessTools.createJavaProcessBuilder("-XX:ContendedPaddingWidth=0", "-version"); + pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:ContendedPaddingWidth=0", "-version"); output = new OutputAnalyzer(pb.start()); output.shouldHaveExitValue(0); - pb = ProcessTools.createJavaProcessBuilder("-XX:ContendedPaddingWidth=1", "-version"); + pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:ContendedPaddingWidth=1", "-version"); output = new OutputAnalyzer(pb.start()); output.shouldContain("ContendedPaddingWidth"); output.shouldContain("must be a multiple of 8"); output.shouldHaveExitValue(1); - pb = ProcessTools.createJavaProcessBuilder("-XX:ContendedPaddingWidth=8", "-version"); + pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:ContendedPaddingWidth=8", "-version"); output = new OutputAnalyzer(pb.start()); output.shouldHaveExitValue(0); - pb = ProcessTools.createJavaProcessBuilder("-XX:ContendedPaddingWidth=8184", "-version"); // 8192-8 = 8184 + pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:ContendedPaddingWidth=8184", "-version"); // 8192-8 = 8184 output = new OutputAnalyzer(pb.start()); output.shouldHaveExitValue(0); - pb = ProcessTools.createJavaProcessBuilder("-XX:ContendedPaddingWidth=8191", "-version"); + pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:ContendedPaddingWidth=8191", "-version"); output = new OutputAnalyzer(pb.start()); output.shouldContain("ContendedPaddingWidth"); output.shouldContain("must be a multiple of 8"); output.shouldHaveExitValue(1); - pb = ProcessTools.createJavaProcessBuilder("-XX:ContendedPaddingWidth=8192", "-version"); + pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:ContendedPaddingWidth=8192", "-version"); output = new OutputAnalyzer(pb.start()); output.shouldHaveExitValue(0); - pb = ProcessTools.createJavaProcessBuilder("-XX:ContendedPaddingWidth=8193", "-version"); + pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:ContendedPaddingWidth=8193", "-version"); output = new OutputAnalyzer(pb.start()); output.shouldContain("ContendedPaddingWidth"); output.shouldContain("outside the allowed range"); output.shouldHaveExitValue(1); - pb = ProcessTools.createJavaProcessBuilder("-XX:ContendedPaddingWidth=8200", "-version"); // 8192+8 = 8200 + pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:ContendedPaddingWidth=8200", "-version"); // 8192+8 = 8200 output = new OutputAnalyzer(pb.start()); output.shouldContain("ContendedPaddingWidth"); output.shouldContain("outside the allowed range"); diff --git a/test/hotspot/jtreg/runtime/duplAttributes/DuplAttributesTest.java b/test/hotspot/jtreg/runtime/duplAttributes/DuplAttributesTest.java index aebc9d0a899..4116c91705f 100644 --- a/test/hotspot/jtreg/runtime/duplAttributes/DuplAttributesTest.java +++ b/test/hotspot/jtreg/runtime/duplAttributes/DuplAttributesTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2023, Oracle and/or its affiliates. All rights reserved. * 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,7 +41,7 @@ public class DuplAttributesTest { static final String testsrc = System.getProperty("test.src"); public static void runTest(String test, String result) throws Throwable { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(test); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(test); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldContain("java.lang.ClassFormatError: Multiple " + result); output.shouldNotHaveExitValue(0); diff --git a/test/hotspot/jtreg/runtime/execstack/Testexecstack.java b/test/hotspot/jtreg/runtime/execstack/Testexecstack.java index 7af23d7a41e..3c690d54a23 100644 --- a/test/hotspot/jtreg/runtime/execstack/Testexecstack.java +++ b/test/hotspot/jtreg/runtime/execstack/Testexecstack.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2023, Oracle and/or its affiliates. All rights reserved. * 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 static void main(String[] args) throws Throwable { // Create a new java process for the Test Java/JNI test without // an executeable stack - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-Djava.library.path=" + libpath + ":.", "Test", "test-rw"); // Start the process and check the output @@ -56,7 +56,7 @@ public static void main(String[] args) throws Throwable { // Create a new java process for the Test Java/JNI test with an // executable stack - pb = ProcessTools.createJavaProcessBuilder( + pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-Djava.library.path=" + libpath + ":.", "Test", "test-rwx"); // Start the process and check the output @@ -65,7 +65,7 @@ public static void main(String[] args) throws Throwable { // Create a new java process for the TestMT Java/JNI test with an // executable stack - pb = ProcessTools.createJavaProcessBuilder( + pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-Djava.library.path=" + libpath + ":.", "TestMT", "test-rwx"); // Start the process and check the output diff --git a/test/hotspot/jtreg/runtime/getSysPackage/GetPackageXbootclasspath.java b/test/hotspot/jtreg/runtime/getSysPackage/GetPackageXbootclasspath.java index c1767871b72..c146da15f2b 100644 --- a/test/hotspot/jtreg/runtime/getSysPackage/GetPackageXbootclasspath.java +++ b/test/hotspot/jtreg/runtime/getSysPackage/GetPackageXbootclasspath.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -53,7 +53,7 @@ public static void main(String args[]) throws Exception { ClassFileInstaller.writeClassToDisk("P/Test", InMemoryJavaCompiler.compile("P.Test", Test_src), test_classes); - new OutputAnalyzer(ProcessTools.createJavaProcessBuilder( + new OutputAnalyzer(ProcessTools.createLimitedTestJavaProcessBuilder( "-Xbootclasspath/a:" + test_classes, "P.Test") .start()).shouldContain("Test Passed") .shouldHaveExitValue(0); diff --git a/test/hotspot/jtreg/runtime/getSysPackage/GetSysPkgTest.java b/test/hotspot/jtreg/runtime/getSysPackage/GetSysPkgTest.java index bd6dc9ff0c6..5d89e6c9fbd 100644 --- a/test/hotspot/jtreg/runtime/getSysPackage/GetSysPkgTest.java +++ b/test/hotspot/jtreg/runtime/getSysPackage/GetSysPkgTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -100,7 +100,7 @@ public static void main(String args[]) throws Throwable { InMemoryJavaCompiler.compile("GetSysPkg_package.GetSysClass", source); ClassFileInstaller.writeClassToDisk("GetSysPkg_package/GetSysClass", klassbuf); - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-Xbootclasspath/a:bl_dir", + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-Xbootclasspath/a:bl_dir", "--add-opens=java.base/jdk.internal.loader=ALL-UNNAMED", "-cp", "." + File.pathSeparator + System.getProperty("test.classes"), "GetSysPkgTest", "do_tests"); OutputAnalyzer output = new OutputAnalyzer(pb.start()); diff --git a/test/hotspot/jtreg/runtime/handshake/HandshakeTimeoutTest.java b/test/hotspot/jtreg/runtime/handshake/HandshakeTimeoutTest.java index b92ff56da9a..a1a5ff68c31 100644 --- a/test/hotspot/jtreg/runtime/handshake/HandshakeTimeoutTest.java +++ b/test/hotspot/jtreg/runtime/handshake/HandshakeTimeoutTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2021, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -42,7 +42,7 @@ public class HandshakeTimeoutTest { public static void main(String[] args) throws Exception { ProcessBuilder pb = - ProcessTools.createTestJvm( + ProcessTools.createTestJavaProcessBuilder( "-Xbootclasspath/a:.", "-XX:+UnlockDiagnosticVMOptions", "-XX:+WhiteBoxAPI", diff --git a/test/hotspot/jtreg/runtime/handshake/HandshakeTransitionTest.java b/test/hotspot/jtreg/runtime/handshake/HandshakeTransitionTest.java index c8b67b5131b..e14dabbe5ea 100644 --- a/test/hotspot/jtreg/runtime/handshake/HandshakeTransitionTest.java +++ b/test/hotspot/jtreg/runtime/handshake/HandshakeTransitionTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2023, Oracle and/or its affiliates. All rights reserved. * 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,7 +40,7 @@ public class HandshakeTransitionTest { public static void main(String[] args) throws Exception { ProcessBuilder pb = - ProcessTools.createTestJvm( + ProcessTools.createTestJavaProcessBuilder( "-Djava.library.path=" + Utils.TEST_NATIVE_PATH, "-XX:+SafepointALot", "-XX:+HandshakeALot", diff --git a/test/hotspot/jtreg/runtime/jni/checked/TestCheckedReleaseArrayElements.java b/test/hotspot/jtreg/runtime/jni/checked/TestCheckedReleaseArrayElements.java index 1e5145feca5..d8bbe0659c2 100644 --- a/test/hotspot/jtreg/runtime/jni/checked/TestCheckedReleaseArrayElements.java +++ b/test/hotspot/jtreg/runtime/jni/checked/TestCheckedReleaseArrayElements.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2021, 2023, Oracle and/or its affiliates. All rights reserved. * 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,9 +47,9 @@ public static void main(String[] args) throws Throwable { // Uses executeProcess() instead of executeTestJvm() to avoid passing options // that might generate output on stderr (which should be empty for this test). ProcessBuilder pb = - ProcessTools.createJavaProcessBuilder("-Xcheck:jni", - "-Djava.library.path=" + Utils.TEST_NATIVE_PATH, - "TestCheckedReleaseArrayElements"); + ProcessTools.createLimitedTestJavaProcessBuilder("-Xcheck:jni", + "-Djava.library.path=" + Utils.TEST_NATIVE_PATH, + "TestCheckedReleaseArrayElements"); OutputAnalyzer output = ProcessTools.executeProcess(pb); output.shouldHaveExitValue(0); output.stderrShouldBeEmpty(); diff --git a/test/hotspot/jtreg/runtime/jsig/Testjsig.java b/test/hotspot/jtreg/runtime/jsig/Testjsig.java index 315ec3d1500..6e287a6cdc1 100644 --- a/test/hotspot/jtreg/runtime/jsig/Testjsig.java +++ b/test/hotspot/jtreg/runtime/jsig/Testjsig.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2023, Oracle and/or its affiliates. All rights reserved. * 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 static void main(String[] args) throws Throwable { String libpath = System.getProperty("java.library.path"); // Create a new java process for the TestJNI Java/JNI test - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-Djava.library.path=" + libpath + ":.", "TestJNI", "100"); diff --git a/test/hotspot/jtreg/runtime/logging/BiasedLockingTest.java b/test/hotspot/jtreg/runtime/logging/BiasedLockingTest.java index df4486efbf7..962e14613a6 100644 --- a/test/hotspot/jtreg/runtime/logging/BiasedLockingTest.java +++ b/test/hotspot/jtreg/runtime/logging/BiasedLockingTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2024, Oracle and/or its affiliates. All rights reserved. * 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,16 +48,16 @@ static void analyzeOutputOff(ProcessBuilder pb) throws Exception { } public static void main(String[] args) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-XX:+UseBiasedLocking", - "-Xlog:biasedlocking", - "-XX:BiasedLockingStartupDelay=0", - InnerClass.class.getName()); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:+UseBiasedLocking", + "-Xlog:biasedlocking", + "-XX:BiasedLockingStartupDelay=0", + InnerClass.class.getName()); analyzeOutputOn(pb); - pb = ProcessTools.createJavaProcessBuilder("-XX:+UseBiasedLocking", - "-Xlog:biasedlocking=off", - "-XX:BiasedLockingStartupDelay=0", - InnerClass.class.getName()); + pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:+UseBiasedLocking", + "-Xlog:biasedlocking=off", + "-XX:BiasedLockingStartupDelay=0", + InnerClass.class.getName()); analyzeOutputOff(pb); } diff --git a/test/hotspot/jtreg/runtime/logging/ClassInitializationTest.java b/test/hotspot/jtreg/runtime/logging/ClassInitializationTest.java index e4153a8f392..7b0d1dcf859 100644 --- a/test/hotspot/jtreg/runtime/logging/ClassInitializationTest.java +++ b/test/hotspot/jtreg/runtime/logging/ClassInitializationTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2023, Oracle and/or its affiliates. All rights reserved. * 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,10 +41,10 @@ public class ClassInitializationTest { public static void main(String... args) throws Exception { // (1) - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-Xlog:class+init=info", - "-Xverify:all", - "-Xmx128m", - "BadMap50"); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-Xlog:class+init=info", + "-Xverify:all", + "-Xmx128m", + "BadMap50"); OutputAnalyzer out = new OutputAnalyzer(pb.start()); out.shouldNotHaveExitValue(0); out.shouldContain("Start class verification for:"); @@ -55,21 +55,21 @@ public static void main(String... args) throws Exception { // (2) if (Platform.isDebugBuild()) { - pb = ProcessTools.createJavaProcessBuilder("-Xlog:class+init=info", - "-Xverify:all", - "-XX:+EagerInitialization", - "-Xmx128m", - InnerClass.class.getName()); + pb = ProcessTools.createLimitedTestJavaProcessBuilder("-Xlog:class+init=info", + "-Xverify:all", + "-XX:+EagerInitialization", + "-Xmx128m", + InnerClass.class.getName()); out = new OutputAnalyzer(pb.start()); out.shouldContain("[Initialized").shouldContain("without side effects]"); out.shouldHaveExitValue(0); } // (3) class+init should turn off. - pb = ProcessTools.createJavaProcessBuilder("-Xlog:class+init=off", - "-Xverify:all", - "-Xmx128m", - "BadMap50"); + pb = ProcessTools.createLimitedTestJavaProcessBuilder("-Xlog:class+init=off", + "-Xverify:all", + "-Xmx128m", + "BadMap50"); out = new OutputAnalyzer(pb.start()); out.shouldNotHaveExitValue(0); out.shouldNotContain("[class,init]"); diff --git a/test/hotspot/jtreg/runtime/logging/ClassLoadUnloadTest.java b/test/hotspot/jtreg/runtime/logging/ClassLoadUnloadTest.java index 74af1dfc9e8..ea17cad78dd 100644 --- a/test/hotspot/jtreg/runtime/logging/ClassLoadUnloadTest.java +++ b/test/hotspot/jtreg/runtime/logging/ClassLoadUnloadTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -30,6 +30,8 @@ * @library /test/lib * @library classes * @build test.Empty + * @build jdk.test.whitebox.WhiteBox + * @run driver jdk.test.lib.helpers.ClassFileInstaller jdk.test.whitebox.WhiteBox * @run driver ClassLoadUnloadTest */ @@ -68,11 +70,14 @@ static void checkAbsent(OutputAnalyzer output, String... outputStrings) throws E // Use the same command-line heap size setting as ../ClassUnload/UnloadTest.java static OutputAnalyzer exec(String... args) throws Exception { + String classPath = System.getProperty("test.class.path", "."); + + // Sub-process does not get all the properties automatically, so the test class path needs to be passed explicitly List argsList = new ArrayList<>(); Collections.addAll(argsList, args); - Collections.addAll(argsList, "-Xmn8m", "-Dtest.class.path=" + System.getProperty("test.class.path", "."), - "-XX:+ClassUnloading", ClassUnloadTestMain.class.getName()); - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(argsList); + Collections.addAll(argsList, "-Xmn8m", "-Xbootclasspath/a:.", "-XX:+UnlockDiagnosticVMOptions", + "-XX:+WhiteBoxAPI", "-XX:+ClassUnloading", "-Dtest.class.path=" + classPath, ClassUnloadTestMain.class.getName()); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(argsList); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldHaveExitValue(0); return output; @@ -84,7 +89,7 @@ public static void main(String... args) throws Exception { // -Xlog:class+unload=info output = exec("-Xlog:class+unload=info"); - checkFor(output, "[class,unload]", "unloading class"); + checkFor(output, "[class,unload]", "unloading class test.Empty"); // -Xlog:class+unload=off output = exec("-Xlog:class+unload=off"); diff --git a/test/hotspot/jtreg/runtime/logging/ClassResolutionTest.java b/test/hotspot/jtreg/runtime/logging/ClassResolutionTest.java index 05155e5108f..129d34bd2db 100644 --- a/test/hotspot/jtreg/runtime/logging/ClassResolutionTest.java +++ b/test/hotspot/jtreg/runtime/logging/ClassResolutionTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2023, Oracle and/or its affiliates. All rights reserved. * 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,17 +60,17 @@ public static void main(String... args) throws Exception { public static void main(String... args) throws Exception { // (1) class+resolve should turn on. - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-Xlog:class+resolve=debug", - ClassResolutionTestMain.class.getName()); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-Xlog:class+resolve=debug", + ClassResolutionTestMain.class.getName()); OutputAnalyzer o = new OutputAnalyzer(pb.start()); o.shouldHaveExitValue(0); o.shouldContain("[class,resolve] ClassResolutionTest$ClassResolutionTestMain$Thing1Handler ClassResolutionTest$ClassResolutionTestMain$Thing1"); o.shouldContain("[class,resolve] resolve JVM_CONSTANT_MethodHandle"); // (2) class+resolve should turn off. - pb = ProcessTools.createJavaProcessBuilder("-Xlog:class+resolve=debug", - "-Xlog:class+resolve=off", - ClassResolutionTestMain.class.getName()); + pb = ProcessTools.createLimitedTestJavaProcessBuilder("-Xlog:class+resolve=debug", + "-Xlog:class+resolve=off", + ClassResolutionTestMain.class.getName()); o = new OutputAnalyzer(pb.start()); o.shouldHaveExitValue(0); o.shouldNotContain("[class,resolve]"); diff --git a/test/hotspot/jtreg/runtime/logging/CompressedOopsTest.java b/test/hotspot/jtreg/runtime/logging/CompressedOopsTest.java index ee1a4997900..79167f581e7 100644 --- a/test/hotspot/jtreg/runtime/logging/CompressedOopsTest.java +++ b/test/hotspot/jtreg/runtime/logging/CompressedOopsTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -51,20 +51,20 @@ static void analyzeOutputOff(ProcessBuilder pb) throws Exception { } public static void main(String[] args) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-XX:+UseCompressedOops", - "-Xlog:gc+heap+coops=debug", - InnerClass.class.getName()); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:+UseCompressedOops", + "-Xlog:gc+heap+coops=debug", + InnerClass.class.getName()); analyzeOutputOn(pb); - pb = ProcessTools.createJavaProcessBuilder("-XX:+UseCompressedOops", - "-Xlog:gc+heap+coops", - InnerClass.class.getName()); + pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:+UseCompressedOops", + "-Xlog:gc+heap+coops", + InnerClass.class.getName()); // No coops logging on info level. analyzeOutputOff(pb); - pb = ProcessTools.createJavaProcessBuilder("-XX:+UseCompressedOops", - "-Xlog:gc+heap+coops=off", - InnerClass.class.getName()); + pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:+UseCompressedOops", + "-Xlog:gc+heap+coops=off", + InnerClass.class.getName()); analyzeOutputOff(pb); } diff --git a/test/hotspot/jtreg/runtime/logging/CondyIndyTest.java b/test/hotspot/jtreg/runtime/logging/CondyIndyTest.java index f94f5e5cb20..c62402c918b 100644 --- a/test/hotspot/jtreg/runtime/logging/CondyIndyTest.java +++ b/test/hotspot/jtreg/runtime/logging/CondyIndyTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2020, 2023, Oracle and/or its affiliates. All rights reserved. * 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,8 +40,8 @@ public class CondyIndyTest { public static void main(String... args) throws Exception { // (1) methodhandles should turn on, no indy, no condy - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-Xlog:methodhandles", - "CondyIndy"); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-Xlog:methodhandles", + "CondyIndy"); OutputAnalyzer o = new OutputAnalyzer(pb.start()); o.shouldHaveExitValue(0); o.shouldContain("[info][methodhandles"); @@ -49,8 +49,8 @@ public static void main(String... args) throws Exception { o.shouldNotContain("[debug][methodhandles,condy"); // (2) methodhandles+condy=debug only - pb = ProcessTools.createJavaProcessBuilder("-Xlog:methodhandles+condy=debug", - "CondyIndy"); + pb = ProcessTools.createLimitedTestJavaProcessBuilder("-Xlog:methodhandles+condy=debug", + "CondyIndy"); o = new OutputAnalyzer(pb.start()); o.shouldHaveExitValue(0); o.shouldNotContain("[info ][methodhandles"); @@ -58,8 +58,8 @@ public static void main(String... args) throws Exception { o.shouldContain("[debug][methodhandles,condy"); // (3) methodhandles+indy=debug only - pb = ProcessTools.createJavaProcessBuilder("-Xlog:methodhandles+indy=debug", - "CondyIndy"); + pb = ProcessTools.createLimitedTestJavaProcessBuilder("-Xlog:methodhandles+indy=debug", + "CondyIndy"); o = new OutputAnalyzer(pb.start()); o.shouldHaveExitValue(0); o.shouldNotContain("[info ][methodhandles"); @@ -67,10 +67,10 @@ public static void main(String... args) throws Exception { o.shouldNotContain("[debug][methodhandles,condy"); // (4) methodhandles, condy, indy all on - pb = ProcessTools.createJavaProcessBuilder("-Xlog:methodhandles=info", - "-Xlog:methodhandles+condy=debug", - "-Xlog:methodhandles+indy=debug", - "CondyIndy"); + pb = ProcessTools.createLimitedTestJavaProcessBuilder("-Xlog:methodhandles=info", + "-Xlog:methodhandles+condy=debug", + "-Xlog:methodhandles+indy=debug", + "CondyIndy"); o = new OutputAnalyzer(pb.start()); o.shouldHaveExitValue(0); o.shouldContain("[info ][methodhandles"); diff --git a/test/hotspot/jtreg/runtime/logging/DefaultMethodsTest.java b/test/hotspot/jtreg/runtime/logging/DefaultMethodsTest.java index 2ea7e6bb07a..d41d6685c23 100644 --- a/test/hotspot/jtreg/runtime/logging/DefaultMethodsTest.java +++ b/test/hotspot/jtreg/runtime/logging/DefaultMethodsTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2023, Oracle and/or its affiliates. All rights reserved. * 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,8 +37,8 @@ public class DefaultMethodsTest { public static void main(String[] args) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-Xlog:defaultmethods=debug", - InnerClass.class.getName()); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-Xlog:defaultmethods=debug", + InnerClass.class.getName()); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldContain("Slots that need filling:"); output.shouldContain("requires default method processing"); diff --git a/test/hotspot/jtreg/runtime/logging/ExceptionsTest.java b/test/hotspot/jtreg/runtime/logging/ExceptionsTest.java index 976478253ee..327b1cc0f24 100644 --- a/test/hotspot/jtreg/runtime/logging/ExceptionsTest.java +++ b/test/hotspot/jtreg/runtime/logging/ExceptionsTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2023, Oracle and/or its affiliates. All rights reserved. * 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,25 +57,25 @@ static void analyzeOutputOff(ProcessBuilder pb) throws Exception { } public static void main(String[] args) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-Xlog:exceptions=info", - InternalClass.class.getName()); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-Xlog:exceptions=info", + InternalClass.class.getName()); analyzeOutputOn(pb); - pb = ProcessTools.createJavaProcessBuilder("-Xlog:exceptions=off", - InternalClass.class.getName()); + pb = ProcessTools.createLimitedTestJavaProcessBuilder("-Xlog:exceptions=off", + InternalClass.class.getName()); analyzeOutputOff(pb); - pb = ProcessTools.createJavaProcessBuilder(InternalClass.class.getName()); + pb = ProcessTools.createLimitedTestJavaProcessBuilder(InternalClass.class.getName()); updateEnvironment(pb, "_JAVA_OPTIONS", "-Xlog:exceptions=info"); analyzeOutputOn(pb); - pb = ProcessTools.createJavaProcessBuilder(InternalClass.class.getName()); + pb = ProcessTools.createLimitedTestJavaProcessBuilder(InternalClass.class.getName()); updateEnvironment(pb, "JAVA_TOOL_OPTIONS", "-Xlog:exceptions=info -Xlog:exceptions=off"); analyzeOutputOff(pb); - pb = ProcessTools.createJavaProcessBuilder("-XX:VMOptionsFile=" + System.getProperty("test.src", ".") - + File.separator + "ExceptionsTest_options_file", - InternalClass.class.getName()); + pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:VMOptionsFile=" + System.getProperty("test.src", ".") + + File.separator + "ExceptionsTest_options_file", + InternalClass.class.getName()); analyzeOutputOn(pb); } diff --git a/test/hotspot/jtreg/runtime/logging/ItablesTest.java b/test/hotspot/jtreg/runtime/logging/ItablesTest.java index 009986285a4..6869e5b2917 100644 --- a/test/hotspot/jtreg/runtime/logging/ItablesTest.java +++ b/test/hotspot/jtreg/runtime/logging/ItablesTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2023, Oracle and/or its affiliates. All rights reserved. * 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,7 +41,7 @@ public class ItablesTest { public static void main(String[] args) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-Xlog:itables=trace", "ClassB"); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-Xlog:itables=trace", "ClassB"); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldContain(": Initializing itables for ClassB"); output.shouldContain(": Initializing itable indices for interface "); @@ -53,7 +53,7 @@ public static void main(String[] args) throws Exception { output.shouldContain("invokeinterface selected method: receiver-class"); output.shouldHaveExitValue(0); - pb = ProcessTools.createJavaProcessBuilder("-Xlog:itables=trace", "ItablesVtableTest"); + pb = ProcessTools.createLimitedTestJavaProcessBuilder("-Xlog:itables=trace", "ItablesVtableTest"); output = new OutputAnalyzer(pb.start()); output.shouldContain("vtable index "); output.shouldHaveExitValue(0); diff --git a/test/hotspot/jtreg/runtime/logging/LoaderConstraintsTest.java b/test/hotspot/jtreg/runtime/logging/LoaderConstraintsTest.java index eb7f0e1867b..39ad3b872a2 100644 --- a/test/hotspot/jtreg/runtime/logging/LoaderConstraintsTest.java +++ b/test/hotspot/jtreg/runtime/logging/LoaderConstraintsTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -29,6 +29,8 @@ * @modules java.base/jdk.internal.misc * @library /test/lib classes * @build test.Empty + * @build jdk.test.whitebox.WhiteBox + * @run driver jdk.test.lib.helpers.ClassFileInstaller jdk.test.whitebox.WhiteBox * @run driver LoaderConstraintsTest */ @@ -60,9 +62,11 @@ static ProcessBuilder exec(String... args) throws Exception { List argsList = new ArrayList<>(); Collections.addAll(argsList, args); Collections.addAll(argsList, "-Xmn8m"); - Collections.addAll(argsList, "-Dtest.classes=" + System.getProperty("test.classes",".")); + Collections.addAll(argsList, "-Xbootclasspath/a:."); + Collections.addAll(argsList, "-XX:+UnlockDiagnosticVMOptions"); + Collections.addAll(argsList, "-XX:+WhiteBoxAPI"); Collections.addAll(argsList, ClassUnloadTestMain.class.getName()); - return ProcessTools.createJavaProcessBuilder(argsList); + return ProcessTools.createLimitedTestJavaProcessBuilder(argsList); } public static void main(String... args) throws Exception { diff --git a/test/hotspot/jtreg/runtime/logging/ModulesTest.java b/test/hotspot/jtreg/runtime/logging/ModulesTest.java index 5d30fa3a6a4..96292b1d5d2 100644 --- a/test/hotspot/jtreg/runtime/logging/ModulesTest.java +++ b/test/hotspot/jtreg/runtime/logging/ModulesTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -75,7 +75,7 @@ static void testModuleUnload(String... args) throws Exception { } static OutputAnalyzer run(String... args) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(args); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(args); return new OutputAnalyzer(pb.start()); } } diff --git a/test/hotspot/jtreg/runtime/logging/MonitorInflationTest.java b/test/hotspot/jtreg/runtime/logging/MonitorInflationTest.java index 85f025469b4..737c64621e8 100644 --- a/test/hotspot/jtreg/runtime/logging/MonitorInflationTest.java +++ b/test/hotspot/jtreg/runtime/logging/MonitorInflationTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -51,12 +51,12 @@ static void analyzeOutputOff(ProcessBuilder pb) throws Exception { } public static void main(String[] args) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-Xlog:monitorinflation=trace", - InnerClass.class.getName()); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-Xlog:monitorinflation=trace", + InnerClass.class.getName()); analyzeOutputOn(pb); - pb = ProcessTools.createJavaProcessBuilder("-Xlog:monitorinflation=off", - InnerClass.class.getName()); + pb = ProcessTools.createLimitedTestJavaProcessBuilder("-Xlog:monitorinflation=off", + InnerClass.class.getName()); analyzeOutputOff(pb); } diff --git a/test/hotspot/jtreg/runtime/logging/MonitorMismatchTest.java b/test/hotspot/jtreg/runtime/logging/MonitorMismatchTest.java index ac54ab8c2ca..c3b9198b398 100644 --- a/test/hotspot/jtreg/runtime/logging/MonitorMismatchTest.java +++ b/test/hotspot/jtreg/runtime/logging/MonitorMismatchTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2023, Oracle and/or its affiliates. All rights reserved. * 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,19 +40,19 @@ public class MonitorMismatchTest { public static void main(String... args) throws Exception { // monitormismatch should turn on. - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-Xcomp", - "-XX:+TieredCompilation", - "-Xlog:monitormismatch=info", - "MonitorMismatchHelper"); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-Xcomp", + "-XX:+TieredCompilation", + "-Xlog:monitormismatch=info", + "MonitorMismatchHelper"); OutputAnalyzer o = new OutputAnalyzer(pb.start()); o.shouldHaveExitValue(0); o.shouldContain("[monitormismatch] Monitor mismatch in method"); // monitormismatch should turn off. - pb = ProcessTools.createJavaProcessBuilder("-Xcomp", - "-XX:+TieredCompilation", - "-Xlog:monitormismatch=off", - "MonitorMismatchHelper"); + pb = ProcessTools.createLimitedTestJavaProcessBuilder("-Xcomp", + "-XX:+TieredCompilation", + "-Xlog:monitormismatch=off", + "MonitorMismatchHelper"); o = new OutputAnalyzer(pb.start()); o.shouldHaveExitValue(0); o.shouldNotContain("[monitormismatch]"); diff --git a/test/hotspot/jtreg/runtime/logging/OsCpuLoggingTest.java b/test/hotspot/jtreg/runtime/logging/OsCpuLoggingTest.java index bf6e3faed59..a1141964f38 100644 --- a/test/hotspot/jtreg/runtime/logging/OsCpuLoggingTest.java +++ b/test/hotspot/jtreg/runtime/logging/OsCpuLoggingTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -52,14 +52,14 @@ static void analyzeOutputForOsCpuLog(OutputAnalyzer output) throws Exception { public static void main(String[] args) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-Xlog:os+cpu", "-version"); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-Xlog:os+cpu", "-version"); OutputAnalyzer output = new OutputAnalyzer(pb.start()); analyzeOutputForOsCpuLog(output); // PPC64 only uses polling pages when UseSIGTRAP is off. pb = (Platform.isPPC() && Platform.is64bit()) - ? ProcessTools.createJavaProcessBuilder("-Xlog:os", "-XX:-UseSIGTRAP", "-version") - : ProcessTools.createJavaProcessBuilder("-Xlog:os", "-version"); + ? ProcessTools.createLimitedTestJavaProcessBuilder("-Xlog:os", "-XX:-UseSIGTRAP", "-version") + : ProcessTools.createLimitedTestJavaProcessBuilder("-Xlog:os", "-version"); output = new OutputAnalyzer(pb.start()); analyzeOutputForOsLog(output); } diff --git a/test/hotspot/jtreg/runtime/logging/ProtectionDomainVerificationTest.java b/test/hotspot/jtreg/runtime/logging/ProtectionDomainVerificationTest.java index 9d89de8b67b..c99429519e0 100644 --- a/test/hotspot/jtreg/runtime/logging/ProtectionDomainVerificationTest.java +++ b/test/hotspot/jtreg/runtime/logging/ProtectionDomainVerificationTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2023, Oracle and/or its affiliates. All rights reserved. * 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,30 +39,30 @@ public class ProtectionDomainVerificationTest { public static void main(String... args) throws Exception { // -Xlog:protectiondomain=trace - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-Xlog:protectiondomain=trace", - "-Xmx128m", - "-Djava.security.manager=allow", - Hello.class.getName(), "security_manager"); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-Xlog:protectiondomain=trace", + "-Xmx128m", + "-Djava.security.manager=allow", + Hello.class.getName(), "security_manager"); new OutputAnalyzer(pb.start()) .shouldHaveExitValue(0) .shouldContain("[protectiondomain] Checking package access") .shouldContain("[protectiondomain] adding protection domain for class"); // -Xlog:protectiondomain=debug - pb = ProcessTools.createJavaProcessBuilder("-Xlog:protectiondomain=debug", - "-Xmx128m", - "-Djava.security.manager=allow", - Hello.class.getName(), "security_manager"); + pb = ProcessTools.createLimitedTestJavaProcessBuilder("-Xlog:protectiondomain=debug", + "-Xmx128m", + "-Djava.security.manager=allow", + Hello.class.getName(), "security_manager"); new OutputAnalyzer(pb.start()) .shouldHaveExitValue(0) .shouldContain("[protectiondomain] Checking package access") .shouldNotContain("[protectiondomain] adding protection domain for class"); // -Xlog:protectiondomain=debug - pb = ProcessTools.createJavaProcessBuilder("-Xlog:protectiondomain=trace", - "-Xmx128m", - "-Djava.security.manager=disallow", - Hello.class.getName()); + pb = ProcessTools.createLimitedTestJavaProcessBuilder("-Xlog:protectiondomain=trace", + "-Xmx128m", + "-Djava.security.manager=disallow", + Hello.class.getName()); new OutputAnalyzer(pb.start()) .shouldHaveExitValue(0) .shouldNotContain("[protectiondomain] Checking package access") diff --git a/test/hotspot/jtreg/runtime/logging/SafepointCleanupTest.java b/test/hotspot/jtreg/runtime/logging/SafepointCleanupTest.java index 82859b38f15..d4ec877f19b 100644 --- a/test/hotspot/jtreg/runtime/logging/SafepointCleanupTest.java +++ b/test/hotspot/jtreg/runtime/logging/SafepointCleanupTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -51,12 +51,12 @@ static void analyzeOutputOff(ProcessBuilder pb) throws Exception { } public static void main(String[] args) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-Xlog:safepoint+cleanup=info", - InnerClass.class.getName()); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-Xlog:safepoint+cleanup=info", + InnerClass.class.getName()); analyzeOutputOn(pb); - pb = ProcessTools.createJavaProcessBuilder("-Xlog:safepoint+cleanup=off", - InnerClass.class.getName()); + pb = ProcessTools.createLimitedTestJavaProcessBuilder("-Xlog:safepoint+cleanup=off", + InnerClass.class.getName()); analyzeOutputOff(pb); } diff --git a/test/hotspot/jtreg/runtime/logging/SafepointTest.java b/test/hotspot/jtreg/runtime/logging/SafepointTest.java index b79a46ca686..58d02b64660 100644 --- a/test/hotspot/jtreg/runtime/logging/SafepointTest.java +++ b/test/hotspot/jtreg/runtime/logging/SafepointTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2023, Oracle and/or its affiliates. All rights reserved. * 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,8 +38,8 @@ public class SafepointTest { public static void main(String[] args) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-Xlog:safepoint=trace", - InnerClass.class.getName()); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-Xlog:safepoint=trace", + InnerClass.class.getName()); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldContain("Safepoint synchronization initiated"); output.shouldHaveExitValue(0); diff --git a/test/hotspot/jtreg/runtime/logging/StackWalkTest.java b/test/hotspot/jtreg/runtime/logging/StackWalkTest.java index b72358842d9..226dac6f466 100644 --- a/test/hotspot/jtreg/runtime/logging/StackWalkTest.java +++ b/test/hotspot/jtreg/runtime/logging/StackWalkTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2023, Oracle and/or its affiliates. All rights reserved. * 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,12 +49,12 @@ static void analyzeOutputOff(ProcessBuilder pb) throws Exception { } public static void main(String... args) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-Xlog:stackwalk=debug", - InnerClass.class.getName()); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-Xlog:stackwalk=debug", + InnerClass.class.getName()); analyzeOutputOn(pb); - pb = ProcessTools.createJavaProcessBuilder("-Xlog:stackwalk=off", - InnerClass.class.getName()); + pb = ProcessTools.createLimitedTestJavaProcessBuilder("-Xlog:stackwalk=off", + InnerClass.class.getName()); analyzeOutputOff(pb); } diff --git a/test/hotspot/jtreg/runtime/logging/StartupTimeTest.java b/test/hotspot/jtreg/runtime/logging/StartupTimeTest.java index 2066331cb77..88ec76efd12 100644 --- a/test/hotspot/jtreg/runtime/logging/StartupTimeTest.java +++ b/test/hotspot/jtreg/runtime/logging/StartupTimeTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -52,12 +52,12 @@ static void analyzeOutputOff(ProcessBuilder pb) throws Exception { } public static void main(String[] args) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-Xlog:startuptime", - InnerClass.class.getName()); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-Xlog:startuptime", + InnerClass.class.getName()); analyzeOutputOn(pb); - pb = ProcessTools.createJavaProcessBuilder("-Xlog:startuptime=off", - InnerClass.class.getName()); + pb = ProcessTools.createLimitedTestJavaProcessBuilder("-Xlog:startuptime=off", + InnerClass.class.getName()); analyzeOutputOff(pb); } diff --git a/test/hotspot/jtreg/runtime/logging/ThreadLoggingTest.java b/test/hotspot/jtreg/runtime/logging/ThreadLoggingTest.java index 82a189a92cb..ee0082876f9 100644 --- a/test/hotspot/jtreg/runtime/logging/ThreadLoggingTest.java +++ b/test/hotspot/jtreg/runtime/logging/ThreadLoggingTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2023, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2016 SAP SE and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -56,11 +56,11 @@ static void analyzeOutputForDebugLevel(OutputAnalyzer output) throws Exception { public static void main(String[] args) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-Xlog:os+thread", "-version"); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-Xlog:os+thread", "-version"); OutputAnalyzer output = new OutputAnalyzer(pb.start()); analyzeOutputForInfoLevel(output); - pb = ProcessTools.createJavaProcessBuilder("-Xlog:os+thread=debug", "-version"); + pb = ProcessTools.createLimitedTestJavaProcessBuilder("-Xlog:os+thread=debug", "-version"); output = new OutputAnalyzer(pb.start()); analyzeOutputForDebugLevel(output); output.reportDiagnosticSummary(); diff --git a/test/hotspot/jtreg/runtime/logging/VMOperationTest.java b/test/hotspot/jtreg/runtime/logging/VMOperationTest.java index 873ed6e6792..014db904235 100644 --- a/test/hotspot/jtreg/runtime/logging/VMOperationTest.java +++ b/test/hotspot/jtreg/runtime/logging/VMOperationTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2023, Oracle and/or its affiliates. All rights reserved. * 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,10 @@ public class VMOperationTest { public static void main(String[] args) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-Xlog:vmoperation=debug", - "-Xmx128m", - "-Xms128m", - InternalClass.class.getName()); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-Xlog:vmoperation=debug", + "-Xmx128m", + "-Xms128m", + InternalClass.class.getName()); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldContain("VM_Operation ("); output.shouldHaveExitValue(0); diff --git a/test/hotspot/jtreg/runtime/logging/VerificationTest.java b/test/hotspot/jtreg/runtime/logging/VerificationTest.java index 0a7f01f86b7..a6a0ee66acc 100644 --- a/test/hotspot/jtreg/runtime/logging/VerificationTest.java +++ b/test/hotspot/jtreg/runtime/logging/VerificationTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2023, Oracle and/or its affiliates. All rights reserved. * 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,17 +63,17 @@ static void analyzeOutputOff(ProcessBuilder pb) throws Exception { } public static void main(String[] args) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-Xlog:verification=info", - InternalClass.class.getName()); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-Xlog:verification=info", + InternalClass.class.getName()); analyzeOutputOn(pb, true); - pb = ProcessTools.createJavaProcessBuilder("-Xlog:verification=off", - InternalClass.class.getName()); + pb = ProcessTools.createLimitedTestJavaProcessBuilder("-Xlog:verification=off", + InternalClass.class.getName()); analyzeOutputOff(pb); // logging level 'debug' should output stackmaps and bytecode data. - pb = ProcessTools.createJavaProcessBuilder("-Xlog:verification=debug", - InternalClass.class.getName()); + pb = ProcessTools.createLimitedTestJavaProcessBuilder("-Xlog:verification=debug", + InternalClass.class.getName()); analyzeOutputOn(pb, false); } diff --git a/test/hotspot/jtreg/runtime/logging/VtablesTest.java b/test/hotspot/jtreg/runtime/logging/VtablesTest.java index bc525cf2534..a07fe895173 100644 --- a/test/hotspot/jtreg/runtime/logging/VtablesTest.java +++ b/test/hotspot/jtreg/runtime/logging/VtablesTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -44,7 +44,7 @@ public class VtablesTest { public static void main(String[] args) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-Xlog:vtables=trace", "ClassB"); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-Xlog:vtables=trace", "ClassB"); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldContain("copy vtable from ClassA to ClassB"); output.shouldContain("Initializing: ClassB"); @@ -55,7 +55,7 @@ public static void main(String[] args) throws Exception { output.shouldContain("NOT overriding with p2.D.nooverride()V"); output.shouldHaveExitValue(0); - pb = ProcessTools.createJavaProcessBuilder("-Xlog:vtables=trace", "p1/C"); + pb = ProcessTools.createLimitedTestJavaProcessBuilder("-Xlog:vtables=trace", "p1/C"); output = new OutputAnalyzer(pb.start()); output.shouldContain("transitive overriding superclass "); output.shouldHaveExitValue(0); diff --git a/test/hotspot/jtreg/runtime/logging/loadLibraryTest/LoadLibraryTest.java b/test/hotspot/jtreg/runtime/logging/loadLibraryTest/LoadLibraryTest.java index 5fe8386eb0e..9650eb6dd5b 100644 --- a/test/hotspot/jtreg/runtime/logging/loadLibraryTest/LoadLibraryTest.java +++ b/test/hotspot/jtreg/runtime/logging/loadLibraryTest/LoadLibraryTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2020, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -118,7 +118,7 @@ static class LoadLibraryClass { public static void main(String... args) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-Xbootclasspath/a:.", "-XX:+UnlockDiagnosticVMOptions", "-XX:+WhiteBoxAPI", "-Xmn8m", "-Xlog:library=info", "-Djava.library.path=" + System.getProperty("java.library.path"), diff --git a/test/hotspot/jtreg/runtime/memory/LargePages/TestLargePagesFlags.java b/test/hotspot/jtreg/runtime/memory/LargePages/TestLargePagesFlags.java index 7129b3c8f80..5b7f6021583 100644 --- a/test/hotspot/jtreg/runtime/memory/LargePages/TestLargePagesFlags.java +++ b/test/hotspot/jtreg/runtime/memory/LargePages/TestLargePagesFlags.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -328,7 +328,7 @@ private static OutputAnalyzer executeNewJVM(Flag... flags) throws Exception { args.add("-XX:+PrintFlagsFinal"); args.add("-version"); - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(args); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(args); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldHaveExitValue(0); diff --git a/test/hotspot/jtreg/runtime/memory/ReadFromNoaccessArea.java b/test/hotspot/jtreg/runtime/memory/ReadFromNoaccessArea.java index 889e35577f0..ede62416633 100644 --- a/test/hotspot/jtreg/runtime/memory/ReadFromNoaccessArea.java +++ b/test/hotspot/jtreg/runtime/memory/ReadFromNoaccessArea.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -44,7 +44,7 @@ public class ReadFromNoaccessArea { public static void main(String args[]) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-Xbootclasspath/a:.", "-XX:+UnlockDiagnosticVMOptions", "-XX:+WhiteBoxAPI", diff --git a/test/hotspot/jtreg/runtime/memory/ReserveMemory.java b/test/hotspot/jtreg/runtime/memory/ReserveMemory.java index 7cd0e1a0e78..6341a031c13 100644 --- a/test/hotspot/jtreg/runtime/memory/ReserveMemory.java +++ b/test/hotspot/jtreg/runtime/memory/ReserveMemory.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2023, Oracle and/or its affiliates. All rights reserved. * 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,7 +48,7 @@ public static void main(String args[]) throws Exception { // expected to crash WhiteBox.getWhiteBox().readReservedMemory(); } else { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-Xbootclasspath/a:.", "-XX:+UnlockDiagnosticVMOptions", "-XX:+WhiteBoxAPI", diff --git a/test/hotspot/jtreg/runtime/modules/AccessCheck/MethodAccessReadTwice.java b/test/hotspot/jtreg/runtime/modules/AccessCheck/MethodAccessReadTwice.java index 29bbe7f39b0..d6b85ced257 100644 --- a/test/hotspot/jtreg/runtime/modules/AccessCheck/MethodAccessReadTwice.java +++ b/test/hotspot/jtreg/runtime/modules/AccessCheck/MethodAccessReadTwice.java @@ -29,8 +29,8 @@ * after the module read edge is added. * @compile ModuleLibrary.java * p2/c2.java - * p5/c5.java - * p7/c7.java + * p5/c5.jasm + * p7/c7.jasm * @run main/othervm MethodAccessReadTwice */ diff --git a/test/hotspot/jtreg/runtime/modules/AccessCheck/p5/c5.jasm b/test/hotspot/jtreg/runtime/modules/AccessCheck/p5/c5.jasm new file mode 100644 index 00000000000..b1178eaab6c --- /dev/null +++ b/test/hotspot/jtreg/runtime/modules/AccessCheck/p5/c5.jasm @@ -0,0 +1,76 @@ +/* + * Copyright (c) 2021, Google LLC. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute 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 input for the fix for JDK-8174954, which checks for an expected + * IllegalAccessError when the parameter type of an invokedynamic is + * inaccessible. + * + * The test assumes that given the string concatenation expression "" + param, + * javac generates an invokedynamic that uses the specific type of param. The + * fix for JDK-8273914 make javac eagerly convert param to a String before + * passing it to the invokedynamic call, which avoids the accessibility issue + * the test is trying to exercise. + * + * This jasm file contains the bytecode javac generated before the fix for + * JDK-8273914, to continue to exercise the invokedynamic behaviour that + * JDK-8174954 is testing. + */ + +package p5; + +super public class c5 + version 61:0 +{ + public Method "":"()V" + stack 1 locals 1 + { + aload_0; + invokespecial Method java/lang/Object."":"()V"; + return; + } + public Method method5:"(Lp2/c2;)V" + stack 2 locals 2 + { + getstatic Field java/lang/System.out:"Ljava/io/PrintStream;"; + aload_1; + invokedynamic InvokeDynamic REF_invokeStatic:Method java/lang/invoke/StringConcatFactory.makeConcatWithConstants:"(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;Ljava/lang/String;[Ljava/lang/Object;)Ljava/lang/invoke/CallSite;":makeConcatWithConstants:"(Lp2/c2;)Ljava/lang/String;" { + String "In c5\'s method5 with param = " + }; + invokevirtual Method java/io/PrintStream.println:"(Ljava/lang/String;)V"; + return; + } + public Method methodAddReadEdge:"(Ljava/lang/Module;)V" + stack 2 locals 2 + { + ldc class c5; + invokevirtual Method java/lang/Class.getModule:"()Ljava/lang/Module;"; + aload_1; + invokevirtual Method java/lang/Module.addReads:"(Ljava/lang/Module;)Ljava/lang/Module;"; + pop; + return; + } + + public static final InnerClass Lookup=class java/lang/invoke/MethodHandles$Lookup of class java/lang/invoke/MethodHandles; + +} // end Class c5 diff --git a/test/hotspot/jtreg/runtime/modules/AccessCheck/p7/c7.jasm b/test/hotspot/jtreg/runtime/modules/AccessCheck/p7/c7.jasm new file mode 100644 index 00000000000..6ca4e6850e3 --- /dev/null +++ b/test/hotspot/jtreg/runtime/modules/AccessCheck/p7/c7.jasm @@ -0,0 +1,113 @@ +/* + * Copyright (c) 2021, Google LLC. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute 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 input for the fix for JDK-8174954, which checks for an expected + * IllegalAccessError when the parameter type of an invokedynamic is + * inaccessible. + * + * The test assumes that given the string concatenation expression "" + param, + * javac generates an invokedynamic that uses the specific type of param. The + * fix for JDK-8273914 make javac eagerly convert param to a String before + * passing it to the invokedynamic call, which avoids the accessibility issue + * the test is trying to exercise. + * + * This jasm file contains the bytecode javac generated before the fix for + * JDK-8273914, to continue to exercise the invokedynamic behaviour that + * JDK-8174954 is testing. + */ + +package p7; + +super public class c7 + version 61:0 +{ + public Method "":"()V" + stack 1 locals 1 + { + aload_0; + invokespecial Method java/lang/Object."":"()V"; + return; + } + public Method method7:"(Lp2/c2;Ljava/lang/Module;)V" + stack 3 locals 4 + { + try t0; + getstatic Field java/lang/System.out:"Ljava/io/PrintStream;"; + aload_1; + invokedynamic InvokeDynamic REF_invokeStatic:Method java/lang/invoke/StringConcatFactory.makeConcatWithConstants:"(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;Ljava/lang/String;[Ljava/lang/Object;)Ljava/lang/invoke/CallSite;":makeConcatWithConstants:"(Lp2/c2;)Ljava/lang/String;" { + String "In c7\'s method7 with param = " + }; + invokevirtual Method java/io/PrintStream.println:"(Ljava/lang/String;)V"; + new class java/lang/RuntimeException; + dup; + ldc String "c7 failed to throw expected IllegalAccessError"; + invokespecial Method java/lang/RuntimeException."":"(Ljava/lang/String;)V"; + athrow; + endtry t0; + catch t0 java/lang/IllegalAccessError; + stack_frame_type stack1; + stack_map class java/lang/IllegalAccessError; + astore_3; + aload_0; + aload_2; + invokevirtual Method methodAddReadEdge:"(Ljava/lang/Module;)V"; + try t1; + getstatic Field java/lang/System.out:"Ljava/io/PrintStream;"; + aload_1; + invokedynamic InvokeDynamic REF_invokeStatic:Method java/lang/invoke/StringConcatFactory.makeConcatWithConstants:"(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;Ljava/lang/String;[Ljava/lang/Object;)Ljava/lang/invoke/CallSite;":makeConcatWithConstants:"(Lp2/c2;)Ljava/lang/String;" { + String "In c7\'s method7 with param = " + }; + invokevirtual Method java/io/PrintStream.println:"(Ljava/lang/String;)V"; + endtry t1; + goto L61; + catch t1 java/lang/IllegalAccessError; + stack_frame_type stack1; + stack_map class java/lang/IllegalAccessError; + astore_3; + new class java/lang/RuntimeException; + dup; + aload_3; + invokevirtual Method java/lang/IllegalAccessError.getMessage:"()Ljava/lang/String;"; + invokedynamic InvokeDynamic REF_invokeStatic:Method java/lang/invoke/StringConcatFactory.makeConcatWithConstants:"(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;Ljava/lang/String;[Ljava/lang/Object;)Ljava/lang/invoke/CallSite;":makeConcatWithConstants:"(Ljava/lang/String;)Ljava/lang/String;" { + String "Unexpected IllegalAccessError: " + }; + invokespecial Method java/lang/RuntimeException."":"(Ljava/lang/String;)V"; + athrow; + L61: stack_frame_type same; + return; + } + public Method methodAddReadEdge:"(Ljava/lang/Module;)V" + stack 2 locals 2 + { + ldc class c7; + invokevirtual Method java/lang/Class.getModule:"()Ljava/lang/Module;"; + aload_1; + invokevirtual Method java/lang/Module.addReads:"(Ljava/lang/Module;)Ljava/lang/Module;"; + pop; + return; + } + + public static final InnerClass Lookup=class java/lang/invoke/MethodHandles$Lookup of class java/lang/invoke/MethodHandles; + +} // end Class c7 diff --git a/test/hotspot/jtreg/runtime/modules/ClassLoaderNoUnnamedModuleTest.java b/test/hotspot/jtreg/runtime/modules/ClassLoaderNoUnnamedModuleTest.java index 91017b30702..765f9dcee7d 100644 --- a/test/hotspot/jtreg/runtime/modules/ClassLoaderNoUnnamedModuleTest.java +++ b/test/hotspot/jtreg/runtime/modules/ClassLoaderNoUnnamedModuleTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2023, Oracle and/or its affiliates. All rights reserved. * 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,7 +37,7 @@ public class ClassLoaderNoUnnamedModuleTest { public static void main(String args[]) throws Throwable { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "--add-modules=java.base", "--add-exports=java.base/jdk.internal.misc=ALL-UNNAMED", "-XX:-CreateCoredumpOnCrash", diff --git a/test/hotspot/jtreg/runtime/modules/IgnoreModulePropertiesTest.java b/test/hotspot/jtreg/runtime/modules/IgnoreModulePropertiesTest.java index a3c9c8ac6ee..6bd2b299a55 100644 --- a/test/hotspot/jtreg/runtime/modules/IgnoreModulePropertiesTest.java +++ b/test/hotspot/jtreg/runtime/modules/IgnoreModulePropertiesTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -43,7 +43,7 @@ public class IgnoreModulePropertiesTest { // bogus for that property. But, since the property is ignored no exception is // thrown. public static void testProperty(String prop, String value) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-D" + prop + "=" + value, "-version"); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldContain(" version "); @@ -62,7 +62,7 @@ public static void testProperty(String prop, String value) throws Exception { public static void testOption(boolean shouldVMFail, String option, String value, String prop, String result) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( option + "=" + value, "-version"); OutputAnalyzer output = new OutputAnalyzer(pb.start()); if (shouldVMFail) { diff --git a/test/hotspot/jtreg/runtime/modules/ModuleOptionsTest.java b/test/hotspot/jtreg/runtime/modules/ModuleOptionsTest.java index 140b9103910..137e482ffb2 100644 --- a/test/hotspot/jtreg/runtime/modules/ModuleOptionsTest.java +++ b/test/hotspot/jtreg/runtime/modules/ModuleOptionsTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -42,7 +42,7 @@ public static void main(String[] args) throws Exception { // Test that multiple --add-modules options are cumulative, not last one wins. // An exception should be thrown because module i_dont_exist doesn't exist. - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "--add-modules=i_dont_exist", "--add-modules=java.base", "-version"); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldContain("FindException"); @@ -51,7 +51,7 @@ public static void main(String[] args) throws Exception { // Test that the last --limit-modules is the only one recognized. No exception // should be thrown. - pb = ProcessTools.createJavaProcessBuilder( + pb = ProcessTools.createLimitedTestJavaProcessBuilder( "--limit-modules=i_dont_exist", "--limit-modules=java.base", "-version"); output = new OutputAnalyzer(pb.start()); output.shouldHaveExitValue(0); diff --git a/test/hotspot/jtreg/runtime/modules/ModuleOptionsWarn.java b/test/hotspot/jtreg/runtime/modules/ModuleOptionsWarn.java index 5e6b526b5a3..73870e029ad 100644 --- a/test/hotspot/jtreg/runtime/modules/ModuleOptionsWarn.java +++ b/test/hotspot/jtreg/runtime/modules/ModuleOptionsWarn.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2023, Oracle and/or its affiliates. All rights reserved. * 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,77 +41,77 @@ public class ModuleOptionsWarn { public static void main(String[] args) throws Exception { // Test that a warning is not issued for extraneous jdk.module properties. - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:+PrintWarnings", "-Djdk.module.ignored", "-version"); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldNotContain("Ignoring system property option"); output.shouldHaveExitValue(0); // Test that a warning is issued for a reserved jdk.module property. - pb = ProcessTools.createJavaProcessBuilder( + pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:+PrintWarnings", "-Djdk.module.addmods", "-version"); output = new OutputAnalyzer(pb.start()); output.shouldContain("Ignoring system property option"); output.shouldHaveExitValue(0); // Test that a warning is issued for a reserved jdk.module property ending in '.'. - pb = ProcessTools.createJavaProcessBuilder( + pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:+PrintWarnings", "-Djdk.module.limitmods.", "-version"); output = new OutputAnalyzer(pb.start()); output.shouldContain("Ignoring system property option"); output.shouldHaveExitValue(0); // Test that a warning is issued for a reserved jdk.module property ending in '='. - pb = ProcessTools.createJavaProcessBuilder( + pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:+PrintWarnings", "-Djdk.module.addexports=", "-version"); output = new OutputAnalyzer(pb.start()); output.shouldContain("Ignoring system property option"); output.shouldHaveExitValue(0); // Test that a warning is issued for a reserved jdk.module property ending in ".stuff" - pb = ProcessTools.createJavaProcessBuilder( + pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:+PrintWarnings", "-Djdk.module.addreads.stuff", "-version"); output = new OutputAnalyzer(pb.start()); output.shouldContain("Ignoring system property option"); output.shouldHaveExitValue(0); // Test that a warning is issued for a reserved jdk.module property ending in "=stuff" - pb = ProcessTools.createJavaProcessBuilder( + pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:+PrintWarnings", "-Djdk.module.path=stuff", "-version"); output = new OutputAnalyzer(pb.start()); output.shouldContain("Ignoring system property option"); output.shouldHaveExitValue(0); // Test that a warning is issued for a reserved jdk.module property ending in ".=" - pb = ProcessTools.createJavaProcessBuilder( + pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:+PrintWarnings", "-Djdk.module.upgrade.path.=xx", "-version"); output = new OutputAnalyzer(pb.start()); output.shouldContain("Ignoring system property option"); output.shouldHaveExitValue(0); // Test that a warning is issued for a reserved jdk.module property ending in "." - pb = ProcessTools.createJavaProcessBuilder( + pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:+PrintWarnings", "-Djdk.module.patch.3=xx", "-version"); output = new OutputAnalyzer(pb.start()); output.shouldContain("Ignoring system property option"); output.shouldHaveExitValue(0); // Test that a warning can be suppressed for module related properties that get ignored. - pb = ProcessTools.createJavaProcessBuilder( + pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-Djdk.module.addmods", "-XX:-PrintWarnings", "-version"); output = new OutputAnalyzer(pb.start()); output.shouldNotContain("Ignoring system property option"); output.shouldHaveExitValue(0); // Test that a warning is not issued for properties of the form "jdk.module.main" - pb = ProcessTools.createJavaProcessBuilder( + pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:+PrintWarnings", "-Djdk.module.main.ignored", "-version"); output = new OutputAnalyzer(pb.start()); output.shouldNotContain("Ignoring system property option"); output.shouldHaveExitValue(0); // Test that a warning is issued for module related properties specified using _JAVA_OPTIONS. - pb = ProcessTools.createJavaProcessBuilder("-XX:+PrintWarnings", "-version"); + pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:+PrintWarnings", "-version"); Map env = pb.environment(); env.put("_JAVA_OPTIONS", "-Djdk.module.addreads"); output = new OutputAnalyzer(pb.start()); diff --git a/test/hotspot/jtreg/runtime/modules/ModuleStress/ExportModuleStressTest.java b/test/hotspot/jtreg/runtime/modules/ModuleStress/ExportModuleStressTest.java index ce9246e83c6..1de5f4ae0f8 100644 --- a/test/hotspot/jtreg/runtime/modules/ModuleStress/ExportModuleStressTest.java +++ b/test/hotspot/jtreg/runtime/modules/ModuleStress/ExportModuleStressTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -71,7 +71,7 @@ public static void main(String[] args) throws Exception { // Sanity check that the test, jdk.test/test/Main.java // runs without error. - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-p", MODS_DIR.toString(), "-m", "jdk.test/test.Main"); OutputAnalyzer output = new OutputAnalyzer(pb.start()); diff --git a/test/hotspot/jtreg/runtime/modules/ModuleStress/ModuleStress.java b/test/hotspot/jtreg/runtime/modules/ModuleStress/ModuleStress.java index bc23a0383ab..7232e213410 100644 --- a/test/hotspot/jtreg/runtime/modules/ModuleStress/ModuleStress.java +++ b/test/hotspot/jtreg/runtime/modules/ModuleStress/ModuleStress.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2023, Oracle and/or its affiliates. All rights reserved. * 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,7 +50,7 @@ public static void main(String[] args) throws Exception { // loaders (boot, application, platform). Thus there is // not a need to walk those lists at a GC safepoint since // those loaders never die. - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-Xbootclasspath/a:.", "-Xlog:module=trace", "-version"); @@ -85,7 +85,7 @@ public static void main(String[] args) throws Exception { // m1x's module readability list and package p2's exportability should // not be walked at a GC safepoint since both modules are defined to // the same loader and thus have the exact same life cycle. - pb = ProcessTools.createJavaProcessBuilder( + pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-Xbootclasspath/a:.", "-Xlog:module=trace", "ModuleSameCLMain"); @@ -99,7 +99,7 @@ public static void main(String[] args) throws Exception { // m1x's module readability list and package p2's exportability list must // be walked at a GC safepoint since both modules are defined to non-builtin // class loaders which could die and thus be unloaded. - pb = ProcessTools.createJavaProcessBuilder( + pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-Xbootclasspath/a:.", "-Xlog:module=trace", "ModuleNonBuiltinCLMain"); @@ -116,7 +116,7 @@ public static void main(String[] args) throws Exception { // m3x is defined to the system class loader, m2x's module readability // list does not have to be walked at a GC safepoint, but package p2's // exportability list does. - pb = ProcessTools.createJavaProcessBuilder( + pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-Djava.system.class.loader=CustomSystemClassLoader", "-Xbootclasspath/a:.", "-Xlog:module=trace", diff --git a/test/hotspot/jtreg/runtime/modules/ModuleStress/ModuleStressGC.java b/test/hotspot/jtreg/runtime/modules/ModuleStress/ModuleStressGC.java index 05b9cf7c2ef..44bbe4ed5c2 100644 --- a/test/hotspot/jtreg/runtime/modules/ModuleStress/ModuleStressGC.java +++ b/test/hotspot/jtreg/runtime/modules/ModuleStress/ModuleStressGC.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -72,7 +72,7 @@ public static void main(String[] args) throws Exception { // Check that jdk.test/test.MainGC walks module jdk.test's // reads list and walks the exports list for package test, // defined in module jdk.test, during a GC. - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-Xmx128m", "-Xlog:module=trace", "-p", MODS_DIR.toString(), diff --git a/test/hotspot/jtreg/runtime/modules/PatchModule/PatchModule2Dirs.java b/test/hotspot/jtreg/runtime/modules/PatchModule/PatchModule2Dirs.java index b582314411d..cd0670cfb72 100644 --- a/test/hotspot/jtreg/runtime/modules/PatchModule/PatchModule2Dirs.java +++ b/test/hotspot/jtreg/runtime/modules/PatchModule/PatchModule2Dirs.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2023, Oracle and/or its affiliates. All rights reserved. * 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,7 +60,7 @@ public static void main(String[] args) throws Exception { InMemoryJavaCompiler.compile("java.beans.Encoder", source2, "--patch-module=java.desktop"), "mods2/java.desktop"); - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "--patch-module=java.naming=mods/java.naming", "--patch-module=java.desktop=mods2/java.desktop", "PatchModule2DirsMain", "javax.naming.spi.NamingManager", "java.beans.Encoder"); diff --git a/test/hotspot/jtreg/runtime/modules/PatchModule/PatchModuleCDS.java b/test/hotspot/jtreg/runtime/modules/PatchModule/PatchModuleCDS.java index 109f6cf2616..e7bf5dabf21 100644 --- a/test/hotspot/jtreg/runtime/modules/PatchModule/PatchModuleCDS.java +++ b/test/hotspot/jtreg/runtime/modules/PatchModule/PatchModuleCDS.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -44,7 +44,7 @@ public static void main(String args[]) throws Throwable { // Case 1: Test that --patch-module and -Xshare:dump are compatible String filename = "patch_module.jsa"; - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:+UnlockDiagnosticVMOptions", "-XX:SharedArchiveFile=" + filename, "-Xshare:dump", @@ -69,7 +69,7 @@ public static void main(String args[]) throws Throwable { InMemoryJavaCompiler.compile("javax.naming.spi.NamingManager", source, "--patch-module=java.naming"), System.getProperty("test.classes")); - pb = ProcessTools.createJavaProcessBuilder( + pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:+UnlockDiagnosticVMOptions", "-XX:SharedArchiveFile=" + filename, "-Xshare:dump", @@ -84,7 +84,7 @@ public static void main(String args[]) throws Throwable { // Case 3a: Test CDS dumping with jar file in --patch-module BasicJarBuilder.build("javanaming", "javax/naming/spi/NamingManager"); String moduleJar = BasicJarBuilder.getTestJar("javanaming.jar"); - pb = ProcessTools.createJavaProcessBuilder( + pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:+UnlockDiagnosticVMOptions", "-XX:SharedArchiveFile=" + filename, "-Xshare:dump", @@ -98,7 +98,7 @@ public static void main(String args[]) throws Throwable { .shouldContain("Cannot use the following option when dumping the shared archive: --patch-module"); // Case 3b: Test CDS run with jar file in --patch-module - pb = ProcessTools.createJavaProcessBuilder( + pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:+UnlockDiagnosticVMOptions", "-XX:SharedArchiveFile=" + filename, "-Xshare:auto", diff --git a/test/hotspot/jtreg/runtime/modules/PatchModule/PatchModuleClassList.java b/test/hotspot/jtreg/runtime/modules/PatchModule/PatchModuleClassList.java index a4a03935f03..35ec86f841d 100644 --- a/test/hotspot/jtreg/runtime/modules/PatchModule/PatchModuleClassList.java +++ b/test/hotspot/jtreg/runtime/modules/PatchModule/PatchModuleClassList.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -64,7 +64,7 @@ public static void main(String args[]) throws Throwable { String moduleJar = BasicJarBuilder.getTestJar("javanaming.jar"); String classList = "javanaming.list"; - ProcessBuilder pb = ProcessTools.createTestJvm( + ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder( "-XX:DumpLoadedClassList=" + classList, "--patch-module=java.naming=" + moduleJar, "PatchModuleMain", BOOT_CLASS.replace('/', '.')); @@ -98,7 +98,7 @@ public static void main(String args[]) throws Throwable { moduleJar = BasicJarBuilder.getTestJar("javasql.jar"); classList = "javasql.list"; - pb = ProcessTools.createTestJvm( + pb = ProcessTools.createTestJavaProcessBuilder( "-XX:DumpLoadedClassList=" + classList, "--patch-module=java.sql=" + moduleJar, "PatchModuleMain", PLATFORM_CLASS.replace('/', '.')); @@ -130,7 +130,7 @@ public static void main(String args[]) throws Throwable { moduleJar = BasicJarBuilder.getTestJar("hello.jar"); classList = "hello.list"; - pb = ProcessTools.createTestJvm( + pb = ProcessTools.createTestJavaProcessBuilder( "-XX:DumpLoadedClassList=" + classList, "-Xbootclasspath/a:" + moduleJar, "Hello"); diff --git a/test/hotspot/jtreg/runtime/modules/PatchModule/PatchModuleDupJavaBase.java b/test/hotspot/jtreg/runtime/modules/PatchModule/PatchModuleDupJavaBase.java index a256a1f6c85..d9d00a1573e 100644 --- a/test/hotspot/jtreg/runtime/modules/PatchModule/PatchModuleDupJavaBase.java +++ b/test/hotspot/jtreg/runtime/modules/PatchModule/PatchModuleDupJavaBase.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2023, Oracle and/or its affiliates. All rights reserved. * 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,7 +37,7 @@ public class PatchModuleDupJavaBase { // The VM should exit initialization if java.base is specified // more than once to --patch-module. public static void main(String args[]) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "--patch-module=java.base=javabase_dir", "--patch-module=java.base=javabase_dir", "-version"); diff --git a/test/hotspot/jtreg/runtime/modules/PatchModule/PatchModuleDupModule.java b/test/hotspot/jtreg/runtime/modules/PatchModule/PatchModuleDupModule.java index a454dcb1527..464a15f78bd 100644 --- a/test/hotspot/jtreg/runtime/modules/PatchModule/PatchModuleDupModule.java +++ b/test/hotspot/jtreg/runtime/modules/PatchModule/PatchModuleDupModule.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2023, Oracle and/or its affiliates. All rights reserved. * 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,7 +39,7 @@ public class PatchModuleDupModule { // if --patch-module is specified with the same module more than once. public static void main(String args[]) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "--patch-module=module_one=module_one_dir", "--patch-module=module_one=module_one_dir", "-version"); diff --git a/test/hotspot/jtreg/runtime/modules/PatchModule/PatchModuleJavaBase.java b/test/hotspot/jtreg/runtime/modules/PatchModule/PatchModuleJavaBase.java index 58aef0fb877..75fcf26f633 100644 --- a/test/hotspot/jtreg/runtime/modules/PatchModule/PatchModuleJavaBase.java +++ b/test/hotspot/jtreg/runtime/modules/PatchModule/PatchModuleJavaBase.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -51,7 +51,7 @@ public static void main(String[] args) throws Exception { InMemoryJavaCompiler.compile("java.lang.NewClass", source, "--patch-module=java.base"), "mods/java.base"); - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("--patch-module=java.base=mods/java.base", + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("--patch-module=java.base=mods/java.base", "PatchModuleMain", "java.lang.NewClass"); new OutputAnalyzer(pb.start()) diff --git a/test/hotspot/jtreg/runtime/modules/PatchModule/PatchModuleTest.java b/test/hotspot/jtreg/runtime/modules/PatchModule/PatchModuleTest.java index 045f156c9d8..ed9f9019033 100644 --- a/test/hotspot/jtreg/runtime/modules/PatchModule/PatchModuleTest.java +++ b/test/hotspot/jtreg/runtime/modules/PatchModule/PatchModuleTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -51,7 +51,7 @@ public static void main(String[] args) throws Exception { InMemoryJavaCompiler.compile("javax.naming.spi.NamingManager", source, "--patch-module=java.naming"), "mods/java.naming"); - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("--patch-module=java.naming=mods/java.naming", + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("--patch-module=java.naming=mods/java.naming", "PatchModuleMain", "javax.naming.spi.NamingManager"); new OutputAnalyzer(pb.start()) diff --git a/test/hotspot/jtreg/runtime/modules/PatchModule/PatchModuleTestJar.java b/test/hotspot/jtreg/runtime/modules/PatchModule/PatchModuleTestJar.java index ed9e2b0ea8b..617d144d186 100644 --- a/test/hotspot/jtreg/runtime/modules/PatchModule/PatchModuleTestJar.java +++ b/test/hotspot/jtreg/runtime/modules/PatchModule/PatchModuleTestJar.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2023, Oracle and/or its affiliates. All rights reserved. * 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,7 +76,7 @@ public static void main(String[] args) throws Exception { System.getProperty("test.classes")); // Supply --patch-module with the name of the jar file for the module java.naming. - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("--patch-module=java.naming=" + moduleJar, + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("--patch-module=java.naming=" + moduleJar, "PatchModuleMain", "javax.naming.spi.NamingManager"); new OutputAnalyzer(pb.start()) diff --git a/test/hotspot/jtreg/runtime/modules/PatchModule/PatchModuleTestJarDir.java b/test/hotspot/jtreg/runtime/modules/PatchModule/PatchModuleTestJarDir.java index 2b2952b1e23..1be1f2f0e22 100644 --- a/test/hotspot/jtreg/runtime/modules/PatchModule/PatchModuleTestJarDir.java +++ b/test/hotspot/jtreg/runtime/modules/PatchModule/PatchModuleTestJarDir.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -92,13 +92,13 @@ public static void main(String[] args) throws Exception { // Supply --patch-module with the name of the jar file for the module java.naming. - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("--patch-module=java.naming=" + - moduleJar + - File.pathSeparator + - System.getProperty("test.classes") + "/mods/java.naming", - "PatchModule2DirsMain", - "javax.naming.spi.NamingManager1", - "javax.naming.spi.NamingManager2"); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("--patch-module=java.naming=" + + moduleJar + + File.pathSeparator + + System.getProperty("test.classes") + "/mods/java.naming", + "PatchModule2DirsMain", + "javax.naming.spi.NamingManager1", + "javax.naming.spi.NamingManager2"); new OutputAnalyzer(pb.start()) .shouldContain("I pass one!") diff --git a/test/hotspot/jtreg/runtime/modules/PatchModule/PatchModuleTraceCL.java b/test/hotspot/jtreg/runtime/modules/PatchModule/PatchModuleTraceCL.java index f98f85cce9a..dd8b33402ac 100644 --- a/test/hotspot/jtreg/runtime/modules/PatchModule/PatchModuleTraceCL.java +++ b/test/hotspot/jtreg/runtime/modules/PatchModule/PatchModuleTraceCL.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -53,7 +53,7 @@ public static void main(String[] args) throws Exception { InMemoryJavaCompiler.compile("javax.naming.spi.NamingManager", source, "--patch-module=java.naming"), "mods/java.naming"); - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("--patch-module=java.naming=mods/java.naming", + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("--patch-module=java.naming=mods/java.naming", "-Xlog:class+load=info", "PatchModuleMain", "javax.naming.spi.NamingManager"); OutputAnalyzer output = new OutputAnalyzer(pb.start()); @@ -77,7 +77,7 @@ public static void main(String[] args) throws Exception { InMemoryJavaCompiler.compile("PatchModuleTraceCL_pkg.ItIsI", source), "xbcp"); - pb = ProcessTools.createJavaProcessBuilder("-Xbootclasspath/a:xbcp", + pb = ProcessTools.createLimitedTestJavaProcessBuilder("-Xbootclasspath/a:xbcp", "-Xlog:class+load=info", "PatchModuleMain", "PatchModuleTraceCL_pkg.ItIsI"); output = new OutputAnalyzer(pb.start()); // -Xbootclasspath/a case. diff --git a/test/hotspot/jtreg/runtime/modules/Visibility/PatchModuleVisibility.java b/test/hotspot/jtreg/runtime/modules/Visibility/PatchModuleVisibility.java index f11d52b46f0..96982593dbb 100644 --- a/test/hotspot/jtreg/runtime/modules/Visibility/PatchModuleVisibility.java +++ b/test/hotspot/jtreg/runtime/modules/Visibility/PatchModuleVisibility.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2023, Oracle and/or its affiliates. All rights reserved. * 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,7 +86,7 @@ public static void main(String[] args) throws Throwable { Files.delete(Paths.get(System.getProperty("test.classes") + File.separator + "p2" + File.separator + "Vis2_B.class")); - new OutputAnalyzer(ProcessTools.createJavaProcessBuilder( + new OutputAnalyzer(ProcessTools.createLimitedTestJavaProcessBuilder( "--patch-module=java.base=mods2/java.base", "--add-exports=java.base/p2=ALL-UNNAMED", "Vis2_A") diff --git a/test/hotspot/jtreg/runtime/modules/Visibility/XbootcpNoVisibility.java b/test/hotspot/jtreg/runtime/modules/Visibility/XbootcpNoVisibility.java index 9d10fe6488c..90df4c10f27 100644 --- a/test/hotspot/jtreg/runtime/modules/Visibility/XbootcpNoVisibility.java +++ b/test/hotspot/jtreg/runtime/modules/Visibility/XbootcpNoVisibility.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -73,7 +73,7 @@ public static void main(String args[]) throws Exception { ClassFileInstaller.writeClassToDisk("Vis3_A", InMemoryJavaCompiler.compile("Vis3_A", Vis3_A_src), System.getProperty("test.classes")); - new OutputAnalyzer(ProcessTools.createJavaProcessBuilder( + new OutputAnalyzer(ProcessTools.createLimitedTestJavaProcessBuilder( "-Xbootclasspath/a:.", "Vis3_A") .start()) diff --git a/test/hotspot/jtreg/runtime/modules/Visibility/XbootcpVisibility.java b/test/hotspot/jtreg/runtime/modules/Visibility/XbootcpVisibility.java index df20c356c92..5d1605b74fe 100644 --- a/test/hotspot/jtreg/runtime/modules/Visibility/XbootcpVisibility.java +++ b/test/hotspot/jtreg/runtime/modules/Visibility/XbootcpVisibility.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -104,7 +104,7 @@ public static void main(String[] args) throws Throwable { Files.delete(Paths.get(System.getProperty("test.classes") + File.separator + "p2" + File.separator + "Vis1_C.class")); - new OutputAnalyzer(ProcessTools.createJavaProcessBuilder( + new OutputAnalyzer(ProcessTools.createLimitedTestJavaProcessBuilder( "-Xbootclasspath/a:nonexistent.jar", "-Xbootclasspath/a:mods1", "Vis1_A") diff --git a/test/hotspot/jtreg/runtime/os/AvailableProcessors.java b/test/hotspot/jtreg/runtime/os/AvailableProcessors.java index 97491d241b9..18201d99127 100644 --- a/test/hotspot/jtreg/runtime/os/AvailableProcessors.java +++ b/test/hotspot/jtreg/runtime/os/AvailableProcessors.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -69,8 +69,8 @@ public static void main(String[] args) throws Exception { // Get the java command we want to execute // Enable logging for easier failure diagnosis ProcessBuilder master = - ProcessTools.createJavaProcessBuilder("-Xlog:os=trace", - "AvailableProcessors"); + ProcessTools.createLimitedTestJavaProcessBuilder("-Xlog:os=trace", + "AvailableProcessors"); int[] expected = new int[] { 1, available/2, available-1, available }; diff --git a/test/hotspot/jtreg/runtime/os/THPsInThreadStackPreventionTest.java b/test/hotspot/jtreg/runtime/os/THPsInThreadStackPreventionTest.java index 261ec205d39..519bcc94b01 100644 --- a/test/hotspot/jtreg/runtime/os/THPsInThreadStackPreventionTest.java +++ b/test/hotspot/jtreg/runtime/os/THPsInThreadStackPreventionTest.java @@ -179,7 +179,7 @@ public static void main(String[] args) throws Exception { switch (args[0]) { case "PATCH-ENABLED": { finalargs.add(TestMain.class.getName()); - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(finalargs); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(finalargs); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldHaveExitValue(0); @@ -216,7 +216,7 @@ public static void main(String[] args) throws Exception { finalargs.add("-XX:-THPStackMitigation"); finalargs.add(TestMain.class.getName()); - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(finalargs); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(finalargs); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldHaveExitValue(0); diff --git a/test/hotspot/jtreg/runtime/os/TestHugePageDecisionsAtVMStartup.java b/test/hotspot/jtreg/runtime/os/TestHugePageDecisionsAtVMStartup.java index e93309c0b00..340c1370738 100644 --- a/test/hotspot/jtreg/runtime/os/TestHugePageDecisionsAtVMStartup.java +++ b/test/hotspot/jtreg/runtime/os/TestHugePageDecisionsAtVMStartup.java @@ -146,7 +146,7 @@ public static void main(String[] extraOptions) throws Exception { boolean useTHP = allOptions.contains("-XX:+UseTransparentHugePages"); System.out.println("useLP: " + useLP + " useTHP: " + useTHP); - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(allOptions.toArray(new String[0])); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(allOptions.toArray(new String[0])); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.reportDiagnosticSummary(); HugePageConfiguration configuration = HugePageConfiguration.readFromOS(); diff --git a/test/hotspot/jtreg/runtime/os/TestHugePageDetection.java b/test/hotspot/jtreg/runtime/os/TestHugePageDetection.java index 80d7df080d0..2e2d9092c74 100644 --- a/test/hotspot/jtreg/runtime/os/TestHugePageDetection.java +++ b/test/hotspot/jtreg/runtime/os/TestHugePageDetection.java @@ -48,7 +48,7 @@ public static void main(String[] args) throws Exception { finalargs.addAll(Arrays.asList(defaultArgs)); finalargs.add("-version"); - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( new String[] {"-Xlog:pagesize", "-Xmx64M", "-version"}); OutputAnalyzer output = new OutputAnalyzer(pb.start()); diff --git a/test/hotspot/jtreg/runtime/os/TestTimerSlack.java b/test/hotspot/jtreg/runtime/os/TestTimerSlack.java index 86aece992b5..b703625dfd0 100644 --- a/test/hotspot/jtreg/runtime/os/TestTimerSlack.java +++ b/test/hotspot/jtreg/runtime/os/TestTimerSlack.java @@ -42,7 +42,7 @@ public static void main(String[] args) throws Exception { // Check the timer slack value is not printed by default { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-Xlog:os+thread", + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-Xlog:os+thread", "TestTimerSlack$TestMain"); OutputAnalyzer output = new OutputAnalyzer(pb.start()); @@ -52,7 +52,7 @@ public static void main(String[] args) throws Exception { // Check the timer slack value is not printed when explicitly disabled { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-Xlog:os+thread", + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-Xlog:os+thread", "-XX:+UnlockExperimentalVMOptions", "-XX:TimerSlack=-1", "TestTimerSlack$TestMain"); @@ -64,7 +64,7 @@ public static void main(String[] args) throws Exception { // Check the timer slack value is good when system-wide default is requested { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-Xlog:os+thread", + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-Xlog:os+thread", "-XX:+UnlockExperimentalVMOptions", "-XX:TimerSlack=0", "TestTimerSlack$TestMain"); @@ -82,7 +82,7 @@ public static void main(String[] args) throws Exception { // Check the timer slack value is accepted by all threads for (int slack : new int[] {1, 10, 100, 1000, 10000, 100000, 1000000}) { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-Xlog:os+thread", + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-Xlog:os+thread", "-XX:+UnlockExperimentalVMOptions", "-XX:TimerSlack=" + slack, "TestTimerSlack$TestMain"); diff --git a/test/hotspot/jtreg/runtime/os/TestTracePageSizes.java b/test/hotspot/jtreg/runtime/os/TestTracePageSizes.java index dca9f8bb71f..ca9f4ec8996 100644 --- a/test/hotspot/jtreg/runtime/os/TestTracePageSizes.java +++ b/test/hotspot/jtreg/runtime/os/TestTracePageSizes.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2021, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -28,6 +28,7 @@ * @library /test/lib * @build jdk.test.lib.Platform * @requires os.family == "linux" + * @requires os.arch != "ppc64le" * @run main/othervm -XX:+AlwaysPreTouch -Xlog:pagesize:ps-%p.log TestTracePageSizes */ @@ -51,6 +52,7 @@ * @library /test/lib * @build jdk.test.lib.Platform * @requires os.family == "linux" + * @requires os.arch != "ppc64le" * @requires vm.gc != "Z" & vm.gc != "Shenandoah" * @run main/othervm -XX:+AlwaysPreTouch -Xmx128m -Xlog:pagesize:ps-%p.log -XX:-SegmentedCodeCache TestTracePageSizes * @run main/othervm -XX:+AlwaysPreTouch -Xmx128m -Xlog:pagesize:ps-%p.log -XX:-SegmentedCodeCache -XX:+UseLargePages TestTracePageSizes @@ -63,6 +65,7 @@ * @library /test/lib * @build jdk.test.lib.Platform * @requires os.family == "linux" + * @requires os.arch != "ppc64le" * @requires vm.gc.G1 * @run main/othervm -XX:+AlwaysPreTouch -Xmx128m -Xlog:pagesize:ps-%p.log -XX:+UseG1GC TestTracePageSizes * @run main/othervm -XX:+AlwaysPreTouch -Xmx128m -Xlog:pagesize:ps-%p.log -XX:+UseG1GC -XX:+UseLargePages TestTracePageSizes @@ -75,6 +78,7 @@ * @library /test/lib * @build jdk.test.lib.Platform * @requires os.family == "linux" + * @requires os.arch != "ppc64le" * @requires vm.gc.Parallel * @run main/othervm -XX:+AlwaysPreTouch -Xmx128m -Xlog:pagesize:ps-%p.log -XX:+UseParallelGC TestTracePageSizes * @run main/othervm -XX:+AlwaysPreTouch -Xmx128m -Xlog:pagesize:ps-%p.log -XX:+UseParallelGC -XX:+UseLargePages TestTracePageSizes @@ -87,6 +91,7 @@ * @library /test/lib * @build jdk.test.lib.Platform * @requires os.family == "linux" + * @requires os.arch != "ppc64le" * @requires vm.gc.Serial * @run main/othervm -XX:+AlwaysPreTouch -Xmx128m -Xlog:pagesize:ps-%p.log -XX:+UseSerialGC TestTracePageSizes * @run main/othervm -XX:+AlwaysPreTouch -Xmx128m -Xlog:pagesize:ps-%p.log -XX:+UseSerialGC -XX:+UseLargePages TestTracePageSizes @@ -248,12 +253,6 @@ public static void main(String args[]) throws Exception { throw new SkippedException("Kernel older than 3.8 - skipping this test."); } - // For similar reasons, we skip the test on ppc platforms, since there the smaps - // format may follow a different logic. - if (Platform.isPPC()) { - throw new SkippedException("PPC - skipping this test."); - } - // Parse /proc/self/smaps to compare with values logged in the VM. parseSmaps(); diff --git a/test/hotspot/jtreg/runtime/os/TestTrimNative.java b/test/hotspot/jtreg/runtime/os/TestTrimNative.java index 3c64f008e3a..e8645a91479 100644 --- a/test/hotspot/jtreg/runtime/os/TestTrimNative.java +++ b/test/hotspot/jtreg/runtime/os/TestTrimNative.java @@ -167,7 +167,7 @@ private static String[] prepareOptions(String[] extraVMOptions, String[] program } private static OutputAnalyzer runTestWithOptions(String[] extraOptions, String[] programOptions) throws IOException { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(prepareOptions(extraOptions, programOptions)); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(prepareOptions(extraOptions, programOptions)); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldHaveExitValue(0); return output; diff --git a/test/hotspot/jtreg/runtime/os/TestUseCpuAllocPath.java b/test/hotspot/jtreg/runtime/os/TestUseCpuAllocPath.java index 0146256f7dd..6b98f8fd2d9 100644 --- a/test/hotspot/jtreg/runtime/os/TestUseCpuAllocPath.java +++ b/test/hotspot/jtreg/runtime/os/TestUseCpuAllocPath.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2023, Oracle and/or its affiliates. All rights reserved. * 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,10 +42,10 @@ public class TestUseCpuAllocPath { public static void main(String[] args) throws Exception { ProcessBuilder pb = - ProcessTools.createJavaProcessBuilder("-Xlog:os=trace", - "-XX:+UnlockDiagnosticVMOptions", - "-XX:+UseCpuAllocPath", - "-version"); + ProcessTools.createLimitedTestJavaProcessBuilder("-Xlog:os=trace", + "-XX:+UnlockDiagnosticVMOptions", + "-XX:+UseCpuAllocPath", + "-version"); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldHaveExitValue(0); diff --git a/test/hotspot/jtreg/runtime/records/RedefineRecord.java b/test/hotspot/jtreg/runtime/records/RedefineRecord.java index bad4542885e..1019a4c3e7b 100644 --- a/test/hotspot/jtreg/runtime/records/RedefineRecord.java +++ b/test/hotspot/jtreg/runtime/records/RedefineRecord.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -102,7 +102,7 @@ public static void main(String argv[]) throws Exception { return; } if (argv.length == 1 && argv[0].equals("runtest")) { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:MetaspaceSize=12m", "-XX:MaxMetaspaceSize=12m", "-javaagent:redefineagent.jar", diff --git a/test/hotspot/jtreg/runtime/sealedClasses/RedefinePermittedSubclass.java b/test/hotspot/jtreg/runtime/sealedClasses/RedefinePermittedSubclass.java index 1832d295cc5..29ce452cc2c 100644 --- a/test/hotspot/jtreg/runtime/sealedClasses/RedefinePermittedSubclass.java +++ b/test/hotspot/jtreg/runtime/sealedClasses/RedefinePermittedSubclass.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2021, 2023, Oracle and/or its affiliates. All rights reserved. * 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,7 +126,7 @@ public static void main(String argv[]) throws Exception { if (argv.length == 1 && argv[0].equals("runtest")) { String[] javaArgs1 = { "-XX:MetaspaceSize=12m", "-XX:MaxMetaspaceSize=12m", "-javaagent:redefineagent.jar", "RedefinePermittedSubclass"}; - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(javaArgs1); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(javaArgs1); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldNotContain("processing of -javaagent failed"); output.shouldHaveExitValue(0); diff --git a/test/hotspot/jtreg/runtime/sealedClasses/RedefineSealedClass.java b/test/hotspot/jtreg/runtime/sealedClasses/RedefineSealedClass.java index 515dfa9f5e0..84a1b6bfac7 100644 --- a/test/hotspot/jtreg/runtime/sealedClasses/RedefineSealedClass.java +++ b/test/hotspot/jtreg/runtime/sealedClasses/RedefineSealedClass.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2021, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -108,7 +108,7 @@ public static void main(String argv[]) throws Exception { if (argv.length == 1 && argv[0].equals("runtest")) { String[] javaArgs1 = { "-XX:MetaspaceSize=12m", "-XX:MaxMetaspaceSize=12m", "-javaagent:redefineagent.jar", "RedefineSealedClass"}; - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(javaArgs1); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(javaArgs1); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldNotContain("processing of -javaagent failed"); output.shouldHaveExitValue(0); diff --git a/test/hotspot/jtreg/vmTestbase/nsk/stress/stack/stack001.java b/test/hotspot/jtreg/runtime/stack/Stack001.java similarity index 79% rename from test/hotspot/jtreg/vmTestbase/nsk/stress/stack/stack001.java rename to test/hotspot/jtreg/runtime/stack/Stack001.java index 3ded4d236a3..b344e177499 100644 --- a/test/hotspot/jtreg/vmTestbase/nsk/stress/stack/stack001.java +++ b/test/hotspot/jtreg/runtime/stack/Stack001.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -52,25 +52,14 @@ * 4302288 the second stack overflow causes Classic VM to exit on win32 * * @requires vm.opt.DeoptimizeALot != true - * @run main/othervm/timeout=900 nsk.stress.stack.stack001 + * @run main/othervm/timeout=900 Stack001 */ -package nsk.stress.stack; - - -import java.io.PrintStream; - -public class stack001 { +public class Stack001 { public static void main(String[] args) { - int exitCode = run(args, System.out); - System.exit(exitCode + 95); - } - - public static int run(String args[], PrintStream out) { - stack001 test = new stack001(); + Stack001 test = new Stack001(); test.recurse(0); - out.println("Maximal depth: " + test.maxdepth); - return 0; + System.out.println("Maximal depth: " + test.maxdepth); } private int maxdepth; @@ -79,13 +68,10 @@ private void recurse(int depth) { maxdepth = depth; try { recurse(depth + 1); - } catch (Error error) { - if (!(error instanceof StackOverflowError) && - !(error instanceof OutOfMemoryError)) - throw error; - - if (maxdepth == depth) + } catch (StackOverflowError | OutOfMemoryError e) { + if (maxdepth == depth) { recurse(depth + 1); + } } } } diff --git a/test/hotspot/jtreg/vmTestbase/nsk/stress/stack/stack002.java b/test/hotspot/jtreg/runtime/stack/Stack002.java similarity index 84% rename from test/hotspot/jtreg/vmTestbase/nsk/stress/stack/stack002.java rename to test/hotspot/jtreg/runtime/stack/Stack002.java index 84081108410..68265b24620 100644 --- a/test/hotspot/jtreg/vmTestbase/nsk/stress/stack/stack002.java +++ b/test/hotspot/jtreg/runtime/stack/Stack002.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -53,24 +53,14 @@ * 4302288 the second stack overflow causes Classic VM to exit on win32 * * @requires vm.opt.DeoptimizeALot != true - * @run main/othervm/timeout=900 nsk.stress.stack.stack002 + * @run main/othervm/timeout=900 Stack002 */ -package nsk.stress.stack; - - -import java.io.PrintStream; - -public class stack002 { +public class Stack002 { static final long timeout = 10000; // 10 seconds public static void main(String[] args) { - int exitCode = run(args, System.out); - System.exit(exitCode + 95); - } - - public static int run(String args[], PrintStream out) { - Tester tester = new Tester(out); + Tester tester = new Tester(); Timer timer = new Timer(tester); timer.start(); tester.start(); @@ -78,21 +68,18 @@ public static int run(String args[], PrintStream out) { try { timer.join(); } catch (InterruptedException e) { - e.printStackTrace(out); - return 2; + e.printStackTrace(); + throw new RuntimeException(e); } // if (tester.isAlive()) // return 2; - out.println("Maximal depth: " + tester.maxdepth); - return 0; + System.out.println("Maximal depth: " + tester.maxdepth); } private static class Tester extends Thread { int maxdepth; - PrintStream out; - public Tester(PrintStream out) { - this.out = out; + public Tester() { maxdepth = 0; } @@ -108,10 +95,7 @@ void recurse(int depth) { // // OutOfMemoryError is also eligible to indicate stack overflow: // - } catch (Error error) { - if (!(error instanceof StackOverflowError) && - !(error instanceof OutOfMemoryError)) - throw error; + } catch (StackOverflowError | OutOfMemoryError e) { /*** *** Originally, I supposed that VM crashes because of unexpected diff --git a/test/hotspot/jtreg/vmTestbase/nsk/stress/stack/stack003.java b/test/hotspot/jtreg/runtime/stack/Stack003.java similarity index 75% rename from test/hotspot/jtreg/vmTestbase/nsk/stress/stack/stack003.java rename to test/hotspot/jtreg/runtime/stack/Stack003.java index f8a122c2b67..260344456c9 100644 --- a/test/hotspot/jtreg/vmTestbase/nsk/stress/stack/stack003.java +++ b/test/hotspot/jtreg/runtime/stack/Stack003.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2024, Oracle and/or its affiliates. All rights reserved. * 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,48 +47,37 @@ * 4366625 (P4/S4) multiple stack overflow causes HS crash * * @requires vm.opt.DeoptimizeALot != true - * @run main/othervm/timeout=900 nsk.stress.stack.stack003 + * @run main/othervm/timeout=900 Stack003 */ -package nsk.stress.stack; - - -import java.io.PrintStream; - -public class stack003 { +public class Stack003 { final static int ITERATIONS = 100; final static int INCREMENT = 100; public static void main(String[] args) { - int exitCode = run(args, System.out); - System.exit(exitCode + 95); - } - public static int run(String args[], PrintStream out) { int depth; - for (depth = 1; ; depth += INCREMENT) + for (depth = 1; ; depth += INCREMENT) { try { recurse(depth); - } catch (StackOverflowError soe) { - break; - } catch (OutOfMemoryError oome) { + } catch (StackOverflowError | OutOfMemoryError err) { break; } - out.println("Max. depth: " + depth); - for (int i = 0; i < ITERATIONS; i++) + } + System.out.println("Max. depth: " + depth); + for (int i = 0; i < ITERATIONS; i++) { try { recurse(2 * depth); - out.println("?"); - } catch (StackOverflowError soe) { + System.out.println("?"); + } catch (StackOverflowError | OutOfMemoryError err) { // OK. - } catch (OutOfMemoryError oome) { - // Also OK. } - return 0; + } } static void recurse(int depth) { - if (depth > 0) + if (depth > 0) { recurse(depth - 1); + } } } diff --git a/test/hotspot/jtreg/vmTestbase/nsk/stress/stack/stack004.java b/test/hotspot/jtreg/runtime/stack/Stack004.java similarity index 73% rename from test/hotspot/jtreg/vmTestbase/nsk/stress/stack/stack004.java rename to test/hotspot/jtreg/runtime/stack/Stack004.java index b7bff2aedb5..fb9b594421b 100644 --- a/test/hotspot/jtreg/vmTestbase/nsk/stress/stack/stack004.java +++ b/test/hotspot/jtreg/runtime/stack/Stack004.java @@ -47,51 +47,38 @@ * 4366625 (P4/S4) multiple stack overflow causes HS crash * * @requires vm.opt.DeoptimizeALot != true - * @run main/othervm/timeout=900 nsk.stress.stack.stack004 + * @run main/othervm/timeout=900 Stack004 */ -package nsk.stress.stack; - - -import java.io.PrintStream; - -public class stack004 { +public class Stack004 { public static void main(String[] args) { - int exitCode = run(args, System.out); - System.exit(exitCode + 95); + Stack004 test = new Stack004(); + test.doRun(); } - public static int run(String args[], PrintStream out) { - stack004 test = new stack004(); - int exitCode = test.doRun(args, out); - return exitCode; - } - - public int doRun(String args[], PrintStream out) { + public void doRun() { int depth; - for (depth = 100; ; depth += 100) + for (depth = 100; ; depth += 100) { try { recurse(depth); - } catch (StackOverflowError soe) { - break; - } catch (OutOfMemoryError oome) { + } catch (StackOverflowError | OutOfMemoryError err) { break; } - out.println("Max. depth: " + depth); - for (int i = 0; i < 100; i++) + } + System.out.println("Max. depth: " + depth); + for (int i = 0; i < 100; i++) { try { recurse(2 * depth); - out.println("?"); - } catch (StackOverflowError soe) { + System.out.println("?"); + } catch (StackOverflowError | OutOfMemoryError err) { // OK. - } catch (OutOfMemoryError oome) { - // Also OK. } - return 0; + } } final static void recurse(int depth) { - if (depth > 0) + if (depth > 0) { recurse(depth - 1); + } } } diff --git a/test/hotspot/jtreg/vmTestbase/nsk/stress/stack/stack005.java b/test/hotspot/jtreg/runtime/stack/Stack005.java similarity index 74% rename from test/hotspot/jtreg/vmTestbase/nsk/stress/stack/stack005.java rename to test/hotspot/jtreg/runtime/stack/Stack005.java index a5bd10595fc..35963e03bc8 100644 --- a/test/hotspot/jtreg/vmTestbase/nsk/stress/stack/stack005.java +++ b/test/hotspot/jtreg/runtime/stack/Stack005.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2024, Oracle and/or its affiliates. All rights reserved. * 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,46 +47,34 @@ * 4366625 (P4/S4) multiple stack overflow causes HS crash * * @requires vm.opt.DeoptimizeALot != true - * @run main/othervm/timeout=900 nsk.stress.stack.stack005 + * @run main/othervm/timeout=900 Stack005 */ -package nsk.stress.stack; - - -import java.io.PrintStream; - -public class stack005 { +public class Stack005 { public static void main(String[] args) { - int exitCode = run(args, System.out); - System.exit(exitCode + 95); - } - - public static int run(String args[], PrintStream out) { - stack005 test = new stack005(); + Stack005 test = new Stack005(); int depth; - for (depth = 100; ; depth += 100) + for (depth = 100; ; depth += 100) { try { test.recurse(depth); - } catch (StackOverflowError soe) { - break; - } catch (OutOfMemoryError oome) { + } catch (StackOverflowError | OutOfMemoryError soe) { break; } - out.println("Max. depth: " + depth); - for (int i = 0; i < 100; i++) + } + System.out.println("Max. depth: " + depth); + for (int i = 0; i < 100; i++) { try { test.recurse(2 * depth); - out.println("?"); - } catch (StackOverflowError soe) { + System.out.println("?"); + } catch (StackOverflowError | OutOfMemoryError err) { // OK. - } catch (OutOfMemoryError oome) { - // Also OK. } - return 0; + } } final void recurse(int depth) { - if (depth > 0) + if (depth > 0) { recurse(depth - 1); + } } } diff --git a/test/hotspot/jtreg/vmTestbase/nsk/stress/stack/stack006.java b/test/hotspot/jtreg/runtime/stack/Stack006.java similarity index 74% rename from test/hotspot/jtreg/vmTestbase/nsk/stress/stack/stack006.java rename to test/hotspot/jtreg/runtime/stack/Stack006.java index 2b8754dd2ae..313fdd02c6a 100644 --- a/test/hotspot/jtreg/vmTestbase/nsk/stress/stack/stack006.java +++ b/test/hotspot/jtreg/runtime/stack/Stack006.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2024, Oracle and/or its affiliates. All rights reserved. * 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,50 +47,38 @@ * 4366625 (P4/S4) multiple stack overflow causes HS crash * * @requires vm.opt.DeoptimizeALot != true - * @run main/othervm/timeout=900 nsk.stress.stack.stack006 + * @run main/othervm/timeout=900 Stack006 */ -package nsk.stress.stack; - - -import java.io.PrintStream; - -public class stack006 implements stack006i { +public class Stack006 implements Stack006i { public static void main(String[] args) { - int exitCode = run(args, System.out); - System.exit(exitCode + 95); - } - - public static int run(String args[], PrintStream out) { - stack006i test = new stack006(); + Stack006i test = new Stack006(); int depth; - for (depth = 100; ; depth += 100) + for (depth = 100; ; depth += 100) { try { test.recurse(depth); - } catch (StackOverflowError soe) { - break; - } catch (OutOfMemoryError oome) { + } catch (StackOverflowError | OutOfMemoryError err) { break; } - out.println("Max. depth: " + depth); - for (int i = 0; i < 100; i++) + } + System.out.println("Max. depth: " + depth); + for (int i = 0; i < 100; i++) { try { test.recurse(2 * depth); - out.println("?"); - } catch (StackOverflowError soe) { + System.out.println("?"); + } catch (StackOverflowError | OutOfMemoryError err) { // OK. - } catch (OutOfMemoryError oome) { - // Also OK. } - return 0; + } } public void recurse(int depth) { - if (depth > 0) + if (depth > 0) { recurse(depth - 1); + } } } -interface stack006i { +interface Stack006i { void recurse(int depth); } diff --git a/test/hotspot/jtreg/vmTestbase/nsk/stress/stack/stack007.java b/test/hotspot/jtreg/runtime/stack/Stack007.java similarity index 74% rename from test/hotspot/jtreg/vmTestbase/nsk/stress/stack/stack007.java rename to test/hotspot/jtreg/runtime/stack/Stack007.java index 1a9b7f0d392..d8849dd847c 100644 --- a/test/hotspot/jtreg/vmTestbase/nsk/stress/stack/stack007.java +++ b/test/hotspot/jtreg/runtime/stack/Stack007.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2024, Oracle and/or its affiliates. All rights reserved. * 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,53 +46,41 @@ * 4366625 (P4/S4) multiple stack overflow causes HS crash * * @requires vm.opt.DeoptimizeALot != true - * @run main/othervm/timeout=900 nsk.stress.stack.stack007 + * @run main/othervm/timeout=900 Stack007 */ -package nsk.stress.stack; - - -import java.io.PrintStream; - -public class stack007 implements stack007i { +public class Stack007 implements Stack007i { final static int ITERATIONS = 1000; final static int INCREMENT = 100; public static void main(String[] args) { - int exitCode = run(args, System.out); - System.exit(exitCode + 95); - } - - public static int run(String args[], PrintStream out) { - stack007i test = new stack007(); + Stack007i test = new Stack007(); int depth; - for (depth = 100; ; depth += INCREMENT) + for (depth = 100; ; depth += INCREMENT) { try { test.recurse(depth); - } catch (StackOverflowError soe) { - break; - } catch (OutOfMemoryError oome) { + } catch (StackOverflowError | OutOfMemoryError err) { break; } - out.println("Max. depth: " + depth); - for (int i = 0; i < ITERATIONS; i++) + } + System.out.println("Max. depth: " + depth); + for (int i = 0; i < ITERATIONS; i++) { try { test.recurse(10 * depth); - out.println("?"); - } catch (StackOverflowError soe) { + System.out.println("?"); + } catch (StackOverflowError | OutOfMemoryError err) { // OK. - } catch (OutOfMemoryError oome) { - // Also OK. } - return 0; + } } public synchronized void recurse(int depth) { - if (depth > 0) + if (depth > 0) { recurse(depth - 1); + } } } -interface stack007i { +interface Stack007i { void recurse(int depth); } diff --git a/test/hotspot/jtreg/vmTestbase/nsk/stress/stack/stack008.java b/test/hotspot/jtreg/runtime/stack/Stack008.java similarity index 80% rename from test/hotspot/jtreg/vmTestbase/nsk/stress/stack/stack008.java rename to test/hotspot/jtreg/runtime/stack/Stack008.java index a90f237aa76..e1776a0bcb7 100644 --- a/test/hotspot/jtreg/vmTestbase/nsk/stress/stack/stack008.java +++ b/test/hotspot/jtreg/runtime/stack/Stack008.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2024, Oracle and/or its affiliates. All rights reserved. * 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,28 +48,19 @@ * Making it bigger could cause timeouts on other platform. * * @requires (vm.opt.DeoptimizeALot != true & vm.compMode != "Xcomp" & vm.pageSize == 4096) - * @run main/othervm/timeout=900 -Xss200K nsk.stress.stack.stack008 + * @run main/othervm/timeout=900 -Xss200K Stack008 */ -package nsk.stress.stack; - - -import java.io.PrintStream; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; -public class stack008 { +public class Stack008 { public static void main(String[] args) { - int exitCode = run(args, System.out); - System.exit(exitCode + 95); - } - - public static int run(String args[], PrintStream out) { int depth; // // Measure maximal recursion depth until stack overflow: // - for (depth = 100; ; depth += 100) + for (depth = 100; ; depth += 100) { try { invokeRecurse(depth); } catch (Throwable exception) { @@ -77,30 +68,27 @@ public static int run(String args[], PrintStream out) { if ((target instanceof StackOverflowError) || (target instanceof OutOfMemoryError)) break; // OK. - target.printStackTrace(out); - if (target instanceof ThreadDeath) - throw (ThreadDeath) target; - return 2; + target.printStackTrace(); + throw new RuntimeException(exception); } - out.println("Max. depth: " + depth); + } + System.out.println("Max. depth: " + depth); // // Provoke stack overflow multiple times: // - for (int i = 0; i < 100; i++) + for (int i = 0; i < 100; i++) { try { invokeRecurse(2 * depth); -// out.println("?"); +// System.out.println("?"); } catch (Throwable exception) { Throwable target = getTargetException(exception); if ((target instanceof StackOverflowError) || (target instanceof OutOfMemoryError)) continue; // OK. - target.printStackTrace(out); - if (target instanceof ThreadDeath) - throw (ThreadDeath) target; - return 2; + target.printStackTrace(); + throw new RuntimeException(exception); } - return 0; + } } private static Throwable getTargetException(Throwable exception) { @@ -118,7 +106,7 @@ private static Throwable getTargetException(Throwable exception) { } static Method method = null; - static stack008 instance = null; + static Stack008 instance = null; static Object params[] = null; private static void invokeRecurse(int depth) throws Exception { @@ -126,8 +114,8 @@ private static void invokeRecurse(int depth) throws Exception { // // Optimization trick: allocate once, use everywhere. // - instance = new stack008(); - method = stack008.class.getMethod("recurse"); + instance = new Stack008(); + method = Stack008.class.getMethod("recurse"); params = new Object[]{}; } // @@ -140,10 +128,11 @@ private static void invokeRecurse(int depth) throws Exception { int depth = 0; public void recurse() throws Exception { - if (depth > 0) + if (depth > 0) { // // Self-invoke via reflection: // invokeRecurse(depth - 1); + } } } diff --git a/test/hotspot/jtreg/vmTestbase/nsk/stress/stack/stack009.java b/test/hotspot/jtreg/runtime/stack/Stack009.java similarity index 70% rename from test/hotspot/jtreg/vmTestbase/nsk/stress/stack/stack009.java rename to test/hotspot/jtreg/runtime/stack/Stack009.java index b8f52d0a3f2..f2cbb51b304 100644 --- a/test/hotspot/jtreg/vmTestbase/nsk/stress/stack/stack009.java +++ b/test/hotspot/jtreg/runtime/stack/Stack009.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2024, Oracle and/or its affiliates. All rights reserved. * 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,49 +47,32 @@ * 4366625 (P4/S4) multiple stack overflow causes HS crash * * @requires vm.opt.DeoptimizeALot != true - * @run main/othervm/timeout=900 nsk.stress.stack.stack009 + * @run main/othervm/timeout=900 Stack009 */ -package nsk.stress.stack; - - -import java.io.PrintStream; - -public class stack009 { +public class Stack009 { public static void main(String[] args) { - int exitCode = run(args, System.out); - System.exit(exitCode + 95); - } - - public static int run(String args[], PrintStream out) { - for (int depth = 100; ; depth += 100) + for (int depth = 100; ; depth += 100) { try { recurse(depth); - } catch (Error error1) { - if (!(error1 instanceof StackOverflowError) && - !(error1 instanceof OutOfMemoryError)) - throw error1; + } catch (StackOverflowError | OutOfMemoryError error1) { - out.println("Max. depth: " + depth); + System.out.println("Max. depth: " + depth); try { recurse(10 * depth); - out.println("?"); - } catch (Error error2) { - if (!(error2 instanceof StackOverflowError) && - !(error2 instanceof OutOfMemoryError)) - throw error2; - - // Stack overflow is OK here. + System.out.println("?"); + } catch (StackOverflowError | OutOfMemoryError error2) { + // ignore } - break; } - return 0; + } } static void recurse(int depth) { - if (depth > 0) + if (depth > 0) { recurse(depth - 1); + } } } diff --git a/test/hotspot/jtreg/vmTestbase/nsk/stress/stack/stack010.java b/test/hotspot/jtreg/runtime/stack/Stack010.java similarity index 67% rename from test/hotspot/jtreg/vmTestbase/nsk/stress/stack/stack010.java rename to test/hotspot/jtreg/runtime/stack/Stack010.java index 6c4c159b58f..142c7ab6cb2 100644 --- a/test/hotspot/jtreg/vmTestbase/nsk/stress/stack/stack010.java +++ b/test/hotspot/jtreg/runtime/stack/Stack010.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2024, Oracle and/or its affiliates. All rights reserved. * 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,99 +47,82 @@ * 4366625 (P4/S4) multiple stack overflow causes HS crash * * @requires vm.opt.DeoptimizeALot != true - * @run main/othervm/timeout=900 nsk.stress.stack.stack010 + * @run main/othervm/timeout=900 Stack010 */ -package nsk.stress.stack; - - -import java.io.PrintStream; - -public class stack010 extends Thread { - final static int THREADS = 10; - final static int CYCLES = 10; +public class Stack010 extends Thread { + final static int THREADS = 1; + final static int CYCLES = 1; public static void main(String[] args) { - int exitCode = run(args, System.out); - System.exit(exitCode + 95); - } - - public static int run(String args[], PrintStream out) { // // Measure maximal recursion depth until stack overflow: // int maxDepth = 0; - for (int depth = 10; ; depth += 10) + for (int depth = 10; ; depth += 10) { try { recurse(depth); maxDepth = depth; - } catch (StackOverflowError soe) { - break; - } catch (OutOfMemoryError oome) { + } catch (StackOverflowError | OutOfMemoryError err) { break; } - out.println("Max. depth: " + maxDepth); + } + System.out.println("Max. depth: " + maxDepth); // // Execute multiple threads repeatedly provoking stack overflows: // - stack010 threads[] = new stack010[THREADS]; + Stack010 threads[] = new Stack010[THREADS]; for (int i = 0; i < threads.length; i++) { - threads[i] = new stack010(); - threads[i].depthToTry = 10 * maxDepth; + threads[i] = new Stack010(); + threads[i].depthToTry = 100 * maxDepth; threads[i].start(); } - for (int i = 0; i < threads.length; i++) - if (threads[i].isAlive()) + for (int i = 0; i < threads.length; i++) { + if (threads[i].isAlive()) { try { threads[i].join(); } catch (InterruptedException exception) { - exception.printStackTrace(out); - return 2; + throw new RuntimeException(exception); } - + } + } // // Check if unexpected exceptions were not thrown: // - int exitCode = 0; - for (int i = 0; i < threads.length; i++) + for (int i = 0; i < threads.length; i++) { if (threads[i].thrown != null) { - threads[i].thrown.printStackTrace(out); - exitCode = 2; + threads[i].thrown.printStackTrace(); + throw new RuntimeException("Exception in the thread " + threads[i], threads[i].thrown); } - - if (exitCode != 0) - out.println("# TEST FAILED"); - return exitCode; + } } int depthToTry = 0; Throwable thrown = null; public void run() { - for (int i = 0; i < CYCLES; i++) + for (int i = 0; i < CYCLES; i++) { try { + System.out.println("depth = " +depthToTry); recurse(depthToTry); throw new Exception( "TEST_RFE: no stack overflow thrown" + ", need to try deeper recursion?"); - } catch (StackOverflowError soe) { - // It's OK: stack overflow was expected. - } catch (OutOfMemoryError oome) { - // Also OK: out of memory may indacate stack overflow. - + } catch (StackOverflowError | OutOfMemoryError err) { + // It's OK } catch (Throwable throwable) { - if (throwable instanceof ThreadDeath) - throw (ThreadDeath) throwable; // It isn't OK! thrown = throwable; break; } + } } static void recurse(int depth) { - if (depth > 0) + if (depth > 0) { recurse(depth - 1); + } } } diff --git a/test/hotspot/jtreg/vmTestbase/nsk/stress/stack/stack011.java b/test/hotspot/jtreg/runtime/stack/Stack011.java similarity index 70% rename from test/hotspot/jtreg/vmTestbase/nsk/stress/stack/stack011.java rename to test/hotspot/jtreg/runtime/stack/Stack011.java index 81e26f575d7..423e009c912 100644 --- a/test/hotspot/jtreg/vmTestbase/nsk/stress/stack/stack011.java +++ b/test/hotspot/jtreg/runtime/stack/Stack011.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2024, Oracle and/or its affiliates. All rights reserved. * 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,99 +47,81 @@ * 4366625 (P4/S4) multiple stack overflow causes HS crash * * @requires vm.opt.DeoptimizeALot != true - * @run main/othervm/timeout=900 nsk.stress.stack.stack011 + * @run main/othervm/timeout=900 Stack011 */ -package nsk.stress.stack; - - -import java.io.PrintStream; - -public class stack011 extends Thread { +public class Stack011 extends Thread { final static int THREADS = 10; final static int CYCLES = 10; public static void main(String[] args) { - int exitCode = run(args, System.out); - System.exit(exitCode + 95); - } - - public static int run(String args[], PrintStream out) { // // Measure maximal recursion depth until stack overflow: // int maxDepth = 0; - for (int depth = 10; ; depth += 10) + for (int depth = 10; ; depth += 10) { try { recurse(depth); maxDepth = depth; - } catch (StackOverflowError soe) { - break; - } catch (OutOfMemoryError oome) { + } catch (StackOverflowError | OutOfMemoryError soe) { break; } - out.println("Max. depth: " + maxDepth); + } + System.out.println("Max. depth: " + maxDepth); // // Execute multiple threads repeatedly provoking stack overflows: // - stack011 threads[] = new stack011[THREADS]; + Stack011 threads[] = new Stack011[THREADS]; for (int i = 0; i < threads.length; i++) { - threads[i] = new stack011(); + threads[i] = new Stack011(); threads[i].depthToTry = 10 * maxDepth; threads[i].start(); } - for (int i = 0; i < threads.length; i++) - if (threads[i].isAlive()) + for (int i = 0; i < threads.length; i++) { + if (threads[i].isAlive()) { try { threads[i].join(); } catch (InterruptedException exception) { - exception.printStackTrace(out); - return 2; + throw new RuntimeException(exception); } - + } + } // // Check if unexpected exceptions were not thrown: // - int exitCode = 0; - for (int i = 0; i < threads.length; i++) + for (int i = 0; i < threads.length; i++) { if (threads[i].thrown != null) { - threads[i].thrown.printStackTrace(out); - exitCode = 2; + threads[i].thrown.printStackTrace(); + throw new RuntimeException("Exception in the thread " + threads[i], threads[i].thrown); } - - if (exitCode != 0) - out.println("# TEST FAILED"); - return exitCode; + } } int depthToTry = 0; Throwable thrown = null; public void run() { - for (int i = 0; i < CYCLES; i++) + for (int i = 0; i < CYCLES; i++) { try { recurse(depthToTry); throw new Exception( "TEST_RFE: no stack overflow thrown" + ", need to try deeper recursion?"); - } catch (StackOverflowError error) { - // It's OK: stack overflow was expected. - } catch (OutOfMemoryError oome) { - // Also OK: recursion may result in memory lack. - + } catch (StackOverflowError | OutOfMemoryError err) { + // It's OK } catch (Throwable throwable) { - if (throwable instanceof ThreadDeath) - throw (ThreadDeath) throwable; // It isn't OK! thrown = throwable; break; } + } } final static void recurse(int depth) { - if (depth > 0) + if (depth > 0) { recurse(depth - 1); + } } } diff --git a/test/hotspot/jtreg/vmTestbase/nsk/stress/stack/stack012.java b/test/hotspot/jtreg/runtime/stack/Stack012.java similarity index 70% rename from test/hotspot/jtreg/vmTestbase/nsk/stress/stack/stack012.java rename to test/hotspot/jtreg/runtime/stack/Stack012.java index 6dc33a83cc8..1edbe215043 100644 --- a/test/hotspot/jtreg/vmTestbase/nsk/stress/stack/stack012.java +++ b/test/hotspot/jtreg/runtime/stack/Stack012.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2024, Oracle and/or its affiliates. All rights reserved. * 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,100 +48,82 @@ * 4366625 (P4/S4) multiple stack overflow causes HS crash * * @requires vm.opt.DeoptimizeALot != true - * @run main/othervm/timeout=900 nsk.stress.stack.stack012 + * @run main/othervm/timeout=900 Stack012 */ -package nsk.stress.stack; - - -import java.io.PrintStream; - -public class stack012 extends Thread { +public class Stack012 extends Thread { final static int THREADS = 10; final static int CYCLES = 10; public static void main(String[] args) { - int exitCode = run(args, System.out); - System.exit(exitCode + 95); - } - - public static int run(String args[], PrintStream out) { - stack012 test = new stack012(); + Stack012 test = new Stack012(); // // Measure maximal recursion depth until stack overflow: // int maxDepth = 0; - for (int depth = 10; ; depth += 10) + for (int depth = 10; ; depth += 10) { try { test.recurse(depth); maxDepth = depth; - } catch (StackOverflowError soe) { - break; - } catch (OutOfMemoryError oome) { + } catch (StackOverflowError | OutOfMemoryError err) { break; } - out.println("Max. depth: " + maxDepth); + } + System.out.println("Max. depth: " + maxDepth); // // Execute multiple threads repeatedly provoking stack overflows: // - stack012 threads[] = new stack012[THREADS]; + Stack012 threads[] = new Stack012[THREADS]; for (int i = 0; i < threads.length; i++) { - threads[i] = new stack012(); + threads[i] = new Stack012(); threads[i].depthToTry = 10 * maxDepth; threads[i].start(); } - for (int i = 0; i < threads.length; i++) - if (threads[i].isAlive()) + for (int i = 0; i < threads.length; i++) { + if (threads[i].isAlive()) { try { threads[i].join(); } catch (InterruptedException exception) { - exception.printStackTrace(out); - return 2; + throw new RuntimeException(exception); } - + } + } // // Check if unexpected exceptions were not thrown: // - int exitCode = 0; - for (int i = 0; i < threads.length; i++) + for (int i = 0; i < threads.length; i++) { if (threads[i].thrown != null) { - threads[i].thrown.printStackTrace(out); - exitCode = 2; + threads[i].thrown.printStackTrace(); + throw new RuntimeException("Exception in the thread " + threads[i], threads[i].thrown); } - - if (exitCode != 0) - out.println("# TEST FAILED"); - return exitCode; + } } int depthToTry = 0; Throwable thrown = null; public void run() { - for (int i = 0; i < CYCLES; i++) + for (int i = 0; i < CYCLES; i++) { try { this.recurse(depthToTry); throw new Exception( "TEST_RFE: no stack overflow thrown" + ", need to try deeper recursion?"); - } catch (StackOverflowError error) { - // It's OK: stack overflow was expected. - } catch (OutOfMemoryError oome) { - // Also OK: invocation may result in out of memory. - + } catch (StackOverflowError | OutOfMemoryError err) { + // It's OK } catch (Throwable throwable) { - if (throwable instanceof ThreadDeath) - throw (ThreadDeath) throwable; // It isn't OK! thrown = throwable; break; } + } } final void recurse(int depth) { - if (depth > 0) + if (depth > 0) { recurse(depth - 1); + } } } diff --git a/test/hotspot/jtreg/vmTestbase/nsk/stress/stack/stack013.java b/test/hotspot/jtreg/runtime/stack/Stack013.java similarity index 70% rename from test/hotspot/jtreg/vmTestbase/nsk/stress/stack/stack013.java rename to test/hotspot/jtreg/runtime/stack/Stack013.java index 94a3ef622ef..6c17b780d0e 100644 --- a/test/hotspot/jtreg/vmTestbase/nsk/stress/stack/stack013.java +++ b/test/hotspot/jtreg/runtime/stack/Stack013.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2024, Oracle and/or its affiliates. All rights reserved. * 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,81 +47,67 @@ * 4366625 (P4/S4) multiple stack overflow causes HS crash * * @requires vm.opt.DeoptimizeALot != true - * @run main/othervm/timeout=900 nsk.stress.stack.stack013 + * @run main/othervm/timeout=900 Stack013 */ -package nsk.stress.stack; - - -import java.io.PrintStream; - -public class stack013 extends stack013i { +public class Stack013 extends Stack013i { final static int THREADS = 10; final static int CYCLES = 10; public static void main(String[] args) { - int exitCode = run(args, System.out); - System.exit(exitCode + 95); - } - - public static int run(String args[], PrintStream out) { - stack013i test = new stack013(); + Stack013i test = new Stack013(); // // Measure maximal recursion depth until stack overflow: // int maxDepth = 0; - for (int depth = 10; ; depth += 10) + for (int depth = 10; ; depth += 10) { try { test.recurse(depth); maxDepth = depth; - } catch (StackOverflowError soe) { - break; - } catch (OutOfMemoryError oome) { + } catch (StackOverflowError | OutOfMemoryError err) { break; } - out.println("Max. depth: " + maxDepth); + } + System.out.println("Max. depth: " + maxDepth); // // Execute multiple threads repeatedly provoking stack overflows: // - stack013i threads[] = new stack013i[THREADS]; + Stack013i threads[] = new Stack013i[THREADS]; for (int i = 0; i < threads.length; i++) { - threads[i] = new stack013(); + threads[i] = new Stack013(); threads[i].depthToTry = 10 * maxDepth; threads[i].cycles = CYCLES; threads[i].start(); } - for (int i = 0; i < threads.length; i++) - if (threads[i].isAlive()) + for (int i = 0; i < threads.length; i++) { + if (threads[i].isAlive()) { try { threads[i].join(); } catch (InterruptedException exception) { - exception.printStackTrace(out); - return 2; + throw new RuntimeException(exception); } - + } + } // // Check if unexpected exceptions were thrown: // - int exitCode = 0; - for (int i = 0; i < threads.length; i++) + for (int i = 0; i < threads.length; i++) { if (threads[i].thrown != null) { - threads[i].thrown.printStackTrace(out); - exitCode = 2; + threads[i].thrown.printStackTrace(); + throw new RuntimeException("Exception in the thread " + threads[i], threads[i].thrown); } - - if (exitCode != 0) - out.println("# TEST FAILED"); - return exitCode; + } } void recurse(int depth) { - if (depth > 0) + if (depth > 0) { recurse(depth - 1); + } } } -abstract class stack013i extends Thread { +abstract class Stack013i extends Thread { // // Pure virtual method: // @@ -135,24 +121,20 @@ public void run() { // // Provoke multiple stack overflows: // - for (int i = 0; i < cycles; i++) + for (int i = 0; i < cycles; i++) { try { recurse(depthToTry); throw new Exception( "TEST_RFE: no stack overflow thrown" + ", need to try deeper recursion?"); - } catch (StackOverflowError error) { - // It's OK: stack overflow was expected. - } catch (OutOfMemoryError oome) { - // Also OK: out of memory is eligible here. - + } catch (StackOverflowError | OutOfMemoryError err) { + // It's OK } catch (Throwable throwable) { - if (throwable instanceof ThreadDeath) - throw (ThreadDeath) throwable; // It isn't OK! thrown = throwable; break; } + } } } diff --git a/test/hotspot/jtreg/vmTestbase/nsk/stress/stack/stack014.java b/test/hotspot/jtreg/runtime/stack/Stack014.java similarity index 71% rename from test/hotspot/jtreg/vmTestbase/nsk/stress/stack/stack014.java rename to test/hotspot/jtreg/runtime/stack/Stack014.java index 2f7f79331e2..972f386c1f1 100644 --- a/test/hotspot/jtreg/vmTestbase/nsk/stress/stack/stack014.java +++ b/test/hotspot/jtreg/runtime/stack/Stack014.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2024, Oracle and/or its affiliates. All rights reserved. * 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,81 +50,67 @@ * 4366625 (P4/S4) multiple stack overflow causes HS crash * * @requires vm.opt.DeoptimizeALot != true - * @run main/othervm/timeout=900 nsk.stress.stack.stack014 + * @run main/othervm/timeout=900 Stack014 */ -package nsk.stress.stack; - - -import java.io.PrintStream; - -public class stack014 extends stack014i { +public class Stack014 extends Stack014i { final static int THREADS = 10; final static int CYCLES = 10; public static void main(String[] args) { - int exitCode = run(args, System.out); - System.exit(exitCode + 95); - } - - public static int run(String args[], PrintStream out) { - stack014i test = new stack014(); + Stack014i test = new Stack014(); // // Measure maximal recursion depth until stack overflow: // int maxDepth = 0; - for (int depth = 10; ; depth += 10) + for (int depth = 10; ; depth += 10) { try { test.recurse(depth); maxDepth = depth; - } catch (StackOverflowError soe) { - break; - } catch (OutOfMemoryError oome) { + } catch (StackOverflowError | OutOfMemoryError err) { break; } - out.println("Max. depth: " + maxDepth); + } + System.out.println("Max. depth: " + maxDepth); // // Execute multiple threads repeatedly provoking stack overflows: // - stack014i threads[] = new stack014i[THREADS]; + Stack014i threads[] = new Stack014i[THREADS]; for (int i = 0; i < threads.length; i++) { - threads[i] = new stack014(); + threads[i] = new Stack014(); threads[i].depthToTry = 10 * maxDepth; threads[i].cycles = CYCLES; threads[i].start(); } - for (int i = 0; i < threads.length; i++) - if (threads[i].isAlive()) + for (int i = 0; i < threads.length; i++) { + if (threads[i].isAlive()) { try { threads[i].join(); } catch (InterruptedException exception) { - exception.printStackTrace(out); - return 2; + throw new RuntimeException(exception); } - + } + } // // Check if unexpected exceptions were thrown: // - int exitCode = 0; - for (int i = 0; i < threads.length; i++) + for (int i = 0; i < threads.length; i++) { if (threads[i].thrown != null) { - threads[i].thrown.printStackTrace(out); - exitCode = 2; + threads[i].thrown.printStackTrace(); + throw new RuntimeException("Exception in the thread " + threads[i], threads[i].thrown); } - - if (exitCode != 0) - out.println("# TEST FAILED"); - return exitCode; + } } synchronized void recurse(int depth) { - if (depth > 0) + if (depth > 0) { recurse(depth - 1); + } } } -abstract class stack014i extends Thread { +abstract class Stack014i extends Thread { // // Pure virtual method: // @@ -138,24 +124,20 @@ public void run() { // // Provoke multiple stack overflows: // - for (int i = 0; i < cycles; i++) + for (int i = 0; i < cycles; i++) { try { recurse(depthToTry); throw new Exception( "TEST_RFE: no stack overflow thrown" + ", need to try deeper recursion?"); - } catch (StackOverflowError error) { - // It's OK: stack overflow was expected. - } catch (OutOfMemoryError oome) { - // Also OK: if there is no memory for stack expansion. - + } catch (StackOverflowError | OutOfMemoryError err) { + // It's OK } catch (Throwable throwable) { - if (throwable instanceof ThreadDeath) - throw (ThreadDeath) throwable; // It isn't OK! thrown = throwable; break; } + } } } diff --git a/test/hotspot/jtreg/vmTestbase/nsk/stress/stack/stack015.java b/test/hotspot/jtreg/runtime/stack/Stack015.java similarity index 70% rename from test/hotspot/jtreg/vmTestbase/nsk/stress/stack/stack015.java rename to test/hotspot/jtreg/runtime/stack/Stack015.java index 0a2d108af9d..3bceca2119b 100644 --- a/test/hotspot/jtreg/vmTestbase/nsk/stress/stack/stack015.java +++ b/test/hotspot/jtreg/runtime/stack/Stack015.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2024, Oracle and/or its affiliates. All rights reserved. * 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,88 +48,74 @@ * 4366625 (P4/S4) multiple stack overflow causes HS crash * * @requires vm.opt.DeoptimizeALot != true - * @run main/othervm/timeout=900 nsk.stress.stack.stack015 + * @run main/othervm/timeout=900 Stack015 */ -package nsk.stress.stack; - - -import java.io.PrintStream; - -public class stack015 extends stack015i { +public class Stack015 extends Stack015i { final static int THREADS = 10; final static int CYCLES = 10; final static int STEP = 10; final static int RESERVE = 10; public static void main(String[] args) { - int exitCode = run(args, System.out); - System.exit(exitCode + 95); - } - - public static int run(String args[], PrintStream out) { // - // The test will invoke the particular stack015.recurse() + // The test will invoke the particular Stack015.recurse() // method via abstract test.recurse() invocations. // - stack015i test = new stack015(); - stack015i.test = test; + Stack015i test = new Stack015(); + Stack015i.test = test; // // Measure maximal recursion depth until stack overflow: // int maxDepth = 0; - for (int depth = 0; ; depth += STEP) + for (int depth = 0; ; depth += STEP) { try { test.recurse(depth); maxDepth = depth; - } catch (StackOverflowError soe) { - break; - } catch (OutOfMemoryError oome) { + } catch (StackOverflowError | OutOfMemoryError err) { break; } - out.println("Max. depth: " + maxDepth); + } + System.out.println("Max. depth: " + maxDepth); // // Execute multiple threads repeatedly provoking stack overflows: // - stack015i threads[] = new stack015i[THREADS]; + Stack015i threads[] = new Stack015i[THREADS]; for (int i = 0; i < threads.length; i++) { - threads[i] = new stack015(); + threads[i] = new Stack015(); threads[i].depthToTry = RESERVE * maxDepth; threads[i].start(); } - for (int i = 0; i < threads.length; i++) - if (threads[i].isAlive()) + for (int i = 0; i < threads.length; i++) { + if (threads[i].isAlive()) { try { threads[i].join(); } catch (InterruptedException exception) { - exception.printStackTrace(out); - return 2; + throw new RuntimeException(exception); } - + } + } // // Check if unexpected exceptions were thrown: // - int exitCode = 0; - for (int i = 0; i < threads.length; i++) + for (int i = 0; i < threads.length; i++) { if (threads[i].thrown != null) { - threads[i].thrown.printStackTrace(out); - exitCode = 2; + threads[i].thrown.printStackTrace(); + throw new RuntimeException("Exception in the thread " + threads[i], threads[i].thrown); } - - if (exitCode != 0) - out.println("# TEST FAILED"); - return exitCode; + } } synchronized void syncRecurse(int depth) { - if (depth > 0) + if (depth > 0) { syncRecurse(depth - 1); + } } } -abstract class stack015i extends Thread { +abstract class Stack015i extends Thread { // // Pure virtual method: // @@ -139,24 +125,25 @@ void recurse(int depth) { // // Stack overflow must occur here: // - syncRecurse(stack015.STEP); + syncRecurse(Stack015.STEP); // // If no stack overflow occured, try again with deeper stack: // - if (depth > 0) + if (depth > 0) { recurse(depth - 1); + } } Throwable thrown = null; int depthToTry; - static stack015i test; + static Stack015i test; public void run() { // // Provoke multiple stack overflows: // - for (int i = 0; i < stack015.CYCLES; i++) + for (int i = 0; i < Stack015.CYCLES; i++) { try { // // All threads invoke the same synchronized method: @@ -167,17 +154,13 @@ public void run() { "TEST_RFE: no stack overflow thrown" + ", need to try deeper recursion?"); - } catch (StackOverflowError error) { - // It's OK: stack overflow was expected. - } catch (OutOfMemoryError oome) { - // Also OK: there may be no memory for stack expansion. - + } catch (StackOverflowError | OutOfMemoryError err) { + // It's OK } catch (Throwable throwable) { - if (throwable instanceof ThreadDeath) - throw (ThreadDeath) throwable; // It isn't OK! thrown = throwable; break; } + } } } diff --git a/test/hotspot/jtreg/vmTestbase/nsk/stress/stack/stack016.java b/test/hotspot/jtreg/runtime/stack/Stack016.java similarity index 67% rename from test/hotspot/jtreg/vmTestbase/nsk/stress/stack/stack016.java rename to test/hotspot/jtreg/runtime/stack/Stack016.java index dd33dd5e02c..dc2dbe7d105 100644 --- a/test/hotspot/jtreg/vmTestbase/nsk/stress/stack/stack016.java +++ b/test/hotspot/jtreg/runtime/stack/Stack016.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2024, Oracle and/or its affiliates. All rights reserved. * 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,21 +49,12 @@ * 4366625 (P4/S4) multiple stack overflow causes HS crash * * @requires (vm.opt.DeoptimizeALot != true & vm.compMode != "Xcomp") - * @library /vmTestbase - * @build nsk.share.Terminator - * @run main/othervm/timeout=900 -Xint -Xss448K nsk.stress.stack.stack016 -eager - * @run main/othervm/timeout=900 -Xcomp -Xss448K nsk.stress.stack.stack016 -eager - * @run main/othervm/timeout=900 -Xcomp -XX:-TieredCompilation -Xss448K nsk.stress.stack.stack016 -eager + * @run main/othervm/timeout=900 -Xint -Xss448K Stack016 + * @run main/othervm/timeout=900 -Xcomp -Xss448K Stack016 + * @run main/othervm/timeout=900 -Xcomp -XX:-TieredCompilation -Xss448K Stack016 */ -package nsk.stress.stack; - - -import nsk.share.Terminator; - -import java.io.PrintStream; - -public class stack016 extends Thread { +public class Stack016 extends Thread { private final static int THREADS = 10; private final static int CYCLES = 10; private final static int STEP = 10; @@ -71,37 +62,11 @@ public class stack016 extends Thread { private final static int PROBES = STEP * RESERVE; public static void main(String[] args) { - int exitCode = run(args, System.out); - System.exit(exitCode + 95); + Stack016 test = new Stack016(); + test.doRun(); } - public static int run(String args[], PrintStream out) { - verbose = false; - boolean eager = false; - for (int i = 0; i < args.length; i++) - if (args[i].toLowerCase().equals("-verbose")) - verbose = true; - else if (args[i].toLowerCase().equals("-eager")) - eager = true; - if (!eager) - Terminator.appoint(Terminator.parseAppointment(args)); - stack016.out = out; - stack016 test = new stack016(); - return test.doRun(); - } - - private static boolean verbose; - private static PrintStream out; - - private void display(Object message) { - if (!verbose) - return; - synchronized (out) { - out.println(message.toString()); - } - } - - private int doRun() { + private void doRun() { // // Measure recursive depth before stack overflow: // @@ -114,14 +79,14 @@ private int doRun() { break; } } - out.println("Maximal recursion depth: " + maxDepth); + System.out.println("Maximal recursion depth: " + maxDepth); // // Run the tested threads: // - stack016 threads[] = new stack016[THREADS]; + Stack016 threads[] = new Stack016[THREADS]; for (int i = 0; i < threads.length; i++) { - threads[i] = new stack016(); + threads[i] = new Stack016(); threads[i].setName("Thread: " + (i + 1) + "/" + THREADS); threads[i].depthToTry = RESERVE * maxDepth; threads[i].start(); @@ -131,8 +96,7 @@ private int doRun() { try { threads[i].join(); } catch (InterruptedException exception) { - exception.printStackTrace(out); - return 2; + throw new RuntimeException(exception); } } } @@ -140,16 +104,12 @@ private int doRun() { // // Check if unexpected exceptions were thrown: // - int exitCode = 0; for (int i = 0; i < threads.length; i++) { if (threads[i].thrown != null) { - threads[i].thrown.printStackTrace(out); - exitCode = 2; + threads[i].thrown.printStackTrace(); + throw new RuntimeException("Exception in the thread " + threads[i], threads[i].thrown); } } - if (exitCode != 0) - out.println("# TEST FAILED"); - return exitCode; } private int stackTop = 0; @@ -161,11 +121,7 @@ private void trickyRecurse(int depth) { if (depth > 0) { try { trickyRecurse(depth - 1); - } catch (Error error) { - if (!(error instanceof StackOverflowError) && - !(error instanceof OutOfMemoryError)) - throw error; - + } catch (StackOverflowError | OutOfMemoryError error) { // // Provoke more stack overflow, // if current stack is deep enough: @@ -180,28 +136,24 @@ private void trickyRecurse(int depth) { } private static void recurse(int depth) { - if (depth > 0) + if (depth > 0) { recurse(depth - 1); + } } public void run() { String threadName = Thread.currentThread().getName(); for (int i = 1; i <= CYCLES; i++) { try { - display(threadName + ", iteration: " + i + "/" + CYCLES + + System.out.println(threadName + ", iteration: " + i + "/" + CYCLES + ", depthToTry: " + depthToTry); trickyRecurse(depthToTry); throw new Error( "TEST_BUG: trickyRecursion() must throw an error anyway!"); - } catch (StackOverflowError error) { - // It's OK: stack overflow was expected. - } catch (OutOfMemoryError oome) { - // Also OK, if there is no memory for stack expansion. - + } catch (StackOverflowError | OutOfMemoryError err) { + // It's OK } catch (Throwable throwable) { - if (throwable instanceof ThreadDeath) - throw (ThreadDeath) throwable; thrown = throwable; break; } diff --git a/test/hotspot/jtreg/vmTestbase/nsk/stress/stack/stack017.java b/test/hotspot/jtreg/runtime/stack/Stack017.java similarity index 61% rename from test/hotspot/jtreg/vmTestbase/nsk/stress/stack/stack017.java rename to test/hotspot/jtreg/runtime/stack/Stack017.java index fcb18ed216e..47db5886a00 100644 --- a/test/hotspot/jtreg/vmTestbase/nsk/stress/stack/stack017.java +++ b/test/hotspot/jtreg/runtime/stack/Stack017.java @@ -42,99 +42,59 @@ * 4366625 (P4/S4) multiple stack overflow causes HS crash * * @requires (vm.opt.DeoptimizeALot != true & vm.compMode != "Xcomp" & vm.pageSize == 4096) - * @library /vmTestbase - * @build nsk.share.Terminator - * @run main/othervm/timeout=900 -Xss220K nsk.stress.stack.stack017 -eager + * @run main/othervm/timeout=900 -Xss220K Stack017 */ -package nsk.stress.stack; - - -import nsk.share.Terminator; - -import java.io.PrintStream; - -public class stack017 extends Thread { +public class Stack017 extends Thread { private final static int THREADS = 10; private final static int CYCLES = 10; private final static int PROBES = 100; public static void main(String[] args) { - int exitCode = run(args, System.out); - System.exit(exitCode + 95); - } - - public static int run(String args[], PrintStream out) { - verbose = false; - boolean eager = false; - for (int i = 0; i < args.length; i++) - if (args[i].toLowerCase().equals("-verbose")) - verbose = true; - else if (args[i].toLowerCase().equals("-eager")) - eager = true; - if (!eager) - Terminator.appoint(Terminator.parseAppointment(args)); - stack017.out = out; - stack017 test = new stack017(); - return test.doRun(); - } - - private static boolean verbose; - private static PrintStream out; - - private void display(Object message) { - if (!verbose) - return; - synchronized (out) { - out.println(message.toString()); - } + Stack017 test = new Stack017(); + test.doRun(); } private static int depthToTry; - private int doRun() { + private void doRun() { // // Measure recursive depth before stack overflow: // try { recurse(0); - } catch (StackOverflowError soe) { - } catch (OutOfMemoryError oome) { + } catch (StackOverflowError | OutOfMemoryError err) { } - out.println("Maximal recursion depth: " + maxDepth); + System.out.println("Maximal recursion depth: " + maxDepth); depthToTry = maxDepth; // // Run the tested threads: // - stack017 threads[] = new stack017[THREADS]; + Stack017 threads[] = new Stack017[THREADS]; for (int i = 0; i < threads.length; i++) { - threads[i] = new stack017(); + threads[i] = new Stack017(); threads[i].setName("Thread: " + (i + 1) + "/" + THREADS); threads[i].start(); } - for (int i = 0; i < threads.length; i++) - if (threads[i].isAlive()) + for (int i = 0; i < threads.length; i++) { + if (threads[i].isAlive()) { try { threads[i].join(); } catch (InterruptedException exception) { - exception.printStackTrace(out); - return 2; + throw new RuntimeException(exception); } - + } + } // // Check if unexpected exceptions were thrown: // - int exitCode = 0; - for (int i = 0; i < threads.length; i++) + for (int i = 0; i < threads.length; i++) { if (threads[i].thrown != null) { - threads[i].thrown.printStackTrace(out); - exitCode = 2; + threads[i].thrown.printStackTrace(); + throw new RuntimeException("Exception in the thread " + threads[i], threads[i].thrown); } - - if (exitCode != 0) - out.println("# TEST FAILED"); - return exitCode; + } } private int maxDepth = 0; @@ -148,11 +108,7 @@ private void trickyRecurse(int depth) { try { maxDepth = depth; trickyRecurse(depth + 1); - } catch (Error error) { - if (!(error instanceof StackOverflowError) && - !(error instanceof OutOfMemoryError)) - throw error; - + } catch (StackOverflowError | OutOfMemoryError error) { // // Stack problem caught: provoke it again, // if current stack is enough deep: @@ -169,19 +125,14 @@ public void run() { String threadName = Thread.currentThread().getName(); for (int i = 1; i <= CYCLES; i++) try { - display(threadName + ", iteration: " + i + "/" + CYCLES); + System.out.println(threadName + ", iteration: " + i + "/" + CYCLES); trickyRecurse(0); throw new Exception( "TEST_BUG: stack overflow was expected!"); - } catch (StackOverflowError oome) { - // It's OK: stack overflow was expected. - } catch (OutOfMemoryError oome) { - // Also OK, if there is no memory for stack expansion. - + } catch (StackOverflowError | OutOfMemoryError err) { + // It's OK } catch (Throwable throwable) { - if (throwable instanceof ThreadDeath) - throw (ThreadDeath) throwable; // It isn't OK! thrown = throwable; break; diff --git a/test/hotspot/jtreg/vmTestbase/nsk/stress/stack/stack018.java b/test/hotspot/jtreg/runtime/stack/Stack018.java similarity index 72% rename from test/hotspot/jtreg/vmTestbase/nsk/stress/stack/stack018.java rename to test/hotspot/jtreg/runtime/stack/Stack018.java index 48fe41a67fa..57c8151e224 100644 --- a/test/hotspot/jtreg/vmTestbase/nsk/stress/stack/stack018.java +++ b/test/hotspot/jtreg/runtime/stack/Stack018.java @@ -47,58 +47,24 @@ * 4366625 (P4/S4) multiple stack overflow causes HS crash * * @requires (vm.opt.DeoptimizeALot != true & vm.compMode != "Xcomp" & vm.pageSize == 4096) - * @library /vmTestbase - * @build nsk.share.Terminator - * @run main/othervm/timeout=900 -Xss220K nsk.stress.stack.stack018 -eager + * @run main/othervm/timeout=900 -Xss220K Stack018 */ -package nsk.stress.stack; - - -import nsk.share.Terminator; - -import java.io.PrintStream; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; -public class stack018 extends Thread { +public class Stack018 extends Thread { private final static int THREADS = 10; private final static int CYCLES = 10; private final static int STEP = 100; private final static int RESERVE = 100; public static void main(String[] args) { - int exitCode = run(args, System.out); - System.exit(exitCode + 95); - } - - public static int run(String args[], PrintStream out) { - verbose = false; - boolean eager = false; - for (int i = 0; i < args.length; i++) - if (args[i].toLowerCase().equals("-verbose")) - verbose = true; - else if (args[i].toLowerCase().equals("-eager")) - eager = true; - if (!eager) - Terminator.appoint(Terminator.parseAppointment(args)); - stack018.out = out; - stack018 test = new stack018(); - return test.doRun(); - } - - private static boolean verbose; - private static PrintStream out; - - private void display(Object message) { - if (!verbose) - return; - synchronized (out) { - out.println(message.toString()); - } + Stack018 test = new Stack018(); + test.doRun(); } - private int doRun() { + private void doRun() { // // Measure maximal recursion depth until stack overflow: // @@ -112,46 +78,41 @@ private int doRun() { if ((target instanceof StackOverflowError) || (target instanceof OutOfMemoryError)) break; // OK. - target.printStackTrace(out); - if (target instanceof ThreadDeath) - throw (ThreadDeath) target; - return 2; + target.printStackTrace(); + throw new RuntimeException(exception); } - out.println("Maximal recursion depth: " + maxDepth); + System.out.println("Maximal recursion depth: " + maxDepth); // // Run the tested threads: // - stack018 threads[] = new stack018[THREADS]; + Stack018 threads[] = new Stack018[THREADS]; for (int i = 0; i < threads.length; i++) { - threads[i] = new stack018(); + threads[i] = new Stack018(); threads[i].setName("Thread: " + (i + 1) + "/" + THREADS); threads[i].depthToTry = RESERVE * maxDepth; threads[i].start(); } - for (int i = 0; i < threads.length; i++) - if (threads[i].isAlive()) + for (int i = 0; i < threads.length; i++) { + if (threads[i].isAlive()) { try { threads[i].join(); } catch (InterruptedException exception) { - exception.printStackTrace(out); - return 2; + throw new RuntimeException(exception); } - + } + } // // Check if unexpected exceptions were thrown: // int exitCode = 0; - for (int i = 0; i < threads.length; i++) + for (int i = 0; i < threads.length; i++) { if (threads[i].thrown != null) { - out.println("# " + threads[i].getName() + System.out.println("# " + threads[i].getName() + ": " + threads[i].thrown); - exitCode = 2; + throw new RuntimeException("Exception in the thread " + threads[i], threads[i].thrown); } - - if (exitCode != 0) - out.println("# TEST FAILED"); - return exitCode; + } } private int depthToTry = 0; @@ -161,7 +122,7 @@ public void run() { String threadName = Thread.currentThread().getName(); for (int i = 1; i <= CYCLES; i++) try { - display(threadName + ", iteration: " + i + "/" + CYCLES); + System.out.println(threadName + ", iteration: " + i + "/" + CYCLES); invokeRecurse(depthToTry); throw new Error("TEST_RFE: try deeper invocations!"); @@ -170,8 +131,6 @@ public void run() { if ((target instanceof StackOverflowError) || (target instanceof OutOfMemoryError)) continue; // OK. - if (target instanceof ThreadDeath) - throw (ThreadDeath) target; thrown = target; break; } @@ -199,7 +158,7 @@ private void invokeRecurse(int depth) throws Exception { // // Optimization trick: allocate once, use everywhere. // - method = stack018.class.getMethod("recurse"); + method = Stack018.class.getMethod("recurse"); params = new Object[]{}; } this.depth = depth; // actual parameter @@ -209,10 +168,11 @@ private void invokeRecurse(int depth) throws Exception { private int depth = 0; // actual parameter for recurse() public void recurse() throws Exception { - if (depth > 0) + if (depth > 0) { // // Self-invoke via reflection: // invokeRecurse(depth - 1); + } } } diff --git a/test/hotspot/jtreg/vmTestbase/nsk/stress/stack/stack019.java b/test/hotspot/jtreg/runtime/stack/Stack019.java similarity index 65% rename from test/hotspot/jtreg/vmTestbase/nsk/stress/stack/stack019.java rename to test/hotspot/jtreg/runtime/stack/Stack019.java index c6c5efbb36f..7a20ae3e6a2 100644 --- a/test/hotspot/jtreg/vmTestbase/nsk/stress/stack/stack019.java +++ b/test/hotspot/jtreg/runtime/stack/Stack019.java @@ -43,45 +43,22 @@ * * @requires (vm.opt.DeoptimizeALot != true & vm.compMode != "Xcomp" & vm.pageSize == 4096) * @requires os.family != "windows" - * @library /vmTestbase - * @build nsk.share.Terminator - * @run main/othervm/timeout=900 -Xss200K nsk.stress.stack.stack019 -eager + * @run main/othervm/timeout=900 -Xss200K Stack019 */ -package nsk.stress.stack; - - -import nsk.share.Terminator; - -import java.io.PrintStream; - -public class stack019 { +public class Stack019 { private final static int CYCLES = 50; private final static int PROBES = 50; public static void main(String[] args) { - int exitCode = run(args, System.out); - System.exit(exitCode + 95); - } - - public static int run(String args[], PrintStream out) { - boolean verbose = false, eager = false; - for (int i = 0; i < args.length; i++) - if (args[i].toLowerCase().equals("-verbose")) - verbose = true; - else if (args[i].toLowerCase().equals("-eager")) - eager = true; - if (!eager) - Terminator.appoint(Terminator.parseAppointment(args)); // // Measure recursive depth before stack overflow: // try { recurse(0); - } catch (StackOverflowError soe) { - } catch (OutOfMemoryError oome) { + } catch (StackOverflowError | OutOfMemoryError err) { } - out.println("Maximal recursion depth: " + maxDepth); + System.out.println("Maximal recursion depth: " + maxDepth); depthToTry = maxDepth; // @@ -89,23 +66,15 @@ else if (args[i].toLowerCase().equals("-eager")) // for (int i = 0; i < CYCLES; i++) { try { - out.println("Iteration: " + i + "/" + CYCLES); + System.out.println("Iteration: " + i + "/" + CYCLES); trickyRecurse(0); - out.println("# TEST_BUG: stack overflow was expected!"); - return 2; - - } catch (StackOverflowError error) { - } catch (OutOfMemoryError oome) { - // It's OK: stack overflow was expected. - + throw new RuntimeException("# TEST_BUG: stack overflow was expected!"); + } catch (StackOverflowError | OutOfMemoryError error) { + // It's OK } catch (Throwable throwable) { - if (throwable instanceof ThreadDeath) - throw (ThreadDeath) throwable; - throwable.printStackTrace(out); - return 2; + throw new RuntimeException(throwable); } } - return 0; } private static int maxDepth; @@ -120,17 +89,14 @@ private static void trickyRecurse(int depth) { try { maxDepth = depth; trickyRecurse(depth + 1); - } catch (Error error) { - if (!(error instanceof StackOverflowError) && - !(error instanceof OutOfMemoryError)) - throw error; - + } catch (StackOverflowError | OutOfMemoryError error){ // // Stack problem caught: provoke it again, // if current stack is enough deep: // - if (depth < depthToTry - PROBES) + if (depth < depthToTry - PROBES) { throw error; + } recurse(depth + 1); } } diff --git a/test/hotspot/jtreg/runtime/stringtable/StringTableVerifyTest.java b/test/hotspot/jtreg/runtime/stringtable/StringTableVerifyTest.java index 6f6b0a6ef73..f0513de13a4 100644 --- a/test/hotspot/jtreg/runtime/stringtable/StringTableVerifyTest.java +++ b/test/hotspot/jtreg/runtime/stringtable/StringTableVerifyTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2023, Oracle and/or its affiliates. All rights reserved. * 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,7 +36,7 @@ public class StringTableVerifyTest { public static void main(String[] args) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-XX:+UnlockDiagnosticVMOptions", "-XX:+VerifyStringTableAtExit", "-version"); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:+UnlockDiagnosticVMOptions", "-XX:+VerifyStringTableAtExit", "-version"); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldHaveExitValue(0); } diff --git a/test/hotspot/jtreg/runtime/symboltable/ShortLivedSymbolCleanup.java b/test/hotspot/jtreg/runtime/symboltable/ShortLivedSymbolCleanup.java index 6e5db46bd5c..ee7fa8f40d7 100644 --- a/test/hotspot/jtreg/runtime/symboltable/ShortLivedSymbolCleanup.java +++ b/test/hotspot/jtreg/runtime/symboltable/ShortLivedSymbolCleanup.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -89,13 +89,13 @@ static void analyzeOutputOn(int size, ProcessBuilder pb) throws Exception { } public static void main(String[] args) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-Xlog:symboltable=trace", - "-version"); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-Xlog:symboltable=trace", + "-version"); int size = getSymbolTableSize(pb); - pb = ProcessTools.createJavaProcessBuilder("-XX:+PrintSymbolTableSizeHistogram", - LotsOfTempSymbols.class.getName(), - Integer.toString(size)); + pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:+PrintSymbolTableSizeHistogram", + LotsOfTempSymbols.class.getName(), + Integer.toString(size)); analyzeOutputOn(size, pb); } diff --git a/test/hotspot/jtreg/runtime/verifier/OverriderMsg.java b/test/hotspot/jtreg/runtime/verifier/OverriderMsg.java index 38a8595d25d..5b24caacd3e 100644 --- a/test/hotspot/jtreg/runtime/verifier/OverriderMsg.java +++ b/test/hotspot/jtreg/runtime/verifier/OverriderMsg.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2023, Oracle and/or its affiliates. All rights reserved. * 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,7 +125,7 @@ public static void dump_Overrider () throws Exception { public static void main(String... args) throws Exception { dump_HasFinal(); dump_Overrider(); - ProcessBuilder pb = ProcessTools.createTestJvm("-cp", ".", "Overrider"); + ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder("-cp", ".", "Overrider"); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldContain( "java.lang.IncompatibleClassChangeError: class Overrider overrides final method HasFinal.m(Ljava/lang/String;)V"); diff --git a/test/hotspot/jtreg/runtime/verifier/TestANewArray.java b/test/hotspot/jtreg/runtime/verifier/TestANewArray.java index 99333da56dd..011749133da 100644 --- a/test/hotspot/jtreg/runtime/verifier/TestANewArray.java +++ b/test/hotspot/jtreg/runtime/verifier/TestANewArray.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -69,7 +69,7 @@ public static void main(String... args) throws Exception { byte[] classFile_254 = dumpClassFile(cfv, test_Dimension_254, array_Dimension_254); writeClassFileFromByteArray(classFile_254); System.err.println("Running with cfv: " + cfv + ", test_Dimension_254"); - ProcessBuilder pb = ProcessTools.createTestJvm("-verify", "-cp", ".", classCName); + ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder("-verify", "-cp", ".", classCName); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldNotContain("java.lang.VerifyError"); output.shouldHaveExitValue(0); @@ -78,7 +78,7 @@ public static void main(String... args) throws Exception { byte[] classFile_255 = dumpClassFile(cfv, test_Dimension_255, array_Dimension_255); writeClassFileFromByteArray(classFile_255); System.err.println("Running with cfv: " + cfv + ", test_Dimension_255"); - pb = ProcessTools.createTestJvm("-verify", "-cp", ".", classCName); + pb = ProcessTools.createTestJavaProcessBuilder("-verify", "-cp", ".", classCName); output = new OutputAnalyzer(pb.start()); // If anewarray has an operand with 255 array dimensions then VerifyError should // be thrown because the resulting array would have 256 dimensions. @@ -95,7 +95,7 @@ public static void main(String... args) throws Exception { byte[] classFile_264 = dumpClassFile(cfv, test_Dimension_264, array_Dimension_264); writeClassFileFromByteArray(classFile_264); System.err.println("Running with cfv: " + cfv + ", test_Dimension_264"); - pb = ProcessTools.createTestJvm("-verify", "-cp", ".", classCName); + pb = ProcessTools.createTestJavaProcessBuilder("-verify", "-cp", ".", classCName); output = new OutputAnalyzer(pb.start()); output.shouldContain("java.lang.ClassFormatError"); output.shouldHaveExitValue(1); diff --git a/test/hotspot/jtreg/runtime/verifier/TestMultiANewArray.java b/test/hotspot/jtreg/runtime/verifier/TestMultiANewArray.java index 07f2f33110d..6f04278c4cd 100644 --- a/test/hotspot/jtreg/runtime/verifier/TestMultiANewArray.java +++ b/test/hotspot/jtreg/runtime/verifier/TestMultiANewArray.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2023, Oracle and/or its affiliates. All rights reserved. * 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,7 +48,7 @@ public static void main(String... args) throws Exception { int cfv = Integer.parseInt(args[0]); writeClassFile(cfv); System.err.println("Running with cfv: " + cfv); - ProcessBuilder pb = ProcessTools.createTestJvm("-cp", ".", "ClassFile"); + ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder("-cp", ".", "ClassFile"); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldContain("VerifyError"); output.shouldHaveExitValue(1); diff --git a/test/hotspot/jtreg/runtime/verifier/TraceClassRes.java b/test/hotspot/jtreg/runtime/verifier/TraceClassRes.java index c4e420a1613..ddb5e68e1d3 100644 --- a/test/hotspot/jtreg/runtime/verifier/TraceClassRes.java +++ b/test/hotspot/jtreg/runtime/verifier/TraceClassRes.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2023, Oracle and/or its affiliates. All rights reserved. * 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,7 +38,7 @@ public class TraceClassRes { public static void main(String[] args) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-Xlog:class+resolve=debug", "-verify", "-Xshare:off", "-version"); OutputAnalyzer output = new OutputAnalyzer(pb.start()); diff --git a/test/hotspot/jtreg/runtime/whitebox/TestWBDeflateIdleMonitors.java b/test/hotspot/jtreg/runtime/whitebox/TestWBDeflateIdleMonitors.java index e5e22e58239..e88bc025e8c 100644 --- a/test/hotspot/jtreg/runtime/whitebox/TestWBDeflateIdleMonitors.java +++ b/test/hotspot/jtreg/runtime/whitebox/TestWBDeflateIdleMonitors.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2020, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -44,7 +44,7 @@ public class TestWBDeflateIdleMonitors { static final int N_TRIES = 5; // number of times to try deflation public static void main(String args[]) throws Exception { - ProcessBuilder pb = ProcessTools.createTestJvm( + ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder( "-Xbootclasspath/a:.", "-XX:+UnlockDiagnosticVMOptions", "-XX:+WhiteBoxAPI", diff --git a/test/hotspot/jtreg/serviceability/attach/AttachSetGetFlag.java b/test/hotspot/jtreg/serviceability/attach/AttachSetGetFlag.java index 939cc872a11..e38cc940d37 100644 --- a/test/hotspot/jtreg/serviceability/attach/AttachSetGetFlag.java +++ b/test/hotspot/jtreg/serviceability/attach/AttachSetGetFlag.java @@ -67,7 +67,7 @@ public static void main(String... args) throws Exception { } public static ProcessBuilder runTarget(String flagName, String flagValue) throws Exception { - return ProcessTools.createJavaProcessBuilder( + return ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:+UnlockExperimentalVMOptions", "-XX:" + flagName + "=" + flagValue, "AttachSetGetFlag$Target"); diff --git a/test/hotspot/jtreg/serviceability/attach/AttachWithStalePidFile.java b/test/hotspot/jtreg/serviceability/attach/AttachWithStalePidFile.java index f5905396782..aceaa82d668 100644 --- a/test/hotspot/jtreg/serviceability/attach/AttachWithStalePidFile.java +++ b/test/hotspot/jtreg/serviceability/attach/AttachWithStalePidFile.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2023, Oracle and/or its affiliates. All rights reserved. * 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,7 +59,7 @@ public static void main(String... args) throws Exception { } public static boolean runTest() throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:+UnlockDiagnosticVMOptions", "-XX:+PauseAtStartup", "AttachWithStalePidFileTarget"); Process target = pb.start(); Path pidFile = null; diff --git a/test/hotspot/jtreg/serviceability/attach/ShMemLongName.java b/test/hotspot/jtreg/serviceability/attach/ShMemLongName.java index bf90dd9a08c..3618a4cfa09 100644 --- a/test/hotspot/jtreg/serviceability/attach/ShMemLongName.java +++ b/test/hotspot/jtreg/serviceability/attach/ShMemLongName.java @@ -94,7 +94,7 @@ private static void log(String s) { // creates target process builder for the specified shmem transport name private static ProcessBuilder getTarget(String shmemName) throws IOException { log("starting target with shmem name: '" + shmemName + "'..."); - return ProcessTools.createJavaProcessBuilder( + return ProcessTools.createLimitedTestJavaProcessBuilder( "-Xrunjdwp:transport=" + transport + ",server=y,suspend=n,address=" + shmemName, "ShMemLongName$Target"); } diff --git a/test/hotspot/jtreg/serviceability/dcmd/gc/RunFinalizationTest.java b/test/hotspot/jtreg/serviceability/dcmd/gc/RunFinalizationTest.java index bf8605ee320..da47616d6e4 100644 --- a/test/hotspot/jtreg/serviceability/dcmd/gc/RunFinalizationTest.java +++ b/test/hotspot/jtreg/serviceability/dcmd/gc/RunFinalizationTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2023, Oracle and/or its affiliates. All rights reserved. * 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 static void main(String ... args) throws Exception { javaArgs.add("-cp"); javaArgs.add(System.getProperty("test.class.path")); javaArgs.add(TEST_APP_NAME); - ProcessBuilder testAppPb = ProcessTools.createJavaProcessBuilder(javaArgs); + ProcessBuilder testAppPb = ProcessTools.createLimitedTestJavaProcessBuilder(javaArgs); final AtomicBoolean failed = new AtomicBoolean(); final AtomicBoolean passed = new AtomicBoolean(); diff --git a/test/hotspot/jtreg/serviceability/dtrace/DTraceOptionsTest.java b/test/hotspot/jtreg/serviceability/dtrace/DTraceOptionsTest.java index 8822a9ed378..9fc8e476e6b 100644 --- a/test/hotspot/jtreg/serviceability/dtrace/DTraceOptionsTest.java +++ b/test/hotspot/jtreg/serviceability/dtrace/DTraceOptionsTest.java @@ -63,7 +63,7 @@ public static void main(String[] args) throws Throwable { }; for (String opt : options) { - var pb = ProcessTools.createJavaProcessBuilder("-XX:+" + opt, "-version"); + var pb = ProcessTools.createLimitedTestJavaProcessBuilder("-XX:+" + opt, "-version"); var oa = new OutputAnalyzer(pb.start()); if (dtraceEnabled) { oa.shouldHaveExitValue(0); diff --git a/test/hotspot/jtreg/serviceability/jdwp/AllModulesCommandTest.java b/test/hotspot/jtreg/serviceability/jdwp/AllModulesCommandTest.java index 3c799f6e54d..28fdeec3219 100644 --- a/test/hotspot/jtreg/serviceability/jdwp/AllModulesCommandTest.java +++ b/test/hotspot/jtreg/serviceability/jdwp/AllModulesCommandTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -72,12 +72,6 @@ public void onDebuggeeSendingCompleted() { jdwpLatch.countDown(); } - @Override - public void onDebuggeeError(String message) { - System.err.println("Debuggee error: '" + message + "'"); - System.exit(1); - } - private void doJdwp() throws Exception { try { // Establish JDWP socket connection diff --git a/test/hotspot/jtreg/serviceability/jdwp/DebuggeeLauncher.java b/test/hotspot/jtreg/serviceability/jdwp/DebuggeeLauncher.java index 5c3d01ec2dc..f7467affdf8 100644 --- a/test/hotspot/jtreg/serviceability/jdwp/DebuggeeLauncher.java +++ b/test/hotspot/jtreg/serviceability/jdwp/DebuggeeLauncher.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -22,9 +22,9 @@ */ import java.util.StringTokenizer; -import jdk.test.lib.JDKToolFinder; import jdk.test.lib.JDWP; import static jdk.test.lib.Asserts.assertFalse; +import jdk.test.lib.process.ProcessTools; /** * Launches the debuggee with the necessary JDWP options and handles the output @@ -45,21 +45,14 @@ public interface Listener { */ void onDebuggeeSendingCompleted(); - /** - * Callback to handle any debuggee error - * - * @param line line from the debuggee's stderr - */ - void onDebuggeeError(String line); } private int jdwpPort = -1; - private static final String CLS_DIR = System.getProperty("test.classes", "").trim(); private static final String DEBUGGEE = "AllModulesCommandTestDebuggee"; + private static final String JDWP_OPT = "-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=0"; + private Process p; private final Listener listener; - private StreamHandler inputHandler; - private StreamHandler errorHandler; /** * @param listener the listener we report the debuggee events to @@ -70,36 +63,20 @@ public DebuggeeLauncher(Listener listener) { /** * Starts the debuggee with the necessary JDWP options and handles the - * debuggee's stdout and stderr outputs + * debuggee's stdout output. stderr might contain jvm output, which is just printed to the log. * * @throws Throwable */ public void launchDebuggee() throws Throwable { - ProcessBuilder pb = new ProcessBuilder(getCommand()); + ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder(JDWP_OPT, DEBUGGEE); p = pb.start(); - inputHandler = new StreamHandler(p.getInputStream(), this); - errorHandler = new StreamHandler(p.getErrorStream(), this); + StreamHandler inputHandler = new StreamHandler(p.getInputStream(), this); + StreamHandler errorHandler = new StreamHandler(p.getErrorStream(), l -> System.out.println("[stderr]: " + l)); inputHandler.start(); errorHandler.start(); } - /** - * Command to start the debuggee with the JDWP options and using the JDK - * under test - * - * @return the command - */ - private String[] getCommand() { - return new String[]{ - JDKToolFinder.getTestJDKTool("java"), - getJdwpOptions(), - "-cp", - CLS_DIR, - DEBUGGEE - }; - } - /** * Terminates the debuggee */ @@ -109,15 +86,6 @@ public void terminateDebuggee() { } } - /** - * Debuggee JDWP options - * - * @return the JDWP options to start the debuggee with - */ - private static String getJdwpOptions() { - return "-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=0"; - } - /** * Gets JDWP port debuggee is listening on. * @@ -129,16 +97,8 @@ public int getJdwpPort() { } @Override - public void onStringRead(StreamHandler handler, String line) { - if (handler.equals(errorHandler)) { - terminateDebuggee(); - listener.onDebuggeeError(line); - } else { - processDebuggeeOutput(line); - } - } - - private void processDebuggeeOutput(String line) { + public void onStringRead(String line) { + System.out.println("[stdout]: " + line); if (jdwpPort == -1) { JDWP.ListenAddress addr = JDWP.parseListenAddress(line); if (addr != null) { diff --git a/test/hotspot/jtreg/serviceability/jdwp/StreamHandler.java b/test/hotspot/jtreg/serviceability/jdwp/StreamHandler.java index 257f66a66a9..2822a91a8ce 100644 --- a/test/hotspot/jtreg/serviceability/jdwp/StreamHandler.java +++ b/test/hotspot/jtreg/serviceability/jdwp/StreamHandler.java @@ -37,10 +37,9 @@ public class StreamHandler implements Runnable { public interface Listener { /** * Called when a line has been read from the process output stream - * @param handler this StreamHandler * @param s the line */ - void onStringRead(StreamHandler handler, String s); + void onStringRead(String s); } private final ExecutorService executor; @@ -71,7 +70,7 @@ public void run() { BufferedReader br = new BufferedReader(new InputStreamReader(is)); String line; while ((line = br.readLine()) != null) { - listener.onStringRead(this, line); + listener.onStringRead(line); } } catch (Exception x) { throw new RuntimeException(x); diff --git a/test/hotspot/jtreg/serviceability/jvmti/8036666/GetObjectLockCount.java b/test/hotspot/jtreg/serviceability/jvmti/8036666/GetObjectLockCount.java index 70b525f552e..e34da9013d5 100644 --- a/test/hotspot/jtreg/serviceability/jvmti/8036666/GetObjectLockCount.java +++ b/test/hotspot/jtreg/serviceability/jvmti/8036666/GetObjectLockCount.java @@ -1,5 +1,6 @@ /* * Copyright (c) 2014 SAP SE. All rights reserved. + * Copyright (c) 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -56,12 +57,14 @@ import com.sun.jdi.request.ClassPrepareRequest; import com.sun.jdi.request.EventRequestManager; +import jdk.test.lib.Utils; /* * @test GetObjectLockCount.java * @bug 8036666 * @summary verify jvm returns correct lock recursion count * @requires vm.jvmti + * @library /test/lib * @run compile -g RecursiveObjectLock.java * @run main/othervm GetObjectLockCount * @author axel.siebenborn@sap.com @@ -71,8 +74,6 @@ public class GetObjectLockCount { public static final String CLASS_NAME = "RecursiveObjectLock"; public static final String METHOD_NAME = "breakpoint1"; - public static final String ARGUMENTS = ""; - /** * Find a com.sun.jdi.CommandLineLaunch connector @@ -119,7 +120,7 @@ static Map connectorArguments(LaunchingConnector con if (optionsArg == null) { throw new Error("Bad launching connector"); } - optionsArg.setValue(ARGUMENTS); + optionsArg.setValue(String.join(" ", Utils.getTestJavaOpts())); return arguments; } diff --git a/test/hotspot/jtreg/serviceability/jvmti/CanGenerateAllClassHook/CanGenerateAllClassHook.java b/test/hotspot/jtreg/serviceability/jvmti/CanGenerateAllClassHook/CanGenerateAllClassHook.java index 759967c5c96..b3c8ed66a0b 100644 --- a/test/hotspot/jtreg/serviceability/jvmti/CanGenerateAllClassHook/CanGenerateAllClassHook.java +++ b/test/hotspot/jtreg/serviceability/jvmti/CanGenerateAllClassHook/CanGenerateAllClassHook.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2023, Oracle and/or its affiliates. All rights reserved. * 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,7 +125,7 @@ private static void log(String msg) { } private static OutputAnalyzer execJava(String... args) throws IOException { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(args); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(args); OutputAnalyzer output = new OutputAnalyzer(pb.start()); diff --git a/test/hotspot/jtreg/serviceability/jvmti/GetObjectSizeClass.java b/test/hotspot/jtreg/serviceability/jvmti/GetObjectSizeClass.java index 126f3333cae..b5ab4eeb997 100644 --- a/test/hotspot/jtreg/serviceability/jvmti/GetObjectSizeClass.java +++ b/test/hotspot/jtreg/serviceability/jvmti/GetObjectSizeClass.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -51,7 +51,7 @@ public static void main(String[] args) throws Exception { pb.command(new String[] { JDKToolFinder.getJDKTool("jar"), "cmf", "MANIFEST.MF", "agent.jar", "GetObjectSizeClassAgent.class"}); pb.start().waitFor(); - ProcessBuilder pt = ProcessTools.createTestJvm("-javaagent:agent.jar", "GetObjectSizeClassAgent"); + ProcessBuilder pt = ProcessTools.createTestJavaProcessBuilder("-javaagent:agent.jar", "GetObjectSizeClassAgent"); OutputAnalyzer output = new OutputAnalyzer(pt.start()); output.shouldHaveExitValue(0); diff --git a/test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/RedefineLeak.java b/test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/RedefineLeak.java index 3e2da128b53..733850d0e24 100644 --- a/test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/RedefineLeak.java +++ b/test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/RedefineLeak.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -104,7 +104,7 @@ public static void main(String argv[]) throws Exception { } if (argv.length == 1 && argv[0].equals("runtest")) { // run outside of jtreg to not OOM on jtreg classes that are loaded after metaspace is full - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-XX:MetaspaceSize=12m", "-XX:MaxMetaspaceSize=12m", "-javaagent:redefineagent.jar", diff --git a/test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/RedefinePreviousVersions.java b/test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/RedefinePreviousVersions.java index d6dc502656b..79ab843bb33 100644 --- a/test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/RedefinePreviousVersions.java +++ b/test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/RedefinePreviousVersions.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -82,7 +82,7 @@ public static void main(String[] args) throws Exception { if (args.length > 0) { // java -javaagent:redefineagent.jar -Xlog:stuff RedefinePreviousVersions - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( "-javaagent:redefineagent.jar", + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-javaagent:redefineagent.jar", "-Xlog:redefine+class+iklass+add=trace,redefine+class+iklass+purge=trace", "RedefinePreviousVersions"); new OutputAnalyzer(pb.start()) diff --git a/test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/RedefineSharedClassJFR.java b/test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/RedefineSharedClassJFR.java index 6ee54be7831..bf6216ae85a 100644 --- a/test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/RedefineSharedClassJFR.java +++ b/test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/RedefineSharedClassJFR.java @@ -75,7 +75,7 @@ public static void main(String[] args) throws Exception { List offCommand = new ArrayList<>(); offCommand.add("-Xshare:off"); offCommand.addAll(baseCommand); - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(offCommand); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(offCommand); new OutputAnalyzer(pb.start()) // We can't expect any of the transformed classes to be in use // so the only thing we can verify is that no scratch classes @@ -89,7 +89,7 @@ public static void main(String[] args) throws Exception { List onCommand = new ArrayList<>(); onCommand.add("-Xshare:on"); onCommand.addAll(baseCommand); - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(onCommand); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(onCommand); new OutputAnalyzer(pb.start()) .shouldContain(SHOULD_CLEAN_FALSE) .shouldNotContain(SHOULD_CLEAN_TRUE) diff --git a/test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/RetransformClassesZeroLength.java b/test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/RetransformClassesZeroLength.java index 13ac65a2eb7..7f7ec792941 100644 --- a/test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/RetransformClassesZeroLength.java +++ b/test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/RetransformClassesZeroLength.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -56,7 +56,7 @@ public class RetransformClassesZeroLength { public static void main(String args[]) throws Throwable { String agentJar = buildAgent(); ProcessTools.executeProcess( - ProcessTools.createJavaProcessBuilder( + ProcessTools.createLimitedTestJavaProcessBuilder( "-javaagent:" + agentJar, "-version") ).shouldHaveExitValue(0); diff --git a/test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/TransformerDeadlockTest.java b/test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/TransformerDeadlockTest.java index f51ff4c58a5..99c7a49263c 100644 --- a/test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/TransformerDeadlockTest.java +++ b/test/hotspot/jtreg/serviceability/jvmti/RedefineClasses/TransformerDeadlockTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2020, 2023, Oracle and/or its affiliates. All rights reserved. * 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,7 +57,7 @@ public class TransformerDeadlockTest { public static void main(String args[]) throws Throwable { String agentJar = buildAgent(); ProcessTools.executeProcess( - ProcessTools.createJavaProcessBuilder( + ProcessTools.createLimitedTestJavaProcessBuilder( "-javaagent:" + agentJar, TransformerDeadlockTest.Agent.class.getName()) ).shouldHaveExitValue(0); diff --git a/test/hotspot/jtreg/serviceability/logging/TestBasicLogOutput.java b/test/hotspot/jtreg/serviceability/logging/TestBasicLogOutput.java index 07aafabf995..895e5504feb 100644 --- a/test/hotspot/jtreg/serviceability/logging/TestBasicLogOutput.java +++ b/test/hotspot/jtreg/serviceability/logging/TestBasicLogOutput.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2023, Oracle and/or its affiliates. All rights reserved. * 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,7 +36,7 @@ public class TestBasicLogOutput { public static void main(String[] args) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-Xlog:all=trace", "-version"); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-Xlog:all=trace", "-version"); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldMatch("\\[logging *\\]"); // expected tag(s) output.shouldContain("Log configuration fully initialized."); // expected message diff --git a/test/hotspot/jtreg/serviceability/logging/TestDefaultLogOutput.java b/test/hotspot/jtreg/serviceability/logging/TestDefaultLogOutput.java index 3a7fde88894..a1f70fdeb13 100644 --- a/test/hotspot/jtreg/serviceability/logging/TestDefaultLogOutput.java +++ b/test/hotspot/jtreg/serviceability/logging/TestDefaultLogOutput.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2023, Oracle and/or its affiliates. All rights reserved. * 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,7 +36,7 @@ public class TestDefaultLogOutput { public static void main(String[] args) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-Xlog:badTag"); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-Xlog:badTag"); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.stdoutShouldMatch("\\[error *\\]\\[logging *\\]"); output.shouldHaveExitValue(1); diff --git a/test/hotspot/jtreg/serviceability/logging/TestFullNames.java b/test/hotspot/jtreg/serviceability/logging/TestFullNames.java index dceb2e32f63..0a3bc855d8f 100644 --- a/test/hotspot/jtreg/serviceability/logging/TestFullNames.java +++ b/test/hotspot/jtreg/serviceability/logging/TestFullNames.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 2023, Oracle and/or its affiliates. All rights reserved. * 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,9 +63,9 @@ public static void main(String[] args) throws Exception { for (String logOutput : validOutputs) { Asserts.assertFalse(file.exists()); // Run with logging=trace on stdout so that we can verify the log configuration afterwards. - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-Xlog:logging=trace", - "-Xlog:all=trace:" + logOutput, - "-version"); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-Xlog:logging=trace", + "-Xlog:all=trace:" + logOutput, + "-version"); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldHaveExitValue(0); Asserts.assertTrue(file.exists()); diff --git a/test/hotspot/jtreg/serviceability/logging/TestLogRotation.java b/test/hotspot/jtreg/serviceability/logging/TestLogRotation.java index 608c656c580..585e8bda47d 100644 --- a/test/hotspot/jtreg/serviceability/logging/TestLogRotation.java +++ b/test/hotspot/jtreg/serviceability/logging/TestLogRotation.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -71,7 +71,7 @@ public static void cleanLogs() { } public static void runTest(int numberOfFiles) throws Exception { - ProcessBuilder pb = ProcessTools.createTestJvm( + ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder( "-cp", System.getProperty("java.class.path"), "-Xlog:gc=debug:" + logFileName + "::filesize=" + logFileSizeK + "k" diff --git a/test/hotspot/jtreg/serviceability/logging/TestMultipleXlogArgs.java b/test/hotspot/jtreg/serviceability/logging/TestMultipleXlogArgs.java index 8570eec7360..13560eeb68a 100644 --- a/test/hotspot/jtreg/serviceability/logging/TestMultipleXlogArgs.java +++ b/test/hotspot/jtreg/serviceability/logging/TestMultipleXlogArgs.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2023, Oracle and/or its affiliates. All rights reserved. * 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,13 +36,13 @@ public class TestMultipleXlogArgs { public static void main(String[] args) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-Xlog:logging=debug", - "-Xlog:logging=trace", - "-Xlog:defaultmethods=trace", - "-Xlog:defaultmethods=warning", - "-Xlog:safepoint=info", - "-Xlog:safepoint=info", - "-version"); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-Xlog:logging=debug", + "-Xlog:logging=trace", + "-Xlog:defaultmethods=trace", + "-Xlog:defaultmethods=warning", + "-Xlog:safepoint=info", + "-Xlog:safepoint=info", + "-version"); OutputAnalyzer output = new OutputAnalyzer(pb.start()); // -Xlog:logging=trace means that the log configuration will be printed. String stdoutConfigLine = "\\[logging *\\] #0: stdout .*"; diff --git a/test/hotspot/jtreg/serviceability/logging/TestQuotedLogOutputs.java b/test/hotspot/jtreg/serviceability/logging/TestQuotedLogOutputs.java index dff973f61da..dea656130ab 100644 --- a/test/hotspot/jtreg/serviceability/logging/TestQuotedLogOutputs.java +++ b/test/hotspot/jtreg/serviceability/logging/TestQuotedLogOutputs.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -73,9 +73,9 @@ public static void main(String[] args) throws Exception { }; for (String logOutput : validOutputs) { // Run with logging=trace on stdout so that we can verify the log configuration afterwards. - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-Xlog:logging=trace", - "-Xlog:all=trace:" + logOutput, - "-version"); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-Xlog:logging=trace", + "-Xlog:all=trace:" + logOutput, + "-version"); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldHaveExitValue(0); Asserts.assertTrue(file.exists()); @@ -98,9 +98,9 @@ public static void main(String[] args) throws Exception { "A" + quote + quote + "B" }; for (String logOutput : invalidOutputs) { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-Xlog:logging=trace", - "-Xlog:all=trace:" + logOutput, - "-version"); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-Xlog:logging=trace", + "-Xlog:all=trace:" + logOutput, + "-version"); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldHaveExitValue(1); // Ensure error message was logged diff --git a/test/hotspot/jtreg/serviceability/sa/ClhsdbCDSCore.java b/test/hotspot/jtreg/serviceability/sa/ClhsdbCDSCore.java index 3655a8c8847..53370fc09d6 100644 --- a/test/hotspot/jtreg/serviceability/sa/ClhsdbCDSCore.java +++ b/test/hotspot/jtreg/serviceability/sa/ClhsdbCDSCore.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -90,7 +90,7 @@ public static void main(String[] args) throws Exception { try { List options = new ArrayList<>(); options.addAll(Arrays.asList(jArgs)); - ProcessBuilder pb = ProcessTools.createTestJvm(options); + ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder(options); // Add "ulimit -c unlimited" if we can since we are generating a core file. pb = CoreUtils.addCoreUlimitCommand(pb); crashOutput = ProcessTools.executeProcess(pb); diff --git a/test/hotspot/jtreg/serviceability/sa/TestClassDump.java b/test/hotspot/jtreg/serviceability/sa/TestClassDump.java index 18f3c47e5d1..04d225287b8 100644 --- a/test/hotspot/jtreg/serviceability/sa/TestClassDump.java +++ b/test/hotspot/jtreg/serviceability/sa/TestClassDump.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -49,7 +49,7 @@ private static void dumpClass(long lingeredAppPid) ProcessBuilder pb; OutputAnalyzer output; - pb = ProcessTools.createJavaProcessBuilder( + pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-Dsun.jvm.hotspot.tools.jcore.outputDir=jtreg_classes", "-m", "jdk.hotspot.agent/sun.jvm.hotspot.tools.jcore.ClassDump", String.valueOf(lingeredAppPid)); SATestUtils.addPrivilegesIfNeeded(pb); @@ -68,7 +68,7 @@ private static void dumpClass(long lingeredAppPid) throw new RuntimeException("jtreg_classes/sun/net/util/URLUtil.class not found"); } - pb = ProcessTools.createJavaProcessBuilder( + pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-Dsun.jvm.hotspot.tools.jcore.outputDir=jtreg_classes2", "-Dsun.jvm.hotspot.tools.jcore.PackageNameFilter.pkgList=jdk,sun", "-m", "jdk.hotspot.agent/sun.jvm.hotspot.tools.jcore.ClassDump", String.valueOf(lingeredAppPid)); diff --git a/test/hotspot/jtreg/serviceability/sa/TestCpoolForInvokeDynamic.java b/test/hotspot/jtreg/serviceability/sa/TestCpoolForInvokeDynamic.java index 4753c924f1e..ca5c99d00b8 100644 --- a/test/hotspot/jtreg/serviceability/sa/TestCpoolForInvokeDynamic.java +++ b/test/hotspot/jtreg/serviceability/sa/TestCpoolForInvokeDynamic.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2023, Oracle and/or its affiliates. All rights reserved. * 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,7 +91,7 @@ private static void createAnotherToAttach( String[] instanceKlassNames, long lingeredAppPid) throws Exception { // Start a new process to attach to the lingered app - ProcessBuilder processBuilder = ProcessTools.createJavaProcessBuilder( + ProcessBuilder processBuilder = ProcessTools.createLimitedTestJavaProcessBuilder( "--add-modules=jdk.hotspot.agent", "--add-exports=jdk.hotspot.agent/sun.jvm.hotspot=ALL-UNNAMED", "--add-exports=jdk.hotspot.agent/sun.jvm.hotspot.utilities=ALL-UNNAMED", diff --git a/test/hotspot/jtreg/serviceability/sa/TestDefaultMethods.java b/test/hotspot/jtreg/serviceability/sa/TestDefaultMethods.java index f674008e2f8..094c7525048 100644 --- a/test/hotspot/jtreg/serviceability/sa/TestDefaultMethods.java +++ b/test/hotspot/jtreg/serviceability/sa/TestDefaultMethods.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -98,7 +98,7 @@ private static void createAnotherToAttach( String[] instanceKlassNames, long lingeredAppPid) throws Exception { // Start a new process to attach to the lingered app - ProcessBuilder processBuilder = ProcessTools.createJavaProcessBuilder( + ProcessBuilder processBuilder = ProcessTools.createLimitedTestJavaProcessBuilder( "--add-modules=jdk.hotspot.agent", "--add-exports=jdk.hotspot.agent/sun.jvm.hotspot=ALL-UNNAMED", "--add-exports=jdk.hotspot.agent/sun.jvm.hotspot.utilities=ALL-UNNAMED", diff --git a/test/hotspot/jtreg/serviceability/sa/TestG1HeapRegion.java b/test/hotspot/jtreg/serviceability/sa/TestG1HeapRegion.java index 70b9f066257..5c344b408dc 100644 --- a/test/hotspot/jtreg/serviceability/sa/TestG1HeapRegion.java +++ b/test/hotspot/jtreg/serviceability/sa/TestG1HeapRegion.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -72,7 +72,7 @@ private static void checkHeapRegion(String pid) throws Exception { private static void createAnotherToAttach(long lingeredAppPid) throws Exception { // Start a new process to attach to the lingered app - ProcessBuilder processBuilder = ProcessTools.createJavaProcessBuilder( + ProcessBuilder processBuilder = ProcessTools.createLimitedTestJavaProcessBuilder( "--add-modules=jdk.hotspot.agent", "--add-exports=jdk.hotspot.agent/sun.jvm.hotspot=ALL-UNNAMED", "--add-exports=jdk.hotspot.agent/sun.jvm.hotspot.gc.g1=ALL-UNNAMED", diff --git a/test/hotspot/jtreg/serviceability/sa/TestInstanceKlassSize.java b/test/hotspot/jtreg/serviceability/sa/TestInstanceKlassSize.java index a2190d48487..ebe55b75061 100644 --- a/test/hotspot/jtreg/serviceability/sa/TestInstanceKlassSize.java +++ b/test/hotspot/jtreg/serviceability/sa/TestInstanceKlassSize.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -82,7 +82,7 @@ private static void startMeWithArgs() throws Exception { } try { // Run this app with the LingeredApp PID to get SA output from the LingeredApp - ProcessBuilder processBuilder = ProcessTools.createJavaProcessBuilder( + ProcessBuilder processBuilder = ProcessTools.createLimitedTestJavaProcessBuilder( "--add-modules=jdk.hotspot.agent", "--add-exports=jdk.hotspot.agent/sun.jvm.hotspot=ALL-UNNAMED", "--add-exports=jdk.hotspot.agent/sun.jvm.hotspot.utilities=ALL-UNNAMED", diff --git a/test/hotspot/jtreg/serviceability/sa/TestInstanceKlassSizeForInterface.java b/test/hotspot/jtreg/serviceability/sa/TestInstanceKlassSizeForInterface.java index f2310dfe561..e0f7cbecd2f 100644 --- a/test/hotspot/jtreg/serviceability/sa/TestInstanceKlassSizeForInterface.java +++ b/test/hotspot/jtreg/serviceability/sa/TestInstanceKlassSizeForInterface.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -103,7 +103,7 @@ private static void createAnotherToAttach( String[] instanceKlassNames, int lingeredAppPid) throws Exception { // Start a new process to attach to the LingeredApp process to get SA info - ProcessBuilder processBuilder = ProcessTools.createJavaProcessBuilder( + ProcessBuilder processBuilder = ProcessTools.createLimitedTestJavaProcessBuilder( "--add-modules=jdk.hotspot.agent", "--add-exports=jdk.hotspot.agent/sun.jvm.hotspot=ALL-UNNAMED", "--add-exports=jdk.hotspot.agent/sun.jvm.hotspot.utilities=ALL-UNNAMED", diff --git a/test/hotspot/jtreg/serviceability/sa/TestJmapCore.java b/test/hotspot/jtreg/serviceability/sa/TestJmapCore.java index 34cac852c7b..434248a289f 100644 --- a/test/hotspot/jtreg/serviceability/sa/TestJmapCore.java +++ b/test/hotspot/jtreg/serviceability/sa/TestJmapCore.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -71,7 +71,7 @@ public static void main(String[] args) throws Throwable { } static void test(String type) throws Throwable { - ProcessBuilder pb = ProcessTools.createTestJvm("-XX:+CreateCoredumpOnCrash", + ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder("-XX:+CreateCoredumpOnCrash", "-Xmx512m", "-XX:MaxMetaspaceSize=64m", "-XX:+CrashOnOutOfMemoryError", // The test loads lots of small classes to exhaust Metaspace, skip method // dependency verification to improve performance in debug builds. diff --git a/test/hotspot/jtreg/serviceability/sa/TestObjectAlignment.java b/test/hotspot/jtreg/serviceability/sa/TestObjectAlignment.java index 236dee6c39d..84744c70cdf 100644 --- a/test/hotspot/jtreg/serviceability/sa/TestObjectAlignment.java +++ b/test/hotspot/jtreg/serviceability/sa/TestObjectAlignment.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -64,7 +64,7 @@ private static void checkAlignment(String pid, int expectedAlign) throws Excepti private static void createAnotherToAttach(long lingeredAppPid, int expectedAlign) throws Exception { // Start a new process to attach to the lingered app - ProcessBuilder processBuilder = ProcessTools.createJavaProcessBuilder( + ProcessBuilder processBuilder = ProcessTools.createLimitedTestJavaProcessBuilder( "--add-modules=jdk.hotspot.agent", "--add-exports=jdk.hotspot.agent/sun.jvm.hotspot=ALL-UNNAMED", "--add-exports=jdk.hotspot.agent/sun.jvm.hotspot.runtime=ALL-UNNAMED", diff --git a/test/hotspot/jtreg/serviceability/sa/TestObjectMonitorIterate.java b/test/hotspot/jtreg/serviceability/sa/TestObjectMonitorIterate.java index e2d79b1ce9d..15201a9c92b 100644 --- a/test/hotspot/jtreg/serviceability/sa/TestObjectMonitorIterate.java +++ b/test/hotspot/jtreg/serviceability/sa/TestObjectMonitorIterate.java @@ -73,7 +73,7 @@ private static void test(String pid) { private static void createAnotherToAttach(long lingeredAppPid) throws Exception { // Start a new process to attach to the lingered app - ProcessBuilder processBuilder = ProcessTools.createJavaProcessBuilder( + ProcessBuilder processBuilder = ProcessTools.createLimitedTestJavaProcessBuilder( "--add-modules=jdk.hotspot.agent", "--add-exports=jdk.hotspot.agent/sun.jvm.hotspot=ALL-UNNAMED", "--add-exports=jdk.hotspot.agent/sun.jvm.hotspot.oops=ALL-UNNAMED", diff --git a/test/hotspot/jtreg/serviceability/sa/TestRevPtrsForInvokeDynamic.java b/test/hotspot/jtreg/serviceability/sa/TestRevPtrsForInvokeDynamic.java index da7334503db..315c931d49e 100644 --- a/test/hotspot/jtreg/serviceability/sa/TestRevPtrsForInvokeDynamic.java +++ b/test/hotspot/jtreg/serviceability/sa/TestRevPtrsForInvokeDynamic.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2023, Oracle and/or its affiliates. All rights reserved. * 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,7 +66,7 @@ private static void computeReversePointers(String pid) throws Exception { private static void createAnotherToAttach(long lingeredAppPid) throws Exception { // Start a new process to attach to the lingered app - ProcessBuilder processBuilder = ProcessTools.createJavaProcessBuilder( + ProcessBuilder processBuilder = ProcessTools.createLimitedTestJavaProcessBuilder( "--add-modules=jdk.hotspot.agent", "--add-exports=jdk.hotspot.agent/sun.jvm.hotspot=ALL-UNNAMED", "--add-exports=jdk.hotspot.agent/sun.jvm.hotspot.utilities=ALL-UNNAMED", diff --git a/test/hotspot/jtreg/serviceability/sa/jmap-hprof/JMapHProfLargeHeapTest.java b/test/hotspot/jtreg/serviceability/sa/jmap-hprof/JMapHProfLargeHeapTest.java index 692fc0153e3..9d923f7b710 100644 --- a/test/hotspot/jtreg/serviceability/sa/jmap-hprof/JMapHProfLargeHeapTest.java +++ b/test/hotspot/jtreg/serviceability/sa/jmap-hprof/JMapHProfLargeHeapTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2023, Oracle and/or its affiliates. All rights reserved. * 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,11 +25,11 @@ import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; +import java.io.InputStreamReader; import java.io.IOException; import java.io.Reader; import java.nio.CharBuffer; import java.util.Arrays; -import java.util.Scanner; import jdk.test.lib.Asserts; import jdk.test.lib.JDKToolLauncher; @@ -77,20 +77,27 @@ public static void main(String[] args) throws Exception { private static void testHProfFileFormat(String vmArgs, long heapSize, String expectedFormat) throws Exception, IOException, InterruptedException, FileNotFoundException { - ProcessBuilder procBuilder = ProcessTools.createJavaProcessBuilder( + ProcessBuilder procBuilder = ProcessTools.createTestJavaProcessBuilder( "--add-exports=java.management/sun.management=ALL-UNNAMED", vmArgs, "JMapHProfLargeHeapProc", String.valueOf(heapSize)); procBuilder.redirectError(ProcessBuilder.Redirect.INHERIT); Process largeHeapProc = procBuilder.start(); - try (Scanner largeHeapScanner = new Scanner( - largeHeapProc.getInputStream());) { + try (BufferedReader r = new BufferedReader( + new InputStreamReader(largeHeapProc.getInputStream()))) { String pidstring = null; - if (!largeHeapScanner.hasNext()) { - throw new RuntimeException ("Test failed: could not open largeHeapScanner."); + while ((pidstring = r.readLine()) != null) { + // The output might contain different VM output, skip it while searching PID line. + if (pidstring.matches("PID\\[[0-9].*\\]")) { + System.out.println("Found: " + pidstring); + break; + } else { + System.out.println("Ignoring: " + pidstring); + } } - while ((pidstring = largeHeapScanner.findInLine("PID\\[[0-9].*\\]")) == null) { - Thread.sleep(500); + if (pidstring == null) { + throw new RuntimeException("Not able to find string matching PID."); } + int pid = Integer.parseInt(pidstring.substring(4, pidstring.length() - 1)); System.out.println("Extracted pid: " + pid); diff --git a/test/hotspot/jtreg/testlibrary/ctw/src/sun/hotspot/tools/ctw/CtwRunner.java b/test/hotspot/jtreg/testlibrary/ctw/src/sun/hotspot/tools/ctw/CtwRunner.java index 187b86f6f3a..4f6f0fedefb 100644 --- a/test/hotspot/jtreg/testlibrary/ctw/src/sun/hotspot/tools/ctw/CtwRunner.java +++ b/test/hotspot/jtreg/testlibrary/ctw/src/sun/hotspot/tools/ctw/CtwRunner.java @@ -174,7 +174,7 @@ private void startCtwforAllClasses() { while (!done) { String[] cmd = cmd(classStart, classStop); try { - ProcessBuilder pb = ProcessTools.createTestJvm(cmd); + ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder(cmd); String commandLine = pb.command() .stream() .collect(Collectors.joining(" ")); @@ -290,6 +290,7 @@ private String[] cmd(long classStart, long classStop) { "-XX:+StressGCM", "-XX:+StressIGVN", "-XX:+StressCCP", + "-XX:+StressIncrementalInlining", // StressSeed is uint "-XX:StressSeed=" + Math.abs(rng.nextLong()), // CTW entry point diff --git a/test/hotspot/jtreg/testlibrary/jittester/src/jdk/test/lib/jittester/jtreg/JitTesterDriver.java b/test/hotspot/jtreg/testlibrary/jittester/src/jdk/test/lib/jittester/jtreg/JitTesterDriver.java index e350d5cf121..1f824c5109f 100644 --- a/test/hotspot/jtreg/testlibrary/jittester/src/jdk/test/lib/jittester/jtreg/JitTesterDriver.java +++ b/test/hotspot/jtreg/testlibrary/jittester/src/jdk/test/lib/jittester/jtreg/JitTesterDriver.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2023, Oracle and/or its affiliates. All rights reserved. * 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 static void main(String[] args) { } OutputAnalyzer oa; try { - ProcessBuilder pb = ProcessTools.createTestJvm(args); + ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder(args); oa = new OutputAnalyzer(pb.start()); } catch (Exception e) { throw new Error("Unexpected exception on test jvm start :" + e, e); diff --git a/test/hotspot/jtreg/testlibrary_tests/ctw/CtwTest.java b/test/hotspot/jtreg/testlibrary_tests/ctw/CtwTest.java index ec22510bf8d..2aa2e2a207b 100644 --- a/test/hotspot/jtreg/testlibrary_tests/ctw/CtwTest.java +++ b/test/hotspot/jtreg/testlibrary_tests/ctw/CtwTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -103,7 +103,7 @@ protected void compile(String[] args) throws Exception { } } } - ProcessBuilder pb = ProcessTools.createTestJvm(cmd); + ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder(cmd); OutputAnalyzer output = new OutputAnalyzer(pb.start()); dump(output, "compile"); output.shouldHaveExitValue(0); diff --git a/test/hotspot/jtreg/testlibrary_tests/ir_framework/tests/TestDScenarios.java b/test/hotspot/jtreg/testlibrary_tests/ir_framework/tests/TestDScenarios.java index 10a49f9a3c7..e5476afc1f6 100644 --- a/test/hotspot/jtreg/testlibrary_tests/ir_framework/tests/TestDScenarios.java +++ b/test/hotspot/jtreg/testlibrary_tests/ir_framework/tests/TestDScenarios.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2021, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -73,7 +73,7 @@ public static void main(String[] args) throws Exception { } else { // Test invalid -DScenario flag. OutputAnalyzer oa; - ProcessBuilder process = ProcessTools.createJavaProcessBuilder( + ProcessBuilder process = ProcessTools.createLimitedTestJavaProcessBuilder( "-Dtest.jdk=" + Utils.TEST_JDK, "-DScenarios=a,1,b,10", "ir_framework.tests.TestDScenarios", " test3"); oa = ProcessTools.executeProcess(process); diff --git a/test/hotspot/jtreg/testlibrary_tests/ir_framework/tests/TestDTestAndExclude.java b/test/hotspot/jtreg/testlibrary_tests/ir_framework/tests/TestDTestAndExclude.java index b74012fd54a..22d52f692a3 100644 --- a/test/hotspot/jtreg/testlibrary_tests/ir_framework/tests/TestDTestAndExclude.java +++ b/test/hotspot/jtreg/testlibrary_tests/ir_framework/tests/TestDTestAndExclude.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2021, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -97,7 +97,7 @@ public static void main(String[] args) throws Exception { protected static void run(String dTest, String dExclude, String arg) throws Exception { System.out.println("Run -DTest=" + dTest + " -DExclude=" + dExclude + " arg=" + arg); OutputAnalyzer oa; - ProcessBuilder process = ProcessTools.createJavaProcessBuilder( + ProcessBuilder process = ProcessTools.createLimitedTestJavaProcessBuilder( "-Dtest.class.path=" + Utils.TEST_CLASS_PATH, "-Dtest.jdk=" + Utils.TEST_JDK, "-Dtest.vm.opts=-DTest=" + dTest + " -DExclude=" + dExclude, "ir_framework.tests.TestDTestAndExclude", arg); diff --git a/test/hotspot/jtreg/vmTestbase/gc/g1/unloading/UnloadingTest.java b/test/hotspot/jtreg/vmTestbase/gc/g1/unloading/UnloadingTest.java index 9f84a795090..8154916323c 100644 --- a/test/hotspot/jtreg/vmTestbase/gc/g1/unloading/UnloadingTest.java +++ b/test/hotspot/jtreg/vmTestbase/gc/g1/unloading/UnloadingTest.java @@ -149,8 +149,6 @@ private void check(Collection assertions) { } private static void checkGCCounters() { -// System.out.println("WhiteBox.getWhiteBox().g1GetTotalCollections() = \t" + WhiteBox.getWhiteBox().g1GetTotalCollections()); -// System.out.println("WhiteBox.getWhiteBox().g1GetTotalFullCollections() = \t" + WhiteBox.getWhiteBox().g1GetTotalFullCollections()); GarbageCollectorMXBean oldGenBean = null; for (GarbageCollectorMXBean bean : ManagementFactory.getGarbageCollectorMXBeans()) { System.out.println("bean.getName() = \t\"" + bean.getName() + "\", bean.getCollectionCount() = \t" + bean.getCollectionCount()); @@ -158,9 +156,9 @@ private static void checkGCCounters() { oldGenBean = bean; } } -// if (WhiteBox.getWhiteBox().g1GetTotalFullCollections() != 0 || (oldGenBean != null && oldGenBean.getCollectionCount() != 0)) { + if (oldGenBean != null && oldGenBean.getCollectionCount() != 0) { - throw new RuntimeException("Full gc happened. Test was useless."); + throw new SkippedException("Full gc happened, skip the test."); } } diff --git a/test/hotspot/jtreg/vmTestbase/gc/huge/quicklook/largeheap/MemOptions/MemOptionsTest.java b/test/hotspot/jtreg/vmTestbase/gc/huge/quicklook/largeheap/MemOptions/MemOptionsTest.java index 8eea44148ed..67e629fddcd 100644 --- a/test/hotspot/jtreg/vmTestbase/gc/huge/quicklook/largeheap/MemOptions/MemOptionsTest.java +++ b/test/hotspot/jtreg/vmTestbase/gc/huge/quicklook/largeheap/MemOptions/MemOptionsTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -93,7 +93,7 @@ private void positive(String name, String... opts) throws IOException { var cmd = new ArrayList(); Collections.addAll(cmd, opts); cmd.add(MemStat.class.getName()); - var pb = ProcessTools.createTestJvm(cmd); + var pb = ProcessTools.createTestJavaProcessBuilder(cmd); var output = new OutputAnalyzer(pb.start()); if (output.getExitValue() != 0) { output.reportDiagnosticSummary(); @@ -106,7 +106,7 @@ private void negative(String name, String... opts) throws IOException { var cmd = new ArrayList(); Collections.addAll(cmd, opts); cmd.add(MemStat.class.getName()); - var pb = ProcessTools.createTestJvm(cmd); + var pb = ProcessTools.createTestJavaProcessBuilder(cmd); var output = new OutputAnalyzer(pb.start()); if (output.getExitValue() == 0) { output.reportDiagnosticSummary(); diff --git a/test/hotspot/jtreg/vmTestbase/metaspace/flags/maxMetaspaceSize/TestMaxMetaspaceSize.java b/test/hotspot/jtreg/vmTestbase/metaspace/flags/maxMetaspaceSize/TestMaxMetaspaceSize.java index 5df4b8aea8f..728c6baed6e 100644 --- a/test/hotspot/jtreg/vmTestbase/metaspace/flags/maxMetaspaceSize/TestMaxMetaspaceSize.java +++ b/test/hotspot/jtreg/vmTestbase/metaspace/flags/maxMetaspaceSize/TestMaxMetaspaceSize.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2023, Oracle and/or its affiliates. All rights reserved. * 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,8 +40,8 @@ public class TestMaxMetaspaceSize { public static void main(String[] args) throws Exception { ProcessBuilder pb = - ProcessTools.createTestJvm("-XX:MaxMetaspaceSize=100m", - maxMetaspaceSize.class.getName()); + ProcessTools.createTestJavaProcessBuilder("-XX:MaxMetaspaceSize=100m", + maxMetaspaceSize.class.getName()); OutputAnalyzer out = new OutputAnalyzer(pb.start()); if (out.getExitValue() == 0) { diff --git a/test/hotspot/jtreg/vmTestbase/nsk/jdi/Accessible/isPackagePrivate/accipp001.java b/test/hotspot/jtreg/vmTestbase/nsk/jdi/Accessible/isPackagePrivate/accipp001.java index 8b76843b47e..cdb66bdcf8e 100644 --- a/test/hotspot/jtreg/vmTestbase/nsk/jdi/Accessible/isPackagePrivate/accipp001.java +++ b/test/hotspot/jtreg/vmTestbase/nsk/jdi/Accessible/isPackagePrivate/accipp001.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -109,24 +109,8 @@ private int runThis (String argv[], PrintStream out) { logHandler = new Log(out, argsHandler); Binder binder = new Binder(argsHandler, logHandler); - - if (argsHandler.verbose()) { - debugee = binder.bindToDebugee(debugeeName + " -vbs"); - } else { - debugee = binder.bindToDebugee(debugeeName); - } - - IOPipe pipe = new IOPipe(debugee); - - - debugee.redirectStderr(out); - debugee.resume(); - - String line = pipe.readln(); - if (!line.equals("ready")) { - logHandler.complain("# Cannot recognize debugee's signal: " + line); - return 2; - }; + debugee = Debugee.prepareDebugee(argsHandler, logHandler, + debugeeName + (argsHandler.verbose() ? " -vbs" : "")); // ReferenceType classes[] = debugee.classes(); // for (int i=0; iTerminator class holds a thread which sleeps for the given amount - * of time, and then wakes up and executes System.exit() - * with the given exit status. That thread is daemon, so it doesn't - * prevent application from exiting once all its threads finish - * before it's time for termination. Appointing terminator in zero - * delay implies immediate exit(). - * - *

There is a limitation: you may appoint no more than one terminator - * per application. - */ -public class Terminator { - /** - * Use specific appoint() method to appoint terminator. - * - * @see #appoint(int) - * @see #appoint(int,int) - */ - protected Terminator() {} - - /** - * One terminator per application, or null (by default). - */ - private static Thread terminator = null; - - /** - *

Return timeout (or waittime) value munus the margin - * value (which is assumed 1 minute by default). - * - *

Treat args[0] as $TIMEOUT value, or seek for - * -waittime=$WAITTIME value. If both parameters - * (or either none of them) are assigned, throw an exception to - * report parameters inconsistency. - * - *

Also, seek for -margin=... assignment, or assume margin - * is 1 minute. - * - * @param args Is usually obtained via the application's command-line. - * - * @throws IllegalArgumentException If args[] is inconsistent. - * - * @see #appoint(int) - * @see #appoint(int,int) - */ - public static int parseAppointment(String args[]) { - int timeout=-1, margin=1; - int timeouts=0, waittimes=0, margins=0; - for (int i=0; i 1) - throw new IllegalArgumentException( - "more than one -waittime=... is set"); - if (margins > 1) - throw new IllegalArgumentException( - "more than one -margin=... is set"); - - int result = timeout - margin; - if (result <= 0) - throw new IllegalArgumentException( - "delay appointment must be greater than "+margin+" minutes"); - return result; - } - - /** - * Appoint terminator after the given amount of minutes, - * so that exit status would be 95 (to simulate JCK-like PASS - * status). - * - * @throws IllegalStateException If terminator is already appointed. - * - * @see #appoint(int,int) - * @see #parseAppointment(String[]) - */ - public static void appoint(int minutes) { - appoint(minutes,95); // JCK-like PASS status - } - - /** - * Appoint Terminator for the given amount of minutes, - * so that the given status would be exited when time - * is over. - * - * @throws IllegalStateException If terminator is already appointed. - * - * @see #appoint(int) - * @see #parseAppointment(String[]) - */ - public static void appoint(int minutes, int status) { - if (terminator != null) - throw new IllegalStateException("Terminator is already appointed."); - - final long timeToExit = System.currentTimeMillis() + 60*1000L*minutes; - final int exitStatus = status; - - terminator = new Thread(Terminator.class.getName()) { - public void run() { - long timeToSleep = timeToExit - System.currentTimeMillis(); - if (timeToSleep > 0) - try { - // - // Use wait() instead of sleep(), because Java 2 - // specification doesn't guarantee the method - // sleep() to yield to other threads. - // - Object someDummyObject = new Object(); - synchronized (someDummyObject) { - someDummyObject.wait(timeToSleep); - } - } catch (InterruptedException exception) { - exception.printStackTrace(System.err); - return; - }; - // - // OK, lets do it now: - // - System.err.println( - "#\n# Terminator: prescheduled program termination.\n#"); - System.exit(exitStatus); // terminator to all threads - } - }; - - terminator.setPriority(Thread.MAX_PRIORITY); - terminator.setDaemon(true); - terminator.start(); - } -} diff --git a/test/hotspot/jtreg/vmTestbase/nsk/share/aod/DummyTargetApplication.java b/test/hotspot/jtreg/vmTestbase/nsk/share/aod/DummyTargetApplication.java index d628991a4b2..64688e4a655 100644 --- a/test/hotspot/jtreg/vmTestbase/nsk/share/aod/DummyTargetApplication.java +++ b/test/hotspot/jtreg/vmTestbase/nsk/share/aod/DummyTargetApplication.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2008, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2008, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -54,7 +54,7 @@ protected void targetApplicationActions() { } public void runTargetApplication() { - pipe = SocketIOPipe.createClientIOPipe(log, "localhost", argParser.getPort(), 0); + pipe = SocketIOPipe.createClientIOPipe(log, argParser.getPort(), 0); log.display("Sending signal '" + AODTestRunner.SIGNAL_READY_FOR_ATTACH + "'"); pipe.println(AODTestRunner.SIGNAL_READY_FOR_ATTACH); diff --git a/test/hotspot/jtreg/vmTestbase/nsk/share/aod/TargetApplicationWaitingAgents.java b/test/hotspot/jtreg/vmTestbase/nsk/share/aod/TargetApplicationWaitingAgents.java index 67f4896ea3b..6f80033dff5 100644 --- a/test/hotspot/jtreg/vmTestbase/nsk/share/aod/TargetApplicationWaitingAgents.java +++ b/test/hotspot/jtreg/vmTestbase/nsk/share/aod/TargetApplicationWaitingAgents.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2008, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2008, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -341,7 +341,7 @@ public final void runTargetApplication(String[] args) { /* * When target application initialized send signal to AODTestRunner */ - pipe = SocketIOPipe.createClientIOPipe(log, "localhost", argParser.getPort(), 0); + pipe = SocketIOPipe.createClientIOPipe(log, argParser.getPort(), 0); log.display("Sending signal '" + AODTestRunner.SIGNAL_READY_FOR_ATTACH + "'"); pipe.println(AODTestRunner.SIGNAL_READY_FOR_ATTACH); } diff --git a/test/hotspot/jtreg/vmTestbase/nsk/share/jpda/DebugeeArgumentHandler.java b/test/hotspot/jtreg/vmTestbase/nsk/share/jpda/DebugeeArgumentHandler.java index bb5abbb80f5..98f11a426ea 100644 --- a/test/hotspot/jtreg/vmTestbase/nsk/share/jpda/DebugeeArgumentHandler.java +++ b/test/hotspot/jtreg/vmTestbase/nsk/share/jpda/DebugeeArgumentHandler.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -108,12 +108,12 @@ public DebugeeArgumentHandler(String args[]) { /** * Return name of the host where test executes, specified by * -test.host command line option or - * "localhost" string by default. + * empty string (represents an address of the loopback interface) by default. * * @see #setRawArguments(String[]) */ public String getTestHost() { - return options.getProperty("test.host", "localhost"); + return options.getProperty("test.host", ""); } /** diff --git a/test/hotspot/jtreg/vmTestbase/nsk/share/jpda/DebugeeBinder.java b/test/hotspot/jtreg/vmTestbase/nsk/share/jpda/DebugeeBinder.java index 675cbbdfa2e..ab8b8f7b2b9 100644 --- a/test/hotspot/jtreg/vmTestbase/nsk/share/jpda/DebugeeBinder.java +++ b/test/hotspot/jtreg/vmTestbase/nsk/share/jpda/DebugeeBinder.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -180,7 +180,7 @@ public void prepareForPipeConnection(DebugeeArgumentHandler argumentHandler) { try { pipeServerSocket = new ServerSocket(); pipeServerSocket.setReuseAddress(false); - pipeServerSocket.bind(null); + pipeServerSocket.bind(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0)); } catch (IOException e) { e.printStackTrace(getOutStream()); diff --git a/test/hotspot/jtreg/vmTestbase/nsk/share/jpda/DebugeeProcess.java b/test/hotspot/jtreg/vmTestbase/nsk/share/jpda/DebugeeProcess.java index 10733307679..40261018a12 100644 --- a/test/hotspot/jtreg/vmTestbase/nsk/share/jpda/DebugeeProcess.java +++ b/test/hotspot/jtreg/vmTestbase/nsk/share/jpda/DebugeeProcess.java @@ -110,12 +110,16 @@ public Process getProcess() { // --------------------------------------------------- // - /** Created and return new IOPipe channel to the debugee VM. */ + /** Create and return new IOPipe channel to the debuggee VM. + * The channel should be created before debuggee starts execution, + * i.e. the method assumes debuggee is started, but suspended before + * its main class is loaded. + */ public IOPipe createIOPipe() { if (pipe != null) { throw new TestBug("IOPipe channel is already created"); } - pipe = new IOPipe(this); + pipe = IOPipe.startDebuggerPipe(binder); return pipe; } diff --git a/test/hotspot/jtreg/vmTestbase/nsk/share/jpda/IOPipe.java b/test/hotspot/jtreg/vmTestbase/nsk/share/jpda/IOPipe.java index c54b706996b..1a1d6cab645 100644 --- a/test/hotspot/jtreg/vmTestbase/nsk/share/jpda/IOPipe.java +++ b/test/hotspot/jtreg/vmTestbase/nsk/share/jpda/IOPipe.java @@ -84,7 +84,7 @@ protected IOPipe(Log log, String host, int port, long timeout, boolean listening /** * Creates and starts listening IOPipe at debugger side. */ - public static IOPipe startDebuggerPipe(Binder binder) { + public static IOPipe startDebuggerPipe(DebugeeBinder binder) { IOPipe ioPipe = new IOPipe(binder.getLog(), binder.getArgumentHandler().getDebugeeHost(), binder.getArgumentHandler().getPipePortNumber(), @@ -95,7 +95,6 @@ public static IOPipe startDebuggerPipe(Binder binder) { return ioPipe; } - protected void connect() { super.connect(); } diff --git a/test/hotspot/jtreg/vmTestbase/nsk/share/jpda/SocketIOPipe.java b/test/hotspot/jtreg/vmTestbase/nsk/share/jpda/SocketIOPipe.java index 57fbb7a6915..c8aa2f763c8 100644 --- a/test/hotspot/jtreg/vmTestbase/nsk/share/jpda/SocketIOPipe.java +++ b/test/hotspot/jtreg/vmTestbase/nsk/share/jpda/SocketIOPipe.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,6 +23,7 @@ package nsk.share.jpda; import java.io.IOException; +import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.ServerSocket; import nsk.share.*; @@ -35,13 +36,13 @@ * * Server and client objects should be created using special static methods provided by this class, * for example 'createServerIOPipe(Log log, int port, long timeout)' for server SocketIOPipe - * and 'createClientIOPipe(Log log, String host, int port, long timeout)' for client SocketIOPipe. + * and 'createClientIOPipe(Log log, int port, long timeout)' for client SocketIOPipe. * * When SocketIOPipe is created it can be used to send and receive strings using methods 'readln()' and 'println(String s)'. * TCP/IP connection is established at the first attempt to read or write data. * - * For example, if client process should send string 'OK' to the server process which is run - * at the host 'SERVER_HOST' following code can be written: + * For example, if client process should send string 'OK' to the server process, + * the following code can be written: * * Server side: * @@ -53,8 +54,8 @@ * * Client side: * - * // initialize SocketIOPipe with given values of server host name and port - * SocketIOPipe pipe = SocketIOPipe.createClientIOPipe(log, 'SERVER_HOST', port, timeoutValue); + * // initialize SocketIOPipe with given port + * SocketIOPipe pipe = SocketIOPipe.createClientIOPipe(log, port, timeoutValue); * * String command = "OK"; * // SocketIOPipe tries to create socket and send command to the server @@ -120,7 +121,7 @@ public static SocketIOPipe createServerIOPipe(Log log, int port, long timeout) { // then we should retry the bind() a few times. ss.setReuseAddress(false); } - ss.bind(new InetSocketAddress(port)); + ss.bind(new InetSocketAddress(InetAddress.getLoopbackAddress(), port)); pipe.setServerSocket(ss); } catch (IOException e) { e.printStackTrace(log.getOutStream()); @@ -140,8 +141,9 @@ public static SocketIOPipe createServerIOPipe(Log log, long timeout) { /** * Create attaching SocketIOPipe using given port and timeout */ - public static SocketIOPipe createClientIOPipe(Log log, String host, int port, long timeout) { - return new SocketIOPipe(log, DEFAULT_PIPE_LOG_PREFIX, host, port, timeout, false); + public static SocketIOPipe createClientIOPipe(Log log, int port, long timeout) { + // use null for host to connect to loopback address + return new SocketIOPipe(log, DEFAULT_PIPE_LOG_PREFIX, null, port, timeout, false); } /** diff --git a/test/hotspot/jtreg/vmTestbase/nsk/share/test/Tests.java b/test/hotspot/jtreg/vmTestbase/nsk/share/test/Tests.java index b1755ed47e9..2d5dfa3f623 100644 --- a/test/hotspot/jtreg/vmTestbase/nsk/share/test/Tests.java +++ b/test/hotspot/jtreg/vmTestbase/nsk/share/test/Tests.java @@ -23,6 +23,8 @@ package nsk.share.test; +import jtreg.SkippedException; + import nsk.share.log.*; import nsk.share.runner.*; import nsk.share.TestFailure; @@ -82,6 +84,8 @@ public void execute(Object o) { ((Runnable) o).run(); if (o instanceof TestExitCode) exitCode = ((TestExitCode) o).getExitCode(); + } catch (SkippedException se) { + throw se; } catch (RuntimeException t) { getLog().error(t); exitCode = 97; diff --git a/test/hotspot/jtreg/vmTestbase/vm/compiler/CodeCacheInfo/Test.java b/test/hotspot/jtreg/vmTestbase/vm/compiler/CodeCacheInfo/Test.java index 118d6c8f821..f63eb21a893 100644 --- a/test/hotspot/jtreg/vmTestbase/vm/compiler/CodeCacheInfo/Test.java +++ b/test/hotspot/jtreg/vmTestbase/vm/compiler/CodeCacheInfo/Test.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -69,7 +69,7 @@ public class Test { public static void main(String[] args) throws Exception { { System.out.println("SegmentedCodeCache is enabled"); - var pb = ProcessTools.createTestJvm( + var pb = ProcessTools.createTestJavaProcessBuilder( "-XX:+SegmentedCodeCache", "-XX:+PrintCodeCache", "-version"); @@ -79,7 +79,7 @@ public static void main(String[] args) throws Exception { } { System.out.println("SegmentedCodeCache is disabled"); - var pb = ProcessTools.createTestJvm( + var pb = ProcessTools.createTestJavaProcessBuilder( "-XX:-SegmentedCodeCache", "-XX:+PrintCodeCache", "-version"); diff --git a/test/hotspot/jtreg/vmTestbase/vm/compiler/CodeCacheInfoOnCompilation/Test.java b/test/hotspot/jtreg/vmTestbase/vm/compiler/CodeCacheInfoOnCompilation/Test.java index 4580e7f0ec8..145072487ec 100644 --- a/test/hotspot/jtreg/vmTestbase/vm/compiler/CodeCacheInfoOnCompilation/Test.java +++ b/test/hotspot/jtreg/vmTestbase/vm/compiler/CodeCacheInfoOnCompilation/Test.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2023, Oracle and/or its affiliates. All rights reserved. * 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 Test { private static String REGEXP = "^(CodeCache|(CodeHeap.*)): size=\\d+Kb used=\\d+Kb max_used=\\d+Kb free=\\d+Kb"; public static void main(String[] args) throws Exception { - var pb = ProcessTools.createTestJvm( + var pb = ProcessTools.createTestJavaProcessBuilder( "-XX:-PrintCodeCache", "-XX:+PrintCodeCacheOnCompilation", "-XX:-Inline", diff --git a/test/jdk/ProblemList-zgc.txt b/test/jdk/ProblemList-zgc.txt index 076d247637b..71443499aa8 100644 --- a/test/jdk/ProblemList-zgc.txt +++ b/test/jdk/ProblemList-zgc.txt @@ -27,3 +27,6 @@ # ############################################################################# + +sun/tools/jhsdb/JShellHeapDumpTest.java 8276539 generic-all +sun/tools/jhsdb/HeapDumpTestWithActiveProcess.java 8276539 generic-all diff --git a/test/jdk/ProblemList.txt b/test/jdk/ProblemList.txt index f28e4fecf6e..ff0494c5c43 100644 --- a/test/jdk/ProblemList.txt +++ b/test/jdk/ProblemList.txt @@ -385,7 +385,7 @@ java/awt/Modal/MultipleDialogs/MultipleDialogs3Test.java 8198665 macosx-all java/awt/Modal/MultipleDialogs/MultipleDialogs4Test.java 8198665 macosx-all java/awt/Modal/MultipleDialogs/MultipleDialogs5Test.java 8198665 macosx-all java/awt/Mouse/EnterExitEvents/DragWindowOutOfFrameTest.java 8177326 macosx-all -java/awt/Mouse/EnterExitEvents/ResizingFrameTest.java 8005021 macosx-all +java/awt/Mouse/EnterExitEvents/ResizingFrameTest.java 8005021,8332158 macosx-all,linux-x64 java/awt/Mouse/EnterExitEvents/FullscreenEnterEventTest.java 8051455 macosx-all java/awt/Mouse/MouseModifiersUnitTest/MouseModifiersUnitTest_Standard.java 7124407 macosx-all java/awt/Mouse/RemovedComponentMouseListener/RemovedComponentMouseListener.java 8157170 macosx-all @@ -512,6 +512,10 @@ java/awt/Dialog/MakeWindowAlwaysOnTop/MakeWindowAlwaysOnTop.java 8266243 macosx- # This test fails on macOS 14 java/awt/Choice/SelectNewItemTest/SelectNewItemTest.java 8324782 macosx-all +# Wayland related + +java/awt/FullScreen/FullscreenWindowProps/FullscreenWindowProps.java 8280991 linux-x64 + ############################################################################ # jdk_beans @@ -581,8 +585,8 @@ javax/management/remote/mandatory/connection/RMIConnector_NPETest.java 8267887 g # jdk_net -java/net/DatagramSocket/DatagramSocketExample.java 8308807 aix-ppc64 -java/net/DatagramSocket/DatagramSocketMulticasting.java 8308807 aix-ppc64 +java/net/DatagramSocket/DatagramSocketExample.java 8144003,8308807 macosx-all,aix-ppc64 +java/net/DatagramSocket/DatagramSocketMulticasting.java 8144003,8308807 macosx-all,aix-ppc64 java/net/MulticastSocket/B6427403.java 8308807 aix-ppc64 java/net/MulticastSocket/IPMulticastIF.java 8308807 aix-ppc64 @@ -604,17 +608,18 @@ java/net/MulticastSocket/SetOutgoingIf.java 8308807 aix-ppc6 # jdk_nio -java/nio/channels/DatagramChannel/AdaptorMulticasting.java 8308807 aix-ppc64 +java/nio/channels/DatagramChannel/AdaptorMulticasting.java 8144003,8308807 macosx-all,aix-ppc64 java/nio/channels/DatagramChannel/AfterDisconnect.java 8308807 aix-ppc64 +java/nio/channels/DatagramChannel/BasicMulticastTests.java 8144003 macosx-all java/nio/channels/DatagramChannel/ManySourcesAndTargets.java 8264385 macosx-aarch64 +java/nio/channels/DatagramChannel/MulticastSendReceiveTests.java 8144003 macosx-all +java/nio/channels/DatagramChannel/Promiscuous.java 8144003 macosx-all java/nio/channels/DatagramChannel/Unref.java 8233437 generic-all java/nio/channels/AsynchronousSocketChannel/StressLoopback.java 8211851 aix-ppc64 java/nio/file/Files/probeContentType/Basic.java 8320943 windows-all -java/nio/channels/DatagramChannel/AfterDisconnect.java 8308807 aix-ppc64 - ############################################################################ # jdk_rmi @@ -658,7 +663,6 @@ sun/security/smartcardio/TestMultiplePresent.java 8039280 generic- sun/security/smartcardio/TestPresent.java 8039280 generic-all sun/security/smartcardio/TestTransmit.java 8039280 generic-all com/sun/crypto/provider/Cipher/DES/PerformanceTest.java 8039280 generic-all -com/sun/security/auth/callback/TextCallbackHandler/Default.java 8039280 generic-all com/sun/security/auth/callback/TextCallbackHandler/Password.java 8039280 generic-all com/sun/security/sasl/gsskerb/AuthOnly.java 8039280 generic-all com/sun/security/sasl/gsskerb/ConfSecurityLayer.java 8039280 generic-all @@ -759,6 +763,11 @@ tools/jlink/plugins/CompressorPluginTest.java 8247407 generic- ############################################################################ +# core_svc +tools/launcher/TestXcheckJNIWarnings.java#jdwp-agent 8296936 generic-all + +############################################################################ + # jdk_jdi com/sun/jdi/RepStep.java 8043571 generic-all @@ -794,6 +803,7 @@ sun/tools/jstat/jstatLineCounts1.sh 8248691,8268211 sun/tools/jstat/jstatLineCounts2.sh 8248691,8268211 linux-ppc64le,aix-ppc64,linux-aarch64 sun/tools/jstat/jstatLineCounts3.sh 8248691,8268211 linux-ppc64le,aix-ppc64,linux-aarch64 sun/tools/jstat/jstatLineCounts4.sh 8248691,8268211 linux-ppc64le,aix-ppc64,linux-aarch64 +sun/tools/jhsdb/HeapDumpTestWithActiveProcess.java 8313798 generic-aarch64 ############################################################################ diff --git a/test/jdk/TEST.groups b/test/jdk/TEST.groups index 568c67fdc66..2b5778328c6 100644 --- a/test/jdk/TEST.groups +++ b/test/jdk/TEST.groups @@ -550,26 +550,27 @@ needs_g1gc = \ jdk_core_manual = \ :jdk_core_manual_no_input \ - :jdk_core_manual_no_input_security \ - :jdk_core_manual_requires_human_input + :jdk_security_manual_no_input \ + :jdk_core_manual_interactive \ + :jdk_security_manual_interactive jdk_core_manual_no_input = \ java/net/HugeDataTransferTest.java \ java/net/httpclient/BodyProcessorInputStreamTest.java \ java/net/httpclient/HttpInputStreamTest.java \ - java/nio/MappedByteBuffer/PmemTest.java \ - java/rmi/registry/nonLocalRegistry/NonLocalRegistryTest.java \ java/util/zip/ZipFile/TestZipFile.java \ javax/net/ssl/compatibility/AlpnTest.java \ javax/net/ssl/compatibility/BasicConnectTest.java \ javax/net/ssl/compatibility/HrrTest.java \ javax/net/ssl/compatibility/SniTest.java \ - jdk/nio/zipfs/TestLocOffsetFromZip64EF.java + jdk/nio/zipfs/TestLocOffsetFromZip64EF.java \ + jdk/nio/zipfs/LargeCompressedEntrySizeTest.java -jdk_core_manual_no_input_security = \ +jdk_security_manual_no_input = \ :jdk_security_infra \ com/sun/crypto/provider/Cipher/DES/PerformanceTest.java \ - com/sun/security/auth/callback/TextCallbackHandler/Default.java \ + com/sun/crypto/provider/Cipher/AEAD/GCMIncrementByte4.java \ + com/sun/crypto/provider/Cipher/AEAD/GCMIncrementDirect4.java \ com/sun/security/auth/callback/TextCallbackHandler/Password.java \ com/sun/security/sasl/gsskerb/AuthOnly.java \ com/sun/security/sasl/gsskerb/ConfSecurityLayer.java \ @@ -591,14 +592,24 @@ jdk_core_manual_no_input_security = \ sun/security/smartcardio/TestTransmit.java \ sun/security/tools/jarsigner/compatibility/Compatibility.java -jdk_core_manual_requires_human_input = \ +jdk_core_manual_interactive = \ com/sun/jndi/dns/Test6991580.java \ java/util/TimeZone/DefaultTimeZoneTest.java \ - sun/security/tools/keytool/i18n.java + java/nio/MappedByteBuffer/PmemTest.java \ + java/rmi/registry/nonLocalRegistry/NonLocalRegistryTest.java \ + java/rmi/registry/nonLocalRegistry/NonLocalSkeletonTest.java +jdk_security_manual_interactive = \ + sun/security/tools/keytool/i18n.java \ + java/security/Policy/Root/Root.java \ + sun/security/krb5/config/native/TestDynamicStore.java # Test sets for running inside container environment jdk_containers_extended = \ :jdk_io \ :jdk_nio \ :jdk_svc + +jdk_core_no_security = \ + :jdk_core \ + -:jdk_security \ No newline at end of file diff --git a/test/jdk/com/sun/jdi/JITDebug.java b/test/jdk/com/sun/jdi/JITDebug.java index e7a5647fdd4..45ec0f2ea79 100644 --- a/test/jdk/com/sun/jdi/JITDebug.java +++ b/test/jdk/com/sun/jdi/JITDebug.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -104,7 +104,7 @@ boolean parseArgs(String[] args) { } void testLaunch() { - ProcessBuilder pb = ProcessTools.createTestJvm(); + ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder(); List largs = pb.command(); largs.add("-classpath"); largs.add(Utils.TEST_CLASSES); diff --git a/test/jdk/com/sun/jdi/JdbLockTest.java b/test/jdk/com/sun/jdi/JdbLockTest.java index 948c3e86d82..34723a326f2 100644 --- a/test/jdk/com/sun/jdi/JdbLockTest.java +++ b/test/jdk/com/sun/jdi/JdbLockTest.java @@ -56,7 +56,7 @@ public static void main(String args[]) { } class sleeper extends Thread { - public static int started = 0; + public static volatile int started = 0; public void run() { started = 1; System.out.println(" sleeper starts sleeping"); diff --git a/test/jdk/com/sun/jdi/NoLaunchOptionTest.java b/test/jdk/com/sun/jdi/NoLaunchOptionTest.java index 275b130bf96..fca9d59196f 100644 --- a/test/jdk/com/sun/jdi/NoLaunchOptionTest.java +++ b/test/jdk/com/sun/jdi/NoLaunchOptionTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 2023, Oracle and/or its affiliates. All rights reserved. * 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 @@ public static void main(String[] args) throws Exception { "onthrow=java.lang.ClassNotFoundException,suspend=n", "NotAClass" }); - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(cmd); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(cmd); OutputAnalyzer output = ProcessTools.executeProcess(pb); System.out.println(output.getOutput()); diff --git a/test/jdk/com/sun/jdi/PrivateTransportTest.java b/test/jdk/com/sun/jdi/PrivateTransportTest.java index c12db8b90be..a023b8a752c 100644 --- a/test/jdk/com/sun/jdi/PrivateTransportTest.java +++ b/test/jdk/com/sun/jdi/PrivateTransportTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -82,7 +82,7 @@ private void test() throws Throwable { String libName = transportLib.getFileName().toString().replace("dt_socket", "private_dt_socket"); Files.copy(transportLib, Paths.get(Utils.TEST_CLASSES).resolve(libName)); - ProcessBuilder pb = ProcessTools.createTestJvm( + ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder( "-agentlib:jdwp=transport=private_dt_socket,server=y,suspend=n", "-classpath", Utils.TEST_CLASSES, "HelloWorld"); diff --git a/test/jdk/com/sun/jdi/ProcessAttachTest.java b/test/jdk/com/sun/jdi/ProcessAttachTest.java index 8cccb1e2be3..746b5d047fe 100644 --- a/test/jdk/com/sun/jdi/ProcessAttachTest.java +++ b/test/jdk/com/sun/jdi/ProcessAttachTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2023, Oracle and/or its affiliates. All rights reserved. * 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,8 +58,6 @@ public static void main(String args[]) throws Exception { public class ProcessAttachTest { - public static final String TESTCLASSES = System.getProperty("test.classes"); - public static void main(String[] args) throws Exception { System.out.println("Test 1: Debuggee start with suspend=n"); @@ -71,9 +69,8 @@ public static void main(String[] args) throws Exception { } private static void runTest(String jdwpArg) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder( jdwpArg, - "-classpath", TESTCLASSES, "ProcessAttachTestTarg"); Process p = null; try { diff --git a/test/jdk/com/sun/jdi/RunToExit.java b/test/jdk/com/sun/jdi/RunToExit.java index d5fd5d2b6f7..a7c7058b7aa 100644 --- a/test/jdk/com/sun/jdi/RunToExit.java +++ b/test/jdk/com/sun/jdi/RunToExit.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2004, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2004, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -79,7 +79,7 @@ private static Process launch(String class_name) throws Exception { }; args = VMConnection.insertDebuggeeVMOptions(args); - ProcessBuilder launcher = ProcessTools.createJavaProcessBuilder(args); + ProcessBuilder launcher = ProcessTools.createLimitedTestJavaProcessBuilder(args); System.out.println(launcher.command().stream().collect(Collectors.joining(" ", "Starting: ", ""))); diff --git a/test/jdk/com/sun/jdi/cds/CDSJDITest.java b/test/jdk/com/sun/jdi/cds/CDSJDITest.java index 22abd30163f..0ec201d7035 100644 --- a/test/jdk/com/sun/jdi/cds/CDSJDITest.java +++ b/test/jdk/com/sun/jdi/cds/CDSJDITest.java @@ -39,7 +39,7 @@ public static void runTest(String testname, String[] jarClasses) throws Exceptio File jarClasslistFile = makeClassList(jarClasses); String appJar = buildJar(testname, jarClasses); - // These are the arguments passed to createJavaProcessBuilder() to launch + // These are the arguments passed to createLimitedTestJavaProcessBuilder() to launch // the JDI test. String[] testArgs = { // JVM Args: @@ -67,7 +67,7 @@ public static void runTest(String testname, String[] jarClasses) throws Exceptio }; // Dump the archive - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-Xbootclasspath/a:" + appJar, "-XX:+UnlockDiagnosticVMOptions", "-XX:SharedArchiveFile=./SharedArchiveFile.jsa", "-XX:ExtraSharedClassListFile=" + jarClasslistFile.getPath(), @@ -80,7 +80,7 @@ public static void runTest(String testname, String[] jarClasses) throws Exceptio outputDump.shouldHaveExitValue(0); // Run the test specified JDI test - pb = ProcessTools.createTestJvm(testArgs); + pb = ProcessTools.createTestJavaProcessBuilder(testArgs); OutputAnalyzer outputRun = executeAndLog(pb, "exec"); try { outputRun.shouldContain("sharing"); diff --git a/test/jdk/com/sun/jdi/lib/jdb/Debuggee.java b/test/jdk/com/sun/jdi/lib/jdb/Debuggee.java index 55956ca5811..35b116d2c51 100644 --- a/test/jdk/com/sun/jdi/lib/jdb/Debuggee.java +++ b/test/jdk/com/sun/jdi/lib/jdb/Debuggee.java @@ -122,7 +122,7 @@ public ProcessBuilder prepare() { + onthrowArgs); debuggeeArgs.addAll(options); debuggeeArgs.add(mainClass); - return ProcessTools.createTestJvm(debuggeeArgs); + return ProcessTools.createTestJavaProcessBuilder(debuggeeArgs); } public Debuggee launch(String name) { diff --git a/test/jdk/com/sun/management/HotSpotDiagnosticMXBean/CheckOrigin.java b/test/jdk/com/sun/management/HotSpotDiagnosticMXBean/CheckOrigin.java index d146d98a5fa..ca4c3301db4 100644 --- a/test/jdk/com/sun/management/HotSpotDiagnosticMXBean/CheckOrigin.java +++ b/test/jdk/com/sun/management/HotSpotDiagnosticMXBean/CheckOrigin.java @@ -60,7 +60,7 @@ public static void main(String... args) throws Exception { } ProcessBuilder pb = ProcessTools. - createJavaProcessBuilder( + createLimitedTestJavaProcessBuilder( "--add-exports", "jdk.attach/sun.tools.attach=ALL-UNNAMED", "-XX:+UseG1GC", // this will cause MaxNewSize to be FLAG_SET_ERGO "-XX:+UseCodeAging", diff --git a/test/jdk/com/sun/net/httpserver/AuthenticatorTest b/test/jdk/com/sun/net/httpserver/AuthenticatorTest.java similarity index 75% rename from test/jdk/com/sun/net/httpserver/AuthenticatorTest rename to test/jdk/com/sun/net/httpserver/AuthenticatorTest.java index 1fe7f383035..1456af618fa 100644 --- a/test/jdk/com/sun/net/httpserver/AuthenticatorTest +++ b/test/jdk/com/sun/net/httpserver/AuthenticatorTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2020, 2024, Oracle and/or its affiliates. All rights reserved. * 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,36 +25,36 @@ * @test * @bug 8251496 * @summary Tests for methods in Authenticator - * @run testng/othervm AuthenticatorTest + * @run junit AuthenticatorTest */ import com.sun.net.httpserver.Authenticator; -import com.sun.net.httpserver.BasicAuthenticator; import com.sun.net.httpserver.HttpPrincipal; -import org.testng.annotations.Test; -import static org.testng.Assert.assertEquals; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; public class AuthenticatorTest { @Test public void testFailure() { var failureResult = new Authenticator.Failure(666); - assertEquals(failureResult.getResponseCode(), 666); + assertEquals(666, failureResult.getResponseCode()); } @Test public void testRetry() { var retryResult = new Authenticator.Retry(333); - assertEquals(retryResult.getResponseCode(), 333); + assertEquals(333, retryResult.getResponseCode()); } @Test - public void TestSuccess() { + public void testSuccess() { var principal = new HttpPrincipal("test", "123"); var successResult = new Authenticator.Success(principal); - assertEquals(successResult.getPrincipal(), principal); - assertEquals("test", principal.getName()); + assertEquals(principal, successResult.getPrincipal()); + assertEquals("test", principal.getUsername()); assertEquals("123", principal.getRealm()); } } diff --git a/test/jdk/com/sun/security/auth/callback/TextCallbackHandler/Default.java b/test/jdk/com/sun/security/auth/callback/TextCallbackHandler/Default.java index 606a1ad5e0e..1fb3350c8f7 100644 --- a/test/jdk/com/sun/security/auth/callback/TextCallbackHandler/Default.java +++ b/test/jdk/com/sun/security/auth/callback/TextCallbackHandler/Default.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,31 +23,48 @@ /* * @test + * @library /test/lib /java/security/testlibrary * @bug 4470717 * @summary fix default handling and other misc - * @run main/manual Default + * @run main/othervm Default */ import com.sun.security.auth.callback.TextCallbackHandler; +import jdk.test.lib.Asserts; + import javax.security.auth.callback.*; +import java.io.*; public class Default { - public static void main(String args[]) throws Exception { - TextCallbackHandler h = new TextCallbackHandler(); - NameCallback nc = new NameCallback("Name: ", "charlie"); - ConfirmationCallback cc = new ConfirmationCallback - ("Correct?", - ConfirmationCallback.INFORMATION, - ConfirmationCallback.YES_NO_OPTION, - ConfirmationCallback.NO); - - Callback[] callbacks = { nc, cc }; - h.handle(callbacks); - - if (cc.getSelectedIndex() == ConfirmationCallback.YES) { - System.out.println("yes"); - } else { - System.out.println("no"); + public static void main(String args[]) throws Exception { + InputStream in = System.in; + PrintStream err = System.err; + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + final String defaultName = "charlie"; + final String simulatedInput = "-1\n-1\n"; + HumanInputStream humanInputStream = new HumanInputStream(simulatedInput); + + try (PrintStream prints = new PrintStream(baos)) { + System.setIn(humanInputStream); + System.setErr(prints); + NameCallback nameCallback = new NameCallback("Name: ", defaultName); + ConfirmationCallback confirmationCallback = new ConfirmationCallback( + "Correct?", + ConfirmationCallback.INFORMATION, + ConfirmationCallback.YES_NO_OPTION, + ConfirmationCallback.NO); + new TextCallbackHandler().handle(new Callback[]{nameCallback, confirmationCallback}); + + Asserts.assertEquals(nameCallback.getDefaultName(), defaultName); + Asserts.assertEquals(confirmationCallback.getSelectedIndex(), ConfirmationCallback.NO); + + } finally { + System.setIn(in); + System.setErr(err); } - } + + // check that the default name and confirmation were visible in the output + Asserts.assertTrue(baos.toString().contains(String.format("Name: [%s]", defaultName))); + Asserts.assertTrue(baos.toString().contains("1. No [default]")); + } } diff --git a/test/jdk/com/sun/tools/attach/RunnerUtil.java b/test/jdk/com/sun/tools/attach/RunnerUtil.java index 92f1a951d07..120736de21b 100644 --- a/test/jdk/com/sun/tools/attach/RunnerUtil.java +++ b/test/jdk/com/sun/tools/attach/RunnerUtil.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -53,7 +53,7 @@ public static ProcessThread startApplication(String... additionalOpts) throws Th "-Dattach.test=true", "-classpath", classpath, "Application" }); String[] args = Utils.addTestJavaOpts(myArgs); - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(args); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(args); ProcessThread pt = new ProcessThread("runApplication", (line) -> line.equals(Application.READY_MSG), pb); pt.start(); return pt; diff --git a/test/jdk/java/awt/Choice/ChoicePopupLocation/ChoicePopupLocation.java b/test/jdk/java/awt/Choice/ChoicePopupLocation/ChoicePopupLocation.java index 229b0492f24..49c146c408b 100644 --- a/test/jdk/java/awt/Choice/ChoicePopupLocation/ChoicePopupLocation.java +++ b/test/jdk/java/awt/Choice/ChoicePopupLocation/ChoicePopupLocation.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -113,6 +113,8 @@ private static void openPopup(final Choice choice) throws Exception { robot.setAutoDelay(100); robot.setAutoWaitForIdle(true); robot.waitForIdle(); + robot.delay(500); + Point pt = choice.getLocationOnScreen(); robot.mouseMove(pt.x + choice.getWidth() / 2, pt.y + choice.getHeight() / 2); diff --git a/test/jdk/java/awt/Choice/PopupPosTest/PopupPosTest.java b/test/jdk/java/awt/Choice/PopupPosTest/PopupPosTest.java index 73b94b5d150..b7a5cdea072 100644 --- a/test/jdk/java/awt/Choice/PopupPosTest/PopupPosTest.java +++ b/test/jdk/java/awt/Choice/PopupPosTest/PopupPosTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2004, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2004, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -30,8 +30,18 @@ @run main PopupPosTest */ -import java.awt.*; -import java.awt.event.*; +import java.awt.BorderLayout; +import java.awt.Choice; +import java.awt.Dimension; +import java.awt.Font; +import java.awt.Frame; +import java.awt.Point; +import java.awt.Robot; +import java.awt.Toolkit; +import java.awt.event.InputEvent; +import java.awt.event.ItemEvent; +import java.awt.event.ItemListener; +import java.awt.event.KeyEvent; public class PopupPosTest { @@ -66,6 +76,7 @@ public TestFrame() { robot = new Robot(); robot.setAutoDelay(50); robot.waitForIdle(); + robot.delay(500); // fix for 6175418. When we take "choice.getHeight()/2" // divider 2 is not sufficiently big to hit into the // small box Choice. We should use bigger divider to get @@ -108,9 +119,9 @@ public void itemStateChanged(ItemEvent ie) { public void mouseMoveAndPressOnChoice(int x, int y){ openChoice(); robot.mouseMove(x, y); - robot.mousePress(InputEvent.BUTTON1_MASK); + robot.mousePress(InputEvent.BUTTON1_DOWN_MASK); robot.delay(30); - robot.mouseRelease(InputEvent.BUTTON1_MASK); + robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK); robot.waitForIdle(); //should close choice after each test stage closeChoice(); @@ -121,9 +132,9 @@ public void openChoice(){ Point pt = choice.getLocationOnScreen(); robot.mouseMove(pt.x + choice.getWidth() - choice.getHeight()/4, pt.y + choice.getHeight()/2); - robot.mousePress(InputEvent.BUTTON1_MASK); + robot.mousePress(InputEvent.BUTTON1_DOWN_MASK); robot.delay(30); - robot.mouseRelease(InputEvent.BUTTON1_MASK); + robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK); robot.waitForIdle(); } public void closeChoice(){ diff --git a/test/jdk/java/awt/Focus/NonFocusableBlockedOwnerTest/NonFocusableBlockedOwnerTest.java b/test/jdk/java/awt/Focus/NonFocusableBlockedOwnerTest/NonFocusableBlockedOwnerTest.java index abf8d57cecd..6d5c9a274e9 100644 --- a/test/jdk/java/awt/Focus/NonFocusableBlockedOwnerTest/NonFocusableBlockedOwnerTest.java +++ b/test/jdk/java/awt/Focus/NonFocusableBlockedOwnerTest/NonFocusableBlockedOwnerTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -79,6 +79,7 @@ public void run() { } waitTillShown(dialog); + robot.delay(500); clickOn(button); if (frame == KeyboardFocusManager.getCurrentKeyboardFocusManager().getActiveWindow()) { throw new RuntimeException("Test failed!"); diff --git a/test/jdk/java/awt/Focus/RowToleranceTransitivityTest.java b/test/jdk/java/awt/Focus/RowToleranceTransitivityTest.java index 099e81a1ab0..e3ea5ce0c0c 100644 --- a/test/jdk/java/awt/Focus/RowToleranceTransitivityTest.java +++ b/test/jdk/java/awt/Focus/RowToleranceTransitivityTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2024, Oracle and/or its affiliates. All rights reserved. * 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,7 +28,7 @@ @summary Tests for a transitivity problem with ROW_TOLERANCE in SortingFTP. @run main RowToleranceTransitivityTest */ -import java.awt.BorderLayout; + import java.awt.Component; import java.awt.Dimension; import java.awt.EventQueue; @@ -36,7 +36,6 @@ import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.KeyboardFocusManager; -import java.awt.Panel; import java.awt.Point; import java.awt.Robot; import java.awt.event.FocusAdapter; @@ -49,8 +48,6 @@ import javax.swing.JLabel; import javax.swing.JPanel; import java.util.concurrent.atomic.AtomicBoolean; -import java.lang.reflect.InvocationTargetException; -import java.util.concurrent.atomic.AtomicBoolean; public class RowToleranceTransitivityTest { static JFrame frame; @@ -60,7 +57,7 @@ public class RowToleranceTransitivityTest { static GridBagConstraints gc; static Robot robot; - static AtomicBoolean focusGained = new AtomicBoolean(false); + static final AtomicBoolean focusGained = new AtomicBoolean(false); public static void main(String[] args) throws Exception { robot = new Robot(); @@ -121,6 +118,7 @@ public void focusGained(FocusEvent e) { robot.delay(1000); test(); } finally { + robot.keyRelease(KeyEvent.VK_TAB); if (frame != null) { frame.dispose(); } diff --git a/test/jdk/java/awt/Focus/WrongKeyTypedConsumedTest/WrongKeyTypedConsumedTest.java b/test/jdk/java/awt/Focus/WrongKeyTypedConsumedTest/WrongKeyTypedConsumedTest.java index 7a71d5f77f8..bae0e493634 100644 --- a/test/jdk/java/awt/Focus/WrongKeyTypedConsumedTest/WrongKeyTypedConsumedTest.java +++ b/test/jdk/java/awt/Focus/WrongKeyTypedConsumedTest/WrongKeyTypedConsumedTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2008, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2008, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -75,6 +75,7 @@ public void start () frame.setLocationRelativeTo(null); frame.setVisible(true); Util.waitForIdle(robot); + robot.delay(500); if (!frame.isActive()) { throw new RuntimeException("Test Fialed: frame isn't active"); diff --git a/test/jdk/java/awt/Frame/MaximizedToIconified/MaximizedToIconified.java b/test/jdk/java/awt/Frame/MaximizedToIconified/MaximizedToIconified.java index ac1a3232d65..7c737923eba 100644 --- a/test/jdk/java/awt/Frame/MaximizedToIconified/MaximizedToIconified.java +++ b/test/jdk/java/awt/Frame/MaximizedToIconified/MaximizedToIconified.java @@ -45,7 +45,7 @@ public class MaximizedToIconified { - static volatile int lastFrameState = Frame.NORMAL; + static volatile int lastFrameState; static volatile boolean failed = false; static volatile Toolkit myKit; private static Robot robot; @@ -77,6 +77,8 @@ private static void examineStates(int states[]) { frame.setSize(200, 200); frame.setVisible(true); + lastFrameState = Frame.NORMAL; + robot.waitForIdle(); frame.addWindowStateListener(new WindowStateListener() { @@ -114,7 +116,12 @@ private static void doTest() { // because Toolkit.isFrameStateSupported() method reports these states // as not supported. And such states will simply be skipped. examineStates(new int[] {Frame.MAXIMIZED_BOTH, Frame.ICONIFIED, Frame.NORMAL}); + System.out.println("------"); examineStates(new int[] {Frame.ICONIFIED, Frame.MAXIMIZED_BOTH, Frame.NORMAL}); + System.out.println("------"); + examineStates(new int[] {Frame.NORMAL, Frame.MAXIMIZED_BOTH, Frame.ICONIFIED}); + System.out.println("------"); + examineStates(new int[] {Frame.NORMAL, Frame.ICONIFIED, Frame.MAXIMIZED_BOTH}); } diff --git a/test/jdk/java/awt/Frame/MiscUndecorated/ActiveAWTWindowTest.java b/test/jdk/java/awt/Frame/MiscUndecorated/ActiveAWTWindowTest.java index 2abd549c1ba..7aa5b8c5132 100644 --- a/test/jdk/java/awt/Frame/MiscUndecorated/ActiveAWTWindowTest.java +++ b/test/jdk/java/awt/Frame/MiscUndecorated/ActiveAWTWindowTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2024, Oracle and/or its affiliates. All rights reserved. * 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,17 +40,27 @@ public class ActiveAWTWindowTest { private Frame frame, frame2; private Button button, button2; private TextField textField, textField2; - private int eventType, eventType1; - private ExtendedRobot robot; - private Object lock1 = new Object(); - private Object lock2 = new Object(); - private Object lock3 = new Object(); + private volatile int eventType; + private final Object lock1 = new Object(); + private final Object lock2 = new Object(); + private final Object lock3 = new Object(); private boolean passed = true; - private int delay = 150; + private final int delay = 150; public static void main(String[] args) { ActiveAWTWindowTest test = new ActiveAWTWindowTest(); - test.doTest(); + try { + test.doTest(); + } finally { + EventQueue.invokeLater(() -> { + if (test.frame != null) { + test.frame.dispose(); + } + if (test.frame2 != null) { + test.frame2.dispose(); + } + }); + } } public ActiveAWTWindowTest() { @@ -105,7 +115,7 @@ public void windowDeactivated(WindowEvent e) { System.out.println("Undecorated Frame got Deactivated\n"); synchronized (lock2) { try { - lock2.notifyAll(); + lock2.notifyAll(); } catch (Exception ex) { ex.printStackTrace(); } @@ -146,6 +156,7 @@ public void actionPerformed(ActionEvent e) { } public void doTest() { + ExtendedRobot robot; try { robot = new ExtendedRobot(); } catch (Exception e) { @@ -153,13 +164,14 @@ public void doTest() { throw new RuntimeException("Cannot create robot"); } + robot.setAutoDelay(delay); + robot.setAutoWaitForIdle(true); + robot.waitForIdle(5*delay); robot.mouseMove(button.getLocationOnScreen().x + button.getSize().width / 2, button.getLocationOnScreen().y + button.getSize().height / 2); - robot.waitForIdle(delay); - robot.mousePress(InputEvent.BUTTON1_MASK); - robot.waitForIdle(delay); - robot.mouseRelease(InputEvent.BUTTON1_MASK); + robot.mousePress(InputEvent.BUTTON1_DOWN_MASK); + robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK); if (eventType != WindowEvent.WINDOW_ACTIVATED) { synchronized (lock1) { @@ -176,15 +188,12 @@ public void doTest() { "undecorated frame is activated!"); } - eventType1 = -1; eventType = -1; robot.mouseMove(button2.getLocationOnScreen().x + button2.getSize().width / 2, button2.getLocationOnScreen().y + button2.getSize().height / 2); - robot.waitForIdle(delay); - robot.mousePress(InputEvent.BUTTON1_MASK); - robot.waitForIdle(delay); - robot.mouseRelease(InputEvent.BUTTON1_MASK); + robot.mousePress(InputEvent.BUTTON1_DOWN_MASK); + robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK); if (eventType != WindowEvent.WINDOW_DEACTIVATED) { synchronized (lock2) { diff --git a/test/jdk/java/awt/Frame/MiscUndecorated/RepaintTest.java b/test/jdk/java/awt/Frame/MiscUndecorated/RepaintTest.java index ce4ecc7e36c..cf286601001 100644 --- a/test/jdk/java/awt/Frame/MiscUndecorated/RepaintTest.java +++ b/test/jdk/java/awt/Frame/MiscUndecorated/RepaintTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2024, Oracle and/or its affiliates. All rights reserved. * 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,27 +28,29 @@ * all the components on it are repainted correctly * @author Jitender(jitender.singh@eng.sun.com) area=AWT * @author yan - * @library /lib/client - * @build ExtendedRobot + * @library /lib/client /test/lib + * @build ExtendedRobot jdk.test.lib.Platform * @run main RepaintTest */ +import jdk.test.lib.Platform; + import java.awt.BorderLayout; import java.awt.Button; import java.awt.Color; import java.awt.Component; import java.awt.Container; +import java.awt.EventQueue; import java.awt.Frame; import java.awt.Panel; import java.awt.Point; import java.awt.Rectangle; import java.awt.TextField; -import java.awt.Toolkit; -import java.awt.event.*; import javax.swing.JFrame; import javax.swing.JButton; import javax.swing.JTextField; import javax.swing.JPanel; +import java.awt.event.ActionListener; import java.awt.image.BufferedImage; import java.awt.image.PixelGrabber; import java.io.File; @@ -57,38 +59,24 @@ public class RepaintTest { private static final int delay = 150; private Frame frame; - private Container panel1, panel2; private Component button; private Component textField; private ExtendedRobot robot; private final Object buttonLock = new Object(); - private boolean passed = true; - private boolean buttonClicked = false; + private volatile boolean buttonClicked = false; private final int MAX_TOLERANCE_LEVEL = 10; - public static void main(String[] args) { + public static void main(String[] args) throws Exception { RepaintTest test = new RepaintTest(); - test.doTest(false); try { - Toolkit.getDefaultToolkit().getSystemEventQueue().invokeAndWait(new Runnable() { - public void run() { - test.frame.dispose(); - } - }); - } catch (Exception e) { - e.printStackTrace(); - throw new RuntimeException("Unexpected Exception occured"); + test.doTest(false); + } finally { + EventQueue.invokeAndWait(test::dispose); } - test.doTest(true); try { - Toolkit.getDefaultToolkit().getSystemEventQueue().invokeAndWait(new Runnable() { - public void run() { - test.frame.dispose(); - } - }); - } catch (Exception e) { - e.printStackTrace(); - throw new RuntimeException("Unexpected Exception occured"); + test.doTest(true); + } finally { + EventQueue.invokeAndWait(test::dispose); } } @@ -101,8 +89,8 @@ private void initializeGUI(boolean swingControl) { button = createButton(swingControl, (swingControl ? "Swing Button" : "AWT Button")); textField = swingControl ? new JTextField("TextField") : new TextField("TextField"); - panel1 = swingControl ? new JPanel() : new Panel(); - panel2 = swingControl ? new JPanel() : new Panel(); + Container panel1 = swingControl ? new JPanel() : new Panel(); + Container panel2 = swingControl ? new JPanel() : new Panel(); panel1.add(button); panel2.add(textField); frame.add(panel2, BorderLayout.SOUTH); @@ -112,58 +100,44 @@ private void initializeGUI(boolean swingControl) { frame.setBackground(Color.green); frame.setVisible(true); } + + private void dispose() { + if (frame != null) { + frame.dispose(); + } + } + private Component createButton(boolean swingControl, String txt) { + ActionListener actionListener = e -> { + buttonClicked = true; + System.out.println("Clicked!!"); + synchronized (buttonLock) { + try { + buttonLock.notifyAll(); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + }; + if(swingControl) { JButton jbtn = new JButton(txt); - jbtn.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - buttonClicked = true; - synchronized (buttonLock) { - try { - buttonLock.notifyAll(); - } catch (Exception ex) { - ex.printStackTrace(); - } - } - } - }); + jbtn.addActionListener(actionListener); return jbtn; } else { Button btn = new Button(txt); - btn.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - buttonClicked = true; - synchronized (buttonLock) { - try { - buttonLock.notifyAll(); - } catch (Exception ex) { - ex.printStackTrace(); - } - } - } - }); + btn.addActionListener(actionListener); return btn; } } - public void doTest(boolean swingControl) { - try { - Toolkit.getDefaultToolkit().getSystemEventQueue().invokeAndWait(new Runnable() { - public void run() { - initializeGUI(swingControl); - } - }); - } catch (Exception e) { - e.printStackTrace(); - throw new RuntimeException("Interrupted or unexpected Exception occured"); - } - try { - robot = new ExtendedRobot(); - robot.waitForIdle(1000); - } catch (Exception e) { - e.printStackTrace(); - throw new RuntimeException("Cannot create robot"); - } + public void doTest(boolean swingControl) throws Exception { + + robot = new ExtendedRobot(); + robot.setAutoDelay(50); + + EventQueue.invokeAndWait(() -> initializeGUI(swingControl)); + robot.waitForIdle(1000); robot.mouseMove(button.getLocationOnScreen().x + button.getSize().width / 2, button.getLocationOnScreen().y + button.getSize().height / 2); @@ -180,54 +154,50 @@ public void run() { } } if (! buttonClicked) { - passed = false; System.err.println("ActionEvent not triggered when " + "button is clicked!"); throw new RuntimeException("ActionEvent not triggered"); } - robot.waitForIdle(delay * 5); // Need to wait until look of the button + robot.waitForIdle(1000); // Need to wait until look of the button // returns to normal undepressed - passed = paintAndRepaint(button, (swingControl? "J": "")+"Button"); - if( !paintAndRepaint(button, (swingControl? "J": "")+"TextField") ) { - passed = false; - } - if(!passed) { + + if (!paintAndRepaint(button, (swingControl ? "J" : "") + "Button") + || !paintAndRepaint(textField, (swingControl ? "J" : "") + "TextField")) { throw new RuntimeException("Test failed"); } } - private boolean paintAndRepaint(Component comp, String prefix) { + private boolean paintAndRepaint(Component comp, String prefix) throws Exception { + boolean passed = true; //Capture the component & compare it's dimensions //before iconifying & after frame comes back from //iconified to normal state - System.out.println("paintAndRepaint "+prefix); + System.out.printf("paintAndRepaint %s %s\n", prefix, comp); Point p = comp.getLocationOnScreen(); Rectangle bRect = new Rectangle((int)p.getX(), (int)p.getY(), comp.getWidth(), comp.getHeight()); BufferedImage capturedImage = robot.createScreenCapture(bRect); + BufferedImage frameImage = robot.createScreenCapture(frame.getBounds()); - try { - Toolkit.getDefaultToolkit().getSystemEventQueue().invokeAndWait(new Runnable() { - public void run() { - frame.setExtendedState(Frame.ICONIFIED); - } - }); - } catch (Exception e) { - e.printStackTrace(); - throw new RuntimeException("Exception while setting extended state ICONIFIED"); - } - robot.waitForIdle(delay * 5); - try { - Toolkit.getDefaultToolkit().getSystemEventQueue().invokeAndWait(new Runnable() { - public void run() { - frame.setExtendedState(Frame.NORMAL); - } - }); - } catch (Exception e) { - e.printStackTrace(); - throw new RuntimeException("Exception while setting extended state NORMAL"); + EventQueue.invokeAndWait(() -> frame.setExtendedState(Frame.ICONIFIED)); + robot.waitForIdle(1500); + EventQueue.invokeAndWait(() -> frame.setExtendedState(Frame.NORMAL)); + robot.waitForIdle(1500); + + if (Platform.isOnWayland()) { + // Robot.mouseMove does not move the actual mouse cursor on the + // screen in X11 compatibility mode on Wayland, but only within + // the XWayland server. + // This can cause the test to fail if the actual mouse cursor on + // the screen is somewhere over the test window, so that when the + // test window is restored from the iconified state, it's detected + // that the mouse cursor has moved to the mouse cursor position on + // the screen, and is no longer hovering over the button, so the + // button is painted differently. + robot.mouseMove(button.getLocationOnScreen().x + button.getSize().width / 2, + button.getLocationOnScreen().y + button.getSize().height / 2); + robot.waitForIdle(); } - robot.waitForIdle(delay * 5); if (! p.equals(comp.getLocationOnScreen())) { passed = false; @@ -238,14 +208,20 @@ public void run() { bRect = new Rectangle((int)p.getX(), (int)p.getY(), comp.getWidth(), comp.getHeight()); BufferedImage capturedImage2 = robot.createScreenCapture(bRect); + BufferedImage frameImage2 = robot.createScreenCapture(frame.getBounds()); - if (! compareImages(capturedImage, capturedImage2)) { + if (!compareImages(capturedImage, capturedImage2)) { passed = false; + try { - javax.imageio.ImageIO.write(capturedImage, "jpg", new File( - prefix+"BeforeMinimize.jpg")); - javax.imageio.ImageIO.write(capturedImage2, "jpg", new File( - prefix+"AfterMinimize.jpg")); + javax.imageio.ImageIO.write(capturedImage, "png", + new File(prefix + "BeforeMinimize.png")); + javax.imageio.ImageIO.write(capturedImage2, "png", + new File(prefix + "AfterMinimize.png")); + javax.imageio.ImageIO.write(frameImage, "png", + new File("Frame" + prefix + "BeforeMinimize.png")); + javax.imageio.ImageIO.write(frameImage2, "png", + new File("Frame" + prefix + "AfterMinimize.png")); } catch (Exception e) { e.printStackTrace(); } diff --git a/test/jdk/java/awt/KeyboardFocusmanager/ConsumeNextMnemonicKeyTypedTest/ConsumeNextMnemonicKeyTypedTest.java b/test/jdk/java/awt/KeyboardFocusmanager/ConsumeNextMnemonicKeyTypedTest/ConsumeNextMnemonicKeyTypedTest.java index 9ae79971af0..5b2dc2844f1 100644 --- a/test/jdk/java/awt/KeyboardFocusmanager/ConsumeNextMnemonicKeyTypedTest/ConsumeNextMnemonicKeyTypedTest.java +++ b/test/jdk/java/awt/KeyboardFocusmanager/ConsumeNextMnemonicKeyTypedTest/ConsumeNextMnemonicKeyTypedTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2006, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2006, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -33,34 +33,50 @@ import jdk.test.lib.Platform; -import java.awt.*; -import javax.swing.*; -import java.awt.event.*; +import javax.swing.JFrame; +import javax.swing.JMenu; +import javax.swing.JMenuBar; +import javax.swing.JMenuItem; +import javax.swing.JTextField; +import javax.swing.SwingUtilities; +import java.awt.Robot; +import java.awt.event.KeyEvent; +import java.awt.event.MouseEvent; public class ConsumeNextMnemonicKeyTypedTest { - Robot robot; - JFrame frame = new JFrame("Test Frame"); - JTextField text = new JTextField(); - JMenuBar bar = new JMenuBar(); - JMenu menu = new JMenu("Menu"); - JMenuItem item = new JMenuItem("item"); - - public static void main(String[] args) { - ConsumeNextMnemonicKeyTypedTest app = new ConsumeNextMnemonicKeyTypedTest(); - app.init(); - app.start(); - } - - public void init() { + static Robot robot; + static JFrame frame; + static JTextField text; + static JMenuBar bar; + static JMenu menu; + static JMenuItem item; + + public static void main(String[] args) throws Exception { + robot = new Robot(); + robot.setAutoDelay(50); try { - robot = new Robot(); - robot.setAutoDelay(50); - } catch (AWTException e) { - throw new RuntimeException("Error: unable to create robot", e); + SwingUtilities.invokeAndWait(ConsumeNextMnemonicKeyTypedTest::init); + + robot.waitForIdle(); + robot.delay(500); + + test(); + } finally { + SwingUtilities.invokeAndWait(() -> { + if (frame != null) { + frame.dispose(); + } + }); } } - public void start() { + public static void init() { + frame = new JFrame("Test Frame"); + text = new JTextField(); + bar = new JMenuBar(); + menu = new JMenu("Menu"); + item = new JMenuItem("item"); + menu.setMnemonic('f'); item.setMnemonic('i'); menu.add(item); @@ -72,20 +88,18 @@ public void start() { frame.setLocationRelativeTo(null); frame.setVisible(true); - - test(); } - void test() { + static void test() { robot.waitForIdle(); if (!text.isFocusOwner()) { robot.mouseMove(text.getLocationOnScreen().x + 5, text.getLocationOnScreen().y + 5); robot.delay(100); - robot.mousePress(MouseEvent.BUTTON1_MASK); + robot.mousePress(MouseEvent.BUTTON1_DOWN_MASK); robot.delay(100); - robot.mouseRelease(MouseEvent.BUTTON1_MASK); + robot.mouseRelease(MouseEvent.BUTTON1_DOWN_MASK); int iter = 10; while (!text.isFocusOwner() && iter-- > 0) { @@ -146,7 +160,7 @@ void test() { robot.waitForIdle(); - System.err.println("Test: chracter typed with VK_A: " + text.getText()); + System.err.println("Test: character typed with VK_A: " + text.getText()); if (!charA.equals(text.getText())) { throw new RuntimeException("Test failed!"); diff --git a/test/jdk/java/awt/List/ActionEventTest/ActionEventTest.java b/test/jdk/java/awt/List/ActionEventTest/ActionEventTest.java index ecda27e4249..19665a6dc29 100644 --- a/test/jdk/java/awt/List/ActionEventTest/ActionEventTest.java +++ b/test/jdk/java/awt/List/ActionEventTest/ActionEventTest.java @@ -29,59 +29,55 @@ * @run main ActionEventTest */ -import java.awt.AWTException; +import java.awt.EventQueue; import java.awt.FlowLayout; import java.awt.Frame; import java.awt.List; import java.awt.Robot; import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; import java.awt.event.KeyEvent; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; -public class ActionEventTest extends Frame { - List list; - Robot robot; - public ActionEventTest() { - try { - robot = new Robot(); - robot.setAutoDelay(100); - robot.setAutoWaitForIdle(true); - } catch(AWTException e) { - throw new RuntimeException(e.getMessage()); - } +public class ActionEventTest { + + static List list; + static Frame frame; + static Robot robot; + static final CountDownLatch countDownLatch = new CountDownLatch(1); + static volatile boolean failed; + + static void initAndShowGui() { list = new List(1, false); list.add("0"); - add(list); - setSize(400,400); - setLayout(new FlowLayout()); - setLocationRelativeTo(null); - pack(); - setVisible(true); - } - void performTest() { - list.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent ae) { - int md = ae.getModifiers(); - int expectedMask = ActionEvent.ALT_MASK | ActionEvent.CTRL_MASK - | ActionEvent.SHIFT_MASK; - - if ((md & expectedMask) != expectedMask) { - - robot.keyRelease(KeyEvent.VK_CONTROL); - robot.keyRelease(KeyEvent.VK_SHIFT); - robot.keyRelease(KeyEvent.VK_ALT); - dispose(); - throw new RuntimeException("Action Event modifiers are not" - + " set correctly."); - } + list.addActionListener(ae -> { + int md = ae.getModifiers(); + int expectedMask = ActionEvent.ALT_MASK | ActionEvent.CTRL_MASK + | ActionEvent.SHIFT_MASK; + + if ((md & expectedMask) != expectedMask) { + failed = true; } + countDownLatch.countDown(); }); + frame = new Frame("ActionEventTest"); + frame.add(list); + frame.setSize(400, 400); + frame.setLayout(new FlowLayout()); + frame.setLocationRelativeTo(null); + frame.pack(); + frame.setVisible(true); list.select(0); + } + + static void performTest() { + robot.waitForIdle(); + robot.delay(500); + robot.keyPress(KeyEvent.VK_ALT); robot.keyPress(KeyEvent.VK_SHIFT); robot.keyPress(KeyEvent.VK_CONTROL); @@ -93,9 +89,29 @@ public void actionPerformed(ActionEvent ae) { robot.keyRelease(KeyEvent.VK_ALT); } - public static void main(String args[]) { - ActionEventTest test = new ActionEventTest(); - test.performTest(); - test.dispose(); + public static void main(String[] args) throws Exception { + robot = new Robot(); + robot.setAutoDelay(100); + robot.setAutoWaitForIdle(true); + + try { + EventQueue.invokeAndWait(ActionEventTest::initAndShowGui); + performTest(); + } finally { + EventQueue.invokeAndWait(() -> { + if (frame != null) { + frame.dispose(); + } + }); + } + + if (!countDownLatch.await(10, TimeUnit.SECONDS)) { + throw new RuntimeException("Action Listener is not triggered"); + } + + if (failed) { + throw new RuntimeException("Action Event modifiers are not" + + " set correctly."); + } } } diff --git a/test/jdk/java/awt/List/KeyEventsTest/KeyEventsTest.java b/test/jdk/java/awt/List/KeyEventsTest/KeyEventsTest.java index 13a019bb6dc..16fbccdafd1 100644 --- a/test/jdk/java/awt/List/KeyEventsTest/KeyEventsTest.java +++ b/test/jdk/java/awt/List/KeyEventsTest/KeyEventsTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2024, Oracle and/or its affiliates. All rights reserved. * 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,33 +32,87 @@ @run main KeyEventsTest */ -import java.awt.*; -import java.awt.event.*; -import java.lang.reflect.*; +import java.awt.BorderLayout; +import java.awt.EventQueue; +import java.awt.KeyboardFocusManager; +import java.awt.Frame; +import java.awt.List; +import java.awt.Panel; +import java.awt.Point; +import java.awt.Robot; +import java.awt.event.FocusEvent; +import java.awt.event.FocusListener; +import java.awt.event.InputEvent; +import java.awt.event.ItemEvent; +import java.awt.event.ItemListener; +import java.awt.event.KeyEvent; +import java.awt.event.KeyListener; import jdk.test.lib.Platform; -public class KeyEventsTest extends Frame implements ItemListener, FocusListener, KeyListener -{ +public class KeyEventsTest { TestState currentState; final Object LOCK = new Object(); final int ACTION_TIMEOUT = 500; - List single = new List(3, false); - List multiple = new List(3, true); + List single; + List multiple; - Panel p1 = new Panel (); - Panel p2 = new Panel (); + KeyFrame keyFrame; - public static void main(final String[] args) { + static Robot r; + + public static void main(final String[] args) throws Exception { + r = new Robot(); KeyEventsTest app = new KeyEventsTest(); - app.init(); - app.start(); + try { + EventQueue.invokeAndWait(app::initAndShowGui); + r.waitForIdle(); + r.delay(500); + app.doTest(); + } finally { + EventQueue.invokeAndWait(() -> { + if (app.keyFrame != null) { + app.keyFrame.dispose(); + } + }); + } + } + + class KeyFrame extends Frame implements ItemListener, FocusListener, KeyListener { + public void itemStateChanged(ItemEvent ie) { + System.out.println("itemStateChanged-" + ie); + currentState.setAction(true); + } + + public void focusGained(FocusEvent e) { + synchronized (LOCK) { + LOCK.notifyAll(); + } + } + + public void focusLost(FocusEvent e) { + } + + public void keyPressed(KeyEvent e) { + System.out.println("keyPressed-" + e); + } + + public void keyReleased(KeyEvent e) { + System.out.println("keyReleased-" + e); + } + + public void keyTyped(KeyEvent e) { + System.out.println("keyTyped-" + e); + } } - public void init() - { - setLayout (new BorderLayout ()); + public void initAndShowGui() { + keyFrame = new KeyFrame(); + keyFrame.setLayout(new BorderLayout ()); + + single = new List(3, false); + multiple = new List(3, true); single.add("0"); single.add("1"); @@ -80,161 +134,105 @@ public void init() multiple.add("7"); multiple.add("8"); - single.addKeyListener(this); - single.addItemListener(this); - single.addFocusListener(this); + single.addKeyListener(keyFrame); + single.addItemListener(keyFrame); + single.addFocusListener(keyFrame); + Panel p1 = new Panel(); p1.add(single); - add("North", p1); + keyFrame.add("North", p1); - multiple.addKeyListener(this); - multiple.addItemListener(this); - multiple.addFocusListener(this); + multiple.addKeyListener(keyFrame); + multiple.addItemListener(keyFrame); + multiple.addFocusListener(keyFrame); + Panel p2 = new Panel(); p2.add(multiple); - add("South", p2); - - }//End init() - - public void start () - { - - try{ - setSize (200,200); - validate(); - setUndecorated(true); - setLocationRelativeTo(null); - setVisible(true); - - doTest(); - System.out.println("Test passed."); - } catch (Exception e) { - e.printStackTrace(); - throw new RuntimeException("The test failed."); - } + keyFrame.add("South", p2); - }// start() - - public void itemStateChanged (ItemEvent ie) { - System.out.println("itemStateChanged-"+ie); - this.currentState.setAction(true); + keyFrame.setSize(200, 200); + keyFrame.validate(); + keyFrame.setUndecorated(true); + keyFrame.setLocationRelativeTo(null); + keyFrame.setVisible(true); } - public void focusGained(FocusEvent e){ - + private void test(TestState currentState) throws Exception { synchronized (LOCK) { - LOCK.notifyAll(); - } - - } - - public void focusLost(FocusEvent e){ - } - - public void keyPressed(KeyEvent e){ - System.out.println("keyPressed-"+e); - } - - public void keyReleased(KeyEvent e){ - System.out.println("keyReleased-"+e); - } - - public void keyTyped(KeyEvent e){ - System.out.println("keyTyped-"+e); - } - - private void test(TestState currentState) - throws InterruptedException, InvocationTargetException { - - synchronized (LOCK) { - this.currentState = currentState; System.out.println(this.currentState); List list; - if (currentState.getMultiple()){ + if (currentState.getMultiple()) { list = multiple; - }else{ + } else { list = single; } - Robot r; - try { - r = new Robot(); - } catch(AWTException e) { - throw new RuntimeException(e.getMessage()); - } - r.delay(10); - Point loc = this.getLocationOnScreen(); + Point loc = keyFrame.getLocationOnScreen(); - r.mouseMove(loc.x+10, loc.y+10); - r.mousePress(InputEvent.BUTTON1_MASK); + r.mouseMove(loc.x + 10, loc.y + 10); + r.mousePress(InputEvent.BUTTON1_DOWN_MASK); r.delay(10); - r.mouseRelease(InputEvent.BUTTON1_MASK); + r.mouseRelease(InputEvent.BUTTON1_DOWN_MASK); r.delay(10); list.requestFocusInWindow(); LOCK.wait(ACTION_TIMEOUT); + r.waitForIdle(); + if (KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner() != list){ throw new RuntimeException("Test failed - list isn't focus owner."); } - list.deselect(0); - list.deselect(1); - list.deselect(2); - list.deselect(3); - list.deselect(4); - list.deselect(5); - list.deselect(6); - list.deselect(7); - list.deselect(8); - - int selectIndex = 0; - int visibleIndex = 0; - - if (currentState.getScrollMoved()){ - - if (currentState.getKeyID() == KeyEvent.VK_PAGE_UP || - currentState.getKeyID() == KeyEvent.VK_HOME){ - selectIndex = 8; - visibleIndex = 8; - }else if (currentState.getKeyID() == KeyEvent.VK_PAGE_DOWN || - currentState.getKeyID() == KeyEvent.VK_END){ - selectIndex = 0; - visibleIndex = 0; - } - - }else{ - - if (currentState.getKeyID() == KeyEvent.VK_PAGE_UP || - currentState.getKeyID() == KeyEvent.VK_HOME){ - - if (currentState.getSelectedMoved()){ - selectIndex = 1; - visibleIndex = 0; - }else{ + EventQueue.invokeAndWait(() -> { + list.deselect(0); + list.deselect(1); + list.deselect(2); + list.deselect(3); + list.deselect(4); + list.deselect(5); + list.deselect(6); + list.deselect(7); + list.deselect(8); + + int selectIndex = 0; + int visibleIndex = 0; + + if (currentState.getScrollMoved()) { + if (currentState.getKeyID() == KeyEvent.VK_PAGE_UP || + currentState.getKeyID() == KeyEvent.VK_HOME) { + selectIndex = 8; + visibleIndex = 8; + } else if (currentState.getKeyID() == KeyEvent.VK_PAGE_DOWN || + currentState.getKeyID() == KeyEvent.VK_END) { selectIndex = 0; visibleIndex = 0; } - - }else if (currentState.getKeyID() == KeyEvent.VK_PAGE_DOWN || - currentState.getKeyID() == KeyEvent.VK_END){ - - if (currentState.getSelectedMoved()){ - selectIndex = 7; - visibleIndex = 8; - }else{ - selectIndex = 8; + } else { + if (currentState.getKeyID() == KeyEvent.VK_PAGE_UP || + currentState.getKeyID() == KeyEvent.VK_HOME) { + if (currentState.getSelectedMoved()) { + selectIndex = 1; + } else { + selectIndex = 0; + } + visibleIndex = 0; + } else if (currentState.getKeyID() == KeyEvent.VK_PAGE_DOWN || + currentState.getKeyID() == KeyEvent.VK_END) { + if (currentState.getSelectedMoved()) { + selectIndex = 7; + } else { + selectIndex = 8; + } visibleIndex = 8; } - } - - } - - list.select(selectIndex); - list.makeVisible(visibleIndex); + list.select(selectIndex); + list.makeVisible(visibleIndex); + }); r.delay(10); + r.waitForIdle(); if (currentState.getKeyID() == KeyEvent.VK_HOME || currentState.getKeyID() == KeyEvent.VK_END){ @@ -259,11 +257,9 @@ private void test(TestState currentState) throw new RuntimeException("Test failed."); } - } - private void doTest() - throws InterruptedException, InvocationTargetException { + private void doTest() throws Exception { boolean isWin = false; if (Platform.isWindows()) { @@ -310,9 +306,9 @@ private void doTest() } }// class KeyEventsTest -class TestState{ +class TestState { - private boolean multiple; + private final boolean multiple; // after key pressing selected item moved private final boolean selectedMoved; // after key pressing scroll moved diff --git a/test/jdk/java/awt/List/SetFontTest.java b/test/jdk/java/awt/List/SetFontTest.java new file mode 100644 index 00000000000..d529e00f7b3 --- /dev/null +++ b/test/jdk/java/awt/List/SetFontTest.java @@ -0,0 +1,96 @@ +/* + * Copyright (c) 2005, 2024, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute 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 5010944 6248072 + @summary List's rows overlap one another + @library /java/awt/regtesthelpers + @run main/manual SetFontTest +*/ + +import java.awt.Button; +import java.awt.FlowLayout; +import java.awt.Font; +import java.awt.Frame; +import java.awt.List; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +public class SetFontTest { + + static final String INSTRUCTIONS = """ + 1) Click on the 'Enlarge font' button to enlarge font of the list. + 2) If you see that the rows of the list overlap one another + then the test failed. Otherwise, go to step 3. + 3) Click on the 'Change mode' button to set multiple-selection mode. + 4) If you see that the rows of the list overlap one another + then the test failed. Otherwise, the test passed. + """; + + public static void main(String[] args) throws Exception { + PassFailJFrame.builder() + .title("AWT List Font Test") + .instructions(INSTRUCTIONS) + .rows(10) + .columns(40) + .testUI(SetFontTest::createFontTest) + .build() + .awaitAndCheck(); + } + + static Frame createFontTest() { + + Frame frame = new Frame("List Font Test"); + List list = new List(8, false); + Button button1 = new Button("Enlarge font"); + Button button2 = new Button("Change mode"); + + list.add("111"); + list.add("222"); + list.add("333"); + list.add("444"); + + button1.addActionListener( + new ActionListener(){ + public void actionPerformed(ActionEvent ae) { + list.setFont(new Font("SansSerif", Font.PLAIN, 30)); + list.repaint(); + } + }); + + button2.addActionListener( + new ActionListener(){ + public void actionPerformed(ActionEvent ae){ + list.setMultipleMode(true); + } + }); + + frame.setLayout(new FlowLayout()); + frame.add(list); + frame.add(button1); + frame.add(button2); + frame.setSize(200, 250); + return frame; + } +} diff --git a/test/jdk/java/awt/List/SetFontTest/SetFontTest.html b/test/jdk/java/awt/List/SetFontTest/SetFontTest.html deleted file mode 100644 index 3ac0d99fc51..00000000000 --- a/test/jdk/java/awt/List/SetFontTest/SetFontTest.html +++ /dev/null @@ -1,43 +0,0 @@ - - - - - - SetFontTest - - - -

SetFontTest
Bug ID: 5010944

- -

See the dialog box (usually in upper left corner) for instructions

- - - - diff --git a/test/jdk/java/awt/List/SetFontTest/SetFontTest.java b/test/jdk/java/awt/List/SetFontTest/SetFontTest.java deleted file mode 100644 index 0b68811cd0b..00000000000 --- a/test/jdk/java/awt/List/SetFontTest/SetFontTest.java +++ /dev/null @@ -1,234 +0,0 @@ -/* - * Copyright (c) 2005, 2007, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute 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 5010944 6248072 - @summary List's rows overlap one another - @author Dmitry Cherepanov area=awt-list - @run applet/manual=yesno SetFontTest.html -*/ - -import java.applet.Applet; -import java.awt.*; -import java.awt.event.*; - -public class SetFontTest extends Applet -{ - List list = new List(8, false); - Button button1 = new Button("Enlarge font"); - Button button2 = new Button("Change mode"); - - public void init() - { - list.add("111"); - list.add("222"); - list.add("333"); - list.add("444"); - this.add(list); - - this.add(button1); - this.add(button2); - - button1.addActionListener( - new ActionListener(){ - public void actionPerformed(ActionEvent ae){ - list.setFont( new Font( "SansSerif", Font.PLAIN, 30 ) ); - list.repaint(); - } - }); - - button2.addActionListener( - new ActionListener(){ - public void actionPerformed(ActionEvent ae){ - list.setMultipleMode(true); - } - }); - - this.setLayout (new FlowLayout ()); - - String[] instructions = - { - "1) Click on the 'Enlarge font' button to enlarge font of the list.", - "2) If you see that the rows of the list overlap one another "+ - "then the test failed. Otherwise, goto to the step 3.", - "3) Click on the 'Change mode' button to set multiple-selection mode.", - "4) If you see that the rows of the list overlap one another "+ - "then the test failed. Otherwise, the test passed." - }; - Sysout.createDialogWithInstructions( instructions ); - - }//End init() - - public void start () - { - - setSize (200,200); - setVisible(true); - validate(); - - }// start() -} - -/* Place other classes related to the test after this line */ - - - - - -/**************************************************** - Standard Test Machinery - DO NOT modify anything below -- it's a standard - chunk of code whose purpose is to make user - interaction uniform, and thereby make it simpler - to read and understand someone else's test. - ****************************************************/ - -/** - This is part of the standard test machinery. - It creates a dialog (with the instructions), and is the interface - for sending text messages to the user. - To print the instructions, send an array of strings to Sysout.createDialog - WithInstructions method. Put one line of instructions per array entry. - To display a message for the tester to see, simply call Sysout.println - with the string to be displayed. - This mimics System.out.println but works within the test harness as well - as standalone. - */ - -class Sysout -{ - private static TestDialog dialog; - - public static void createDialogWithInstructions( String[] instructions ) - { - dialog = new TestDialog( new Frame(), "Instructions" ); - dialog.printInstructions( instructions ); - dialog.setVisible(true); - println( "Any messages for the tester will display here." ); - } - - public static void createDialog( ) - { - dialog = new TestDialog( new Frame(), "Instructions" ); - String[] defInstr = { "Instructions will appear here. ", "" } ; - dialog.printInstructions( defInstr ); - dialog.setVisible(true); - println( "Any messages for the tester will display here." ); - } - - - public static void printInstructions( String[] instructions ) - { - dialog.printInstructions( instructions ); - } - - - public static void println( String messageIn ) - { - dialog.displayMessage( messageIn ); - } - -}// Sysout class - -/** - This is part of the standard test machinery. It provides a place for the - test instructions to be displayed, and a place for interactive messages - to the user to be displayed. - To have the test instructions displayed, see Sysout. - To have a message to the user be displayed, see Sysout. - Do not call anything in this dialog directly. - */ -class TestDialog extends Dialog -{ - - TextArea instructionsText; - TextArea messageText; - int maxStringLength = 80; - - //DO NOT call this directly, go through Sysout - public TestDialog( Frame frame, String name ) - { - super( frame, name ); - int scrollBoth = TextArea.SCROLLBARS_BOTH; - instructionsText = new TextArea( "", 15, maxStringLength, scrollBoth ); - add( "North", instructionsText ); - - messageText = new TextArea( "", 5, maxStringLength, scrollBoth ); - add("Center", messageText); - - pack(); - - setVisible(true); - }// TestDialog() - - //DO NOT call this directly, go through Sysout - public void printInstructions( String[] instructions ) - { - //Clear out any current instructions - instructionsText.setText( "" ); - - //Go down array of instruction strings - - String printStr, remainingStr; - for( int i=0; i < instructions.length; i++ ) - { - //chop up each into pieces maxSringLength long - remainingStr = instructions[ i ]; - while( remainingStr.length() > 0 ) - { - //if longer than max then chop off first max chars to print - if( remainingStr.length() >= maxStringLength ) - { - //Try to chop on a word boundary - int posOfSpace = remainingStr. - lastIndexOf( ' ', maxStringLength - 1 ); - - if( posOfSpace <= 0 ) posOfSpace = maxStringLength - 1; - - printStr = remainingStr.substring( 0, posOfSpace + 1 ); - remainingStr = remainingStr.substring( posOfSpace + 1 ); - } - //else just print - else - { - printStr = remainingStr; - remainingStr = ""; - } - - instructionsText.append( printStr + "\n" ); - - }// while - - }// for - - }//printInstructions() - - //DO NOT call this directly, go through Sysout - public void displayMessage( String messageIn ) - { - messageText.append( messageIn + "\n" ); - System.out.println(messageIn); - } - -}// TestDialog class diff --git a/test/jdk/java/awt/MenuBar/SeparatorsNavigation/SeparatorsNavigation.java b/test/jdk/java/awt/MenuBar/SeparatorsNavigation/SeparatorsNavigation.java index 8aca3ab9b05..6bf6069bf04 100644 --- a/test/jdk/java/awt/MenuBar/SeparatorsNavigation/SeparatorsNavigation.java +++ b/test/jdk/java/awt/MenuBar/SeparatorsNavigation/SeparatorsNavigation.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2020, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -29,6 +29,8 @@ import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; /* * @test @@ -51,6 +53,7 @@ public class SeparatorsNavigation { static class Listener implements ActionListener { public void actionPerformed(ActionEvent e) { SeparatorsNavigation.pressed = true; + latch.countDown(); } } @@ -61,7 +64,8 @@ public void actionPerformed(ActionEvent e) { static Menu m3; static MenuItem i31; static Listener l = new Listener(); - static boolean pressed = false; + static volatile boolean pressed = false; + static final CountDownLatch latch = new CountDownLatch(1); public static void main(String args[]) { f = new Frame(); @@ -83,27 +87,23 @@ public static void main(String args[]) { f.setVisible(true); try { Robot r = new Robot(); + r.setAutoDelay(20); r.delay(1000); r.keyPress(KeyEvent.VK_F10); - r.delay(10); r.keyRelease(KeyEvent.VK_F10); r.delay(1000); r.keyPress(KeyEvent.VK_DOWN); - r.delay(10); r.keyRelease(KeyEvent.VK_DOWN); r.delay(1000); r.keyPress(KeyEvent.VK_RIGHT); - r.delay(10); r.keyRelease(KeyEvent.VK_RIGHT); r.delay(1000); r.keyPress(KeyEvent.VK_RIGHT); - r.delay(10); r.keyRelease(KeyEvent.VK_RIGHT); r.delay(1000); r.keyPress(KeyEvent.VK_ENTER); - r.delay(10); r.keyRelease(KeyEvent.VK_ENTER); - r.delay(10000); + latch.await(5, TimeUnit.SECONDS); } catch (Exception ex) { throw new RuntimeException("Execution interrupted by an " + "exception " + ex.getLocalizedMessage()); diff --git a/test/jdk/java/awt/MenuBar/TestNoScreenMenuBar.java b/test/jdk/java/awt/MenuBar/TestNoScreenMenuBar.java index 416e6605896..6080130d7e1 100644 --- a/test/jdk/java/awt/MenuBar/TestNoScreenMenuBar.java +++ b/test/jdk/java/awt/MenuBar/TestNoScreenMenuBar.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -150,7 +150,7 @@ private void closeOtherApplication() { private Process execute() { try { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( TestNoScreenMenuBar.class.getSimpleName(), "mark"); return ProcessTools.startProcess("Other frame", pb); } catch (IOException ex) { diff --git a/test/jdk/java/awt/Paint/ListRepaint.java b/test/jdk/java/awt/Paint/ListRepaint.java index 6a5df92561e..08cf06d63f6 100644 --- a/test/jdk/java/awt/Paint/ListRepaint.java +++ b/test/jdk/java/awt/Paint/ListRepaint.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -34,22 +34,23 @@ */ public final class ListRepaint extends List { - public static void main(final String[] args) { + static ListRepaint listRepaint; + static Frame frame; + + public static void main(final String[] args) throws Exception { for (int i = 0; i < 10; ++i) { - final Frame frame = new Frame(); - frame.setSize(300, 300); - frame.setLocationRelativeTo(null); - ListRepaint list = new ListRepaint(); - list.add("1"); - list.add("2"); - list.add("3"); - list.add("4"); - list.select(0); - frame.add(list); - frame.setVisible(true); - sleep(); - list.test(); - frame.dispose(); + try { + EventQueue.invokeLater(ListRepaint::createAndShowGUI); + sleep(); + EventQueue.invokeAndWait(listRepaint::test); + } finally { + EventQueue.invokeAndWait(() -> { + if (frame != null) { + frame.dispose(); + frame = null; + } + }); + } } } @@ -60,6 +61,22 @@ private static void sleep() { } } + static void createAndShowGUI() { + frame = new Frame(); + frame.setSize(300, 300); + frame.setLocationRelativeTo(null); + + listRepaint = new ListRepaint(); + listRepaint.add("1"); + listRepaint.add("2"); + listRepaint.add("3"); + listRepaint.add("4"); + listRepaint.select(0); + + frame.add(listRepaint); + frame.setVisible(true); + } + @Override public void paint(final Graphics g) { super.paint(g); diff --git a/test/jdk/java/awt/Robot/ModifierRobotKey/ModifierRobotKeyTest.java b/test/jdk/java/awt/Robot/ModifierRobotKey/ModifierRobotKeyTest.java index e06a2adc4e3..a7eb00d362a 100644 --- a/test/jdk/java/awt/Robot/ModifierRobotKey/ModifierRobotKeyTest.java +++ b/test/jdk/java/awt/Robot/ModifierRobotKey/ModifierRobotKeyTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -88,7 +88,7 @@ public ModifierRobotKeyTest() throws Exception { String os = System.getProperty("os.name").toLowerCase(); - if (os.contains("os x")) + if (os.contains("os x") || os.contains("linux")) textKeys[1] = KeyEvent.VK_K; else textKeys[1] = KeyEvent.VK_I; diff --git a/test/jdk/java/awt/Robot/NonEmptyErrorStream.java b/test/jdk/java/awt/Robot/NonEmptyErrorStream.java index 87137ac74ed..5bdada8aa5f 100644 --- a/test/jdk/java/awt/Robot/NonEmptyErrorStream.java +++ b/test/jdk/java/awt/Robot/NonEmptyErrorStream.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2020, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -42,7 +42,7 @@ public final class NonEmptyErrorStream { public static void main(String[] args) throws Exception { if (args.length == 0) { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( NonEmptyErrorStream.class.getSimpleName(),"run"); Process p = pb.start(); OutputAnalyzer output = new OutputAnalyzer(p); diff --git a/test/jdk/java/awt/TextArea/TextAreaCaretVisibilityTest/bug7129742.java b/test/jdk/java/awt/TextArea/TextAreaCaretVisibilityTest/bug7129742.java index 61c9ba6c22f..c052468a8b9 100644 --- a/test/jdk/java/awt/TextArea/TextAreaCaretVisibilityTest/bug7129742.java +++ b/test/jdk/java/awt/TextArea/TextAreaCaretVisibilityTest/bug7129742.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -98,6 +98,7 @@ public void run() { } }); robot.waitForIdle(); + robot.delay(500); SwingUtilities.invokeAndWait(new Runnable() { @Override diff --git a/test/jdk/java/awt/Toolkit/DesktopProperties/rfe4758438.sh b/test/jdk/java/awt/Toolkit/DesktopProperties/rfe4758438.sh index ce5628ac9d4..e1c00e9adc0 100644 --- a/test/jdk/java/awt/Toolkit/DesktopProperties/rfe4758438.sh +++ b/test/jdk/java/awt/Toolkit/DesktopProperties/rfe4758438.sh @@ -28,20 +28,6 @@ OS=`uname` case "$OS" in Linux* ) - GNOMESID=`pgrep gnome-session | head -n1` - - printf "\n/* gnome-session environ\n" - cat "/proc/$GNOMESID/environ" | tr '\0' '\n' - printf "\n*/\n\n" - - DBUS_SESSION_BUS_ADDRESS=`grep -z DBUS_SESSION_BUS_ADDRESS /proc/$GNOMESID/environ | cut -d= -f2-` - export DBUS_SESSION_BUS_ADDRESS - - DISPLAY=`grep -z DISPLAY /proc/$GNOMESID/environ | cut -d= -f2-` - export DISPLAY - - XDG_CURRENT_DESKTOP=`grep -z XDG_CURRENT_DESKTOP /proc/$GNOMESID/environ | cut -d= -f2-` - export XDG_CURRENT_DESKTOP ;; * ) echo "This Feature is not to be tested on $OS" diff --git a/test/jdk/java/awt/Toolkit/ScreenInsetsDPIVariation/ScreenInsetsDPIVariation.java b/test/jdk/java/awt/Toolkit/ScreenInsetsDPIVariation/ScreenInsetsDPIVariation.java index e089ef26ca9..244f8bb6bd7 100644 --- a/test/jdk/java/awt/Toolkit/ScreenInsetsDPIVariation/ScreenInsetsDPIVariation.java +++ b/test/jdk/java/awt/Toolkit/ScreenInsetsDPIVariation/ScreenInsetsDPIVariation.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2020, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -102,7 +102,7 @@ public static int clipRound(double coordinate) { private static void runProcess(String dpi, int screen, Insets insets) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-Dsun.java2d.uiScale=" + dpi, ScreenInsetsDPIVariation.class.getSimpleName(), String.valueOf(screen), String.valueOf(insets.left), diff --git a/test/jdk/java/awt/TrayIcon/ActionEventTest/ActionEventTest.java b/test/jdk/java/awt/TrayIcon/ActionEventTest/ActionEventTest.java index 5161fa3cc9b..23920e89c50 100644 --- a/test/jdk/java/awt/TrayIcon/ActionEventTest/ActionEventTest.java +++ b/test/jdk/java/awt/TrayIcon/ActionEventTest/ActionEventTest.java @@ -79,7 +79,10 @@ public static void main(String[] args) throws Exception { public ActionEventTest() throws Exception { robot = new Robot(); + robot.setAutoDelay(25); EventQueue.invokeAndWait(this::initializeGUI); + robot.waitForIdle(); + robot.delay(500); } private void initializeGUI() { @@ -117,10 +120,6 @@ public void clear() { } void doTest() throws Exception { - robot.keyPress(KeyEvent.VK_ALT); - robot.keyPress(KeyEvent.VK_SHIFT); - robot.keyPress(KeyEvent.VK_CONTROL); - Point iconPosition = SystemTrayIconHelper.getTrayIconLocation(icon); if (iconPosition == null) { throw new RuntimeException("Unable to find the icon location!"); @@ -129,6 +128,10 @@ void doTest() throws Exception { robot.mouseMove(iconPosition.x, iconPosition.y); robot.waitForIdle(); + robot.keyPress(KeyEvent.VK_ALT); + robot.keyPress(KeyEvent.VK_SHIFT); + robot.keyPress(KeyEvent.VK_CONTROL); + robot.mousePress(InputEvent.BUTTON1_DOWN_MASK); robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK); robot.delay(100); diff --git a/test/jdk/java/awt/TrayIcon/TrayIconPopup/TrayIconPopupTest.java b/test/jdk/java/awt/TrayIcon/TrayIconPopup/TrayIconPopupTest.java index 9d6189722c3..7b487364f96 100644 --- a/test/jdk/java/awt/TrayIcon/TrayIconPopup/TrayIconPopupTest.java +++ b/test/jdk/java/awt/TrayIcon/TrayIconPopup/TrayIconPopupTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 2024, Oracle and/or its affiliates. All rights reserved. * 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 @@ public class TrayIconPopupTest { boolean actionPerformed = false; Object actionLock = new Object(); - static final int ATTEMPTS = 50; + static final int ATTEMPTS = 10; PopupMenu popup; Dialog window; diff --git a/test/jdk/java/awt/Window/MainKeyWindowTest/TestMainKeyWindow.java b/test/jdk/java/awt/Window/MainKeyWindowTest/TestMainKeyWindow.java index 958033e04b1..09ad948ec86 100644 --- a/test/jdk/java/awt/Window/MainKeyWindowTest/TestMainKeyWindow.java +++ b/test/jdk/java/awt/Window/MainKeyWindowTest/TestMainKeyWindow.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -151,7 +151,7 @@ private void performTest(Object windowIdentification, boolean selectColorPanel) private Process execute() { try { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( TestMainKeyWindow.class.getSimpleName(), "mark"); return ProcessTools.startProcess("Other frame", pb); } catch (IOException ex) { diff --git a/test/jdk/java/awt/Window/MinimumSizeDPIVariation/MinimumSizeDPIVariation.java b/test/jdk/java/awt/Window/MinimumSizeDPIVariation/MinimumSizeDPIVariation.java index f00564ff934..534f25c4cbb 100644 --- a/test/jdk/java/awt/Window/MinimumSizeDPIVariation/MinimumSizeDPIVariation.java +++ b/test/jdk/java/awt/Window/MinimumSizeDPIVariation/MinimumSizeDPIVariation.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2020, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -110,7 +110,7 @@ private static void checkAllDPI(String comp, int w, int h) private static void runProcess(String dpi, String comp, int w, int h) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-Dsun.java2d.uiScale=" + dpi, MinimumSizeDPIVariation.class.getSimpleName(), comp, String.valueOf(w), String.valueOf(h), dpi); diff --git a/test/jdk/java/awt/Window/SetWindowLocationByPlatformTest/SetWindowLocationByPlatformTest.java b/test/jdk/java/awt/Window/SetWindowLocationByPlatformTest/SetWindowLocationByPlatformTest.java index 06c2a505cd4..141e9f45df0 100644 --- a/test/jdk/java/awt/Window/SetWindowLocationByPlatformTest/SetWindowLocationByPlatformTest.java +++ b/test/jdk/java/awt/Window/SetWindowLocationByPlatformTest/SetWindowLocationByPlatformTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -51,6 +51,7 @@ public static void main(String[] args) { frame2.setLocationByPlatform(true); frame2.setVisible(true); Util.waitForIdle(r); + r.delay(500); Point point1 = frame1.getLocationOnScreen(); Point point2 = frame2.getLocationOnScreen(); diff --git a/test/jdk/java/awt/color/ICC_ColorSpace/MTTransformReplacedProfile.java b/test/jdk/java/awt/color/ICC_ColorSpace/MTTransformReplacedProfile.java index d9e10785cff..0fad3665b25 100644 --- a/test/jdk/java/awt/color/ICC_ColorSpace/MTTransformReplacedProfile.java +++ b/test/jdk/java/awt/color/ICC_ColorSpace/MTTransformReplacedProfile.java @@ -1,6 +1,6 @@ /* * Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. - * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2021, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it diff --git a/test/jdk/java/awt/event/KeyEvent/FunctionKeyTest.java b/test/jdk/java/awt/event/KeyEvent/FunctionKeyTest.java index 02e7a890d83..78043cb5abd 100644 --- a/test/jdk/java/awt/event/KeyEvent/FunctionKeyTest.java +++ b/test/jdk/java/awt/event/KeyEvent/FunctionKeyTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2024, Oracle and/or its affiliates. All rights reserved. * 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,18 @@ import java.awt.Robot; import java.awt.TextArea; import java.awt.event.KeyEvent; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.CyclicBarrier; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicReference; + +import static java.awt.Event.KEY_ACTION; +import static java.awt.Event.KEY_ACTION_RELEASE; +import static java.util.concurrent.TimeUnit.SECONDS; /* * @test @@ -39,35 +51,38 @@ * @key headful */ -public class FunctionKeyTest { - private static FunctionKeyTester frame; +public final class FunctionKeyTest { + private static Frame frame; private static Robot robot; - static volatile boolean keyPressReceived; - static volatile boolean keyReleaseReceived; + private static final CyclicBarrier keyPress = new CyclicBarrier(2); + private static final CyclicBarrier keyRelease = new CyclicBarrier(2); - static final StringBuilder failures = new StringBuilder(); + private static final CountDownLatch frameActivated = new CountDownLatch(1); - private static void testKey(int keyCode, String keyText) { - keyPressReceived = false; - keyReleaseReceived = false; + private static final List failures = new ArrayList<>(4); + private static final AtomicReference edtException = new AtomicReference<>(); + private static void testKey(int keyCode, String keyText) throws Exception { robot.keyPress(keyCode); - - if (!keyPressReceived) { - failures.append(keyText).append(" key press is not received\n"); + try { + keyPress.await(2, SECONDS); + } catch (TimeoutException e) { + keyPress.reset(); + failures.add(new Error(keyText + " key press is not received", e)); } robot.keyRelease(keyCode); - - if (!keyReleaseReceived) { - failures.append(keyText).append(" key release is not received\n"); + try { + keyRelease.await(2, SECONDS); + } catch (TimeoutException e) { + keyRelease.reset(); + failures.add(new Error(keyText + " key release is not received", e)); } } public static void main(String[] args) throws Exception { robot = new Robot(); - robot.setAutoWaitForIdle(true); robot.setAutoDelay(150); try { @@ -75,11 +90,20 @@ public static void main(String[] args) throws Exception { frame = new FunctionKeyTester(); frame.setSize(200, 200); frame.setLocationRelativeTo(null); + frame.addWindowListener(new WindowAdapter() { + @Override + public void windowActivated(WindowEvent e) { + System.out.println("frame.windowActivated"); + frameActivated.countDown(); + } + }); frame.setVisible(true); }); - robot.waitForIdle(); - robot.delay(1000); + if (!frameActivated.await(2, SECONDS)) { + throw new Error("Frame wasn't activated"); + } + robot.delay(100); testKey(KeyEvent.VK_F11, "F11"); testKey(KeyEvent.VK_F12, "F12"); @@ -91,46 +115,69 @@ public static void main(String[] args) throws Exception { }); } - if (failures.isEmpty()) { - System.out.println("Passed"); - } else { - throw new RuntimeException(failures.toString()); + if (!failures.isEmpty()) { + System.err.println("Failures detected:"); + failures.forEach(System.err::println); + if (edtException.get() != null) { + System.err.println("\nException on EDT:"); + edtException.get().printStackTrace(); + } + System.err.println(); + throw new RuntimeException("Test failed: " + failures.get(0).getMessage(), + failures.get(0)); } - } -} -class FunctionKeyTester extends Frame { - Label l = new Label ("NULL"); - Button b = new Button(); - TextArea log = new TextArea(); - - FunctionKeyTester() { - super("Function Key Test"); - this.setLayout(new BorderLayout()); - this.add(BorderLayout.NORTH, l); - this.add(BorderLayout.SOUTH, b); - this.add(BorderLayout.CENTER, log); - log.setFocusable(false); - log.setEditable(false); - l.setBackground(Color.red); - setSize(200, 200); + if (edtException.get() != null) { + throw new RuntimeException("Test failed because of exception on EDT", + edtException.get()); + } } - public boolean handleEvent(Event e) { - String message = "e.id=" + e.id + "\n"; - System.out.print(message); - log.append(message); - - switch (e.id) { - case 403 -> FunctionKeyTest.keyPressReceived = true; - case 404 -> FunctionKeyTest.keyReleaseReceived = true; + private static final class FunctionKeyTester extends Frame { + Label l = new Label ("NULL"); + Button b = new Button("button"); + TextArea log = new TextArea(); + + FunctionKeyTester() { + super("Function Key Test"); + this.setLayout(new BorderLayout()); + this.add(BorderLayout.NORTH, l); + this.add(BorderLayout.SOUTH, b); + this.add(BorderLayout.CENTER, log); + log.setFocusable(false); + log.setEditable(false); + l.setBackground(Color.red); + setSize(200, 200); } - return super.handleEvent(e); - } + @Override + @SuppressWarnings("deprecation") + public boolean handleEvent(Event e) { + String message = "e.id=" + e.id + "\n"; + System.out.print(message); + log.append(message); + + try { + switch (e.id) { + case KEY_ACTION + -> keyPress.await(); + case KEY_ACTION_RELEASE + -> keyRelease.await(); + } + } catch (Exception ex) { + if (!edtException.compareAndSet(null, ex)) { + edtException.get().addSuppressed(ex); + } + } - public boolean keyDown(Event e, int key) { - l.setText("e.key=" + Integer.valueOf(e.key).toString()); - return false; + return super.handleEvent(e); + } + + @Override + @SuppressWarnings("deprecation") + public boolean keyDown(Event e, int key) { + l.setText("e.key=" + e.key); + return false; + } } } diff --git a/test/jdk/java/awt/event/KeyEvent/KeyTyped/Numpad1KeyTyped.java b/test/jdk/java/awt/event/KeyEvent/KeyTyped/Numpad1KeyTyped.java new file mode 100644 index 00000000000..a944be85581 --- /dev/null +++ b/test/jdk/java/awt/event/KeyEvent/KeyTyped/Numpad1KeyTyped.java @@ -0,0 +1,178 @@ +/* + * Copyright (c) 2002, 2024, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.awt.Frame; +import java.awt.Robot; +import java.awt.TextField; +import java.awt.Toolkit; +import java.awt.event.FocusAdapter; +import java.awt.event.FocusEvent; +import java.awt.event.KeyEvent; +import java.awt.event.KeyListener; +import java.util.concurrent.CountDownLatch; + +import jdk.test.lib.Platform; + +import static java.util.concurrent.TimeUnit.SECONDS; + +/* + * @test + * @bug 4724007 + * @key headful + * @summary Tests that KeyTyped events are fired for the Numpad1 key + * @library /test/lib + * @build jdk.test.lib.Platform + * @run main Numpad1KeyTyped + */ +public final class Numpad1KeyTyped extends FocusAdapter implements KeyListener { + + private static final String ORIGINAL = "0123456789"; + private static final String EXPECTED = "10123456789"; + + private final CountDownLatch typedNum1 = new CountDownLatch(1); + private final CountDownLatch focusGained = new CountDownLatch(1); + + public static void main(String[] args) throws Exception { + Numpad1KeyTyped test = new Numpad1KeyTyped(); + test.start(); + } + + private void start() throws Exception { + Toolkit toolkit = Toolkit.getDefaultToolkit(); + Boolean oldState = null; + + Robot robot = new Robot(); + robot.setAutoDelay(100); + + Frame frame = new Frame("Numpad1KeyTyped"); + TextField tf = new TextField(ORIGINAL, 20); + frame.add(tf); + tf.addKeyListener(this); + + tf.addFocusListener(this); + + frame.setSize(300, 100); + frame.setLocationRelativeTo(null); + frame.setVisible(true); + tf.requestFocusInWindow(); + + if (!focusGained.await(2, SECONDS)) { + throw new RuntimeException("TextField didn't receive focus"); + } + robot.waitForIdle(); + + try { + // Move cursor to start of TextField + robot.keyPress(KeyEvent.VK_HOME); + robot.keyRelease(KeyEvent.VK_HOME); + robot.waitForIdle(); + + if (Platform.isLinux()) { + // Press but don't release NumLock + robot.keyPress(KeyEvent.VK_NUM_LOCK); + } + if (Platform.isWindows()) { + oldState = toolkit.getLockingKeyState(KeyEvent.VK_NUM_LOCK); + toolkit.setLockingKeyState(KeyEvent.VK_NUM_LOCK, true); + } + + // Press and release Numpad-1 + robot.keyPress(KeyEvent.VK_NUMPAD1); + robot.keyRelease(KeyEvent.VK_NUMPAD1); + + if (!typedNum1.await(2, SECONDS)) { + throw new RuntimeException("TextField didn't receive keyTyped('1') - too slow"); + } + + final String text = tf.getText(); + if (!text.equals(EXPECTED)) { + throw new RuntimeException("Test FAILED: wrong string '" + + text + "' vs " + + "expected '" + EXPECTED + "'"); + } + System.out.println("Test PASSED"); + } finally { + if (Platform.isLinux()) { + // "release" + "press and release" NumLock to disable numlock + robot.keyRelease(KeyEvent.VK_NUM_LOCK); + robot.keyPress(KeyEvent.VK_NUM_LOCK); + robot.keyRelease(KeyEvent.VK_NUM_LOCK); + } + if (oldState != null) { + toolkit.setLockingKeyState(KeyEvent.VK_NUM_LOCK, oldState); + } + + frame.dispose(); + } + } + + @Override + public void focusGained(FocusEvent e) { + System.out.println("tf.focusGained"); + focusGained.countDown(); + } + + @Override + public void keyPressed(KeyEvent evt) { + printKey(evt); + } + + @Override + public void keyTyped(KeyEvent evt) { + printKey(evt); + + int keychar = evt.getKeyChar(); + if (keychar == '1') { + typedNum1.countDown(); + } + } + + @Override + public void keyReleased(KeyEvent evt) { + printKey(evt); + System.out.println(); + } + + private static void printKey(KeyEvent evt) { + int id = evt.getID(); + if (id != KeyEvent.KEY_TYPED + && id != KeyEvent.KEY_PRESSED + && id != KeyEvent.KEY_RELEASED) { + + System.out.println("Other Event"); + return; + } + + System.out.println("params= " + evt.paramString() + " \n" + + "KeyChar: " + evt.getKeyChar() + " = " + (int) evt.getKeyChar() + + " KeyCode: " + evt.getKeyCode() + + " Modifiers: " + evt.getModifiersEx()); + + if (evt.isActionKey()) { + System.out.println(" Action Key"); + } + + System.out.println("keyText= " + KeyEvent.getKeyText(evt.getKeyCode()) + "\n"); + } + +} diff --git a/test/jdk/java/awt/print/PageFormat/CustomPaper.java b/test/jdk/java/awt/print/PageFormat/CustomPaper.java index 1976a20c01f..7af689176d8 100644 --- a/test/jdk/java/awt/print/PageFormat/CustomPaper.java +++ b/test/jdk/java/awt/print/PageFormat/CustomPaper.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,224 +21,162 @@ * questions. */ +import java.awt.BasicStroke; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.geom.Rectangle2D; +import java.awt.print.PageFormat; +import java.awt.print.Pageable; +import java.awt.print.Paper; +import java.awt.print.Printable; +import java.awt.print.PrinterException; +import java.awt.print.PrinterJob; + +import jtreg.SkippedException; + /* * @test * @bug 4355514 + * @key printer + * @summary Prints a rectangle to show the imageable area of a + * 12in x 14in custom paper size. + * @library /java/awt/regtesthelpers + * @library /test/lib + * @build PassFailJFrame + * @build jtreg.SkippedException + * @run main/manual CustomPaper 4355514 + */ + +/* + * @test * @bug 4385157 * @key printer * @summary Prints a rectangle to show the imageable area of a * 12in x 14in custom paper size. - * @run main/manual CustomPaper + * @library /java/awt/regtesthelpers + * @library /test/lib + * @build PassFailJFrame + * @build jtreg.SkippedException + * @run main/manual CustomPaper 4385157 */ +public class CustomPaper implements Pageable, Printable { -import java.awt.*; -import java.awt.print.*; -import java.awt.geom.*; - -public class CustomPaper implements Pageable, Printable{ - - private static double PIXELS_PER_INCH = 72.0; - - private PrinterJob printerJob; - private PageFormat pageFormat; - - CustomPaper(){ - printerJob = PrinterJob.getPrinterJob(); - createPageFormat(); - } - - private void createPageFormat(){ - pageFormat = new PageFormat(); - Paper p = new Paper(); - double width = 12.0*PIXELS_PER_INCH; - double height = 14.0*PIXELS_PER_INCH; - double ix = PIXELS_PER_INCH; - double iy = PIXELS_PER_INCH; - double iwidth = width - 2.0*PIXELS_PER_INCH; - double iheight = height - 2.0*PIXELS_PER_INCH; - p.setSize(width, height); - p.setImageableArea(ix, iy, iwidth, iheight); - pageFormat.setPaper(p); - } - - public Printable getPrintable(int index){ - return this; - } - - public PageFormat getPageFormat(int index){ - return pageFormat; - } - - public int getNumberOfPages(){ - return 1; - } - - public void print(){ - if(printerJob.printDialog()) - { - try{ - printerJob.setPageable(this); - printerJob.print(); - }catch(Exception e){e.printStackTrace();} - } + private static final double PIXELS_PER_INCH = 72.0; + + private final PrinterJob printerJob; + private PageFormat pageFormat; - } - - public int print(Graphics g, PageFormat pf, int pageIndex){ - if(pageIndex == 0){ - Graphics2D g2 = (Graphics2D)g; - Rectangle2D r = new Rectangle2D.Double(pf.getImageableX(), - pf.getImageableY(), - pf.getImageableWidth(), - pf.getImageableHeight()); - g2.setStroke(new BasicStroke(3.0f)); - g2.draw(r); - return PAGE_EXISTS; - }else{ - return NO_SUCH_PAGE; + CustomPaper() { + printerJob = PrinterJob.getPrinterJob(); + createPageFormat(); } - } - - public static void main(String[] args){ - - String[] instructions = - { - "You must have a printer that supports custom paper size of ", - "at least 12 x 14 inches to perform this test. It requires", - "user interaction and you must have a 12 x 14 inch paper available.", - " ", - "To test bug ID 4385157, click OK on print dialog box to print.", - " ", - "To test bug ID 4355514, select the printer in the Print Setup dialog and add a ", - "custom paper size under Printer properties' Paper selection menu. ", - "Set the dimension to width=12 inches and height=14 inches.", - "Select this custom paper size before proceeding to print.", - " ", - "Visual inspection of the one-page printout is needed. A passing", - "test will print a rectangle of the imageable area which is approximately", - "10 x 12 inches.", - }; - Sysout.createDialog( ); - Sysout.printInstructions( instructions ); - CustomPaper pt = new CustomPaper(); - pt.print(); - //System.exit (0); - } + private void createPageFormat() { + pageFormat = new PageFormat(); + Paper p = new Paper(); + double width = 12.0 * PIXELS_PER_INCH; + double height = 14.0 * PIXELS_PER_INCH; + double iwidth = width - 2.0 * PIXELS_PER_INCH; + double iheight = height - 2.0 * PIXELS_PER_INCH; + p.setSize(width, height); + p.setImageableArea(PIXELS_PER_INCH, PIXELS_PER_INCH, iwidth, iheight); + pageFormat.setPaper(p); + } -} + @Override + public Printable getPrintable(int index) { + return this; + } + @Override + public PageFormat getPageFormat(int index) { + return pageFormat; + } -class Sysout { - private static TestDialog dialog; + @Override + public int getNumberOfPages() { + return 1; + } - public static void createDialogWithInstructions( String[] instructions ) - { - dialog = new TestDialog( new Frame(), "Instructions" ); - dialog.printInstructions( instructions ); - dialog.show(); - println( "Any messages for the tester will display here." ); + private void print() throws PrinterException { + if (printerJob.printDialog()) { + printerJob.setPageable(this); + printerJob.print(); + } else { + PassFailJFrame.forceFail("Printing canceled by user"); + } } - public static void createDialog( ) - { - dialog = new TestDialog( new Frame(), "Instructions" ); - String[] defInstr = { "Instructions will appear here. ", "" } ; - dialog.printInstructions( defInstr ); - dialog.show(); - println( "Any messages for the tester will display here." ); + @Override + public int print(Graphics g, PageFormat pf, int pageIndex) { + if (pageIndex == 0) { + Graphics2D g2 = (Graphics2D) g; + Rectangle2D r = new Rectangle2D.Double(pf.getImageableX(), + pf.getImageableY(), + pf.getImageableWidth(), + pf.getImageableHeight()); + g2.setStroke(new BasicStroke(3.0f)); + g2.draw(r); + return PAGE_EXISTS; + } else { + return NO_SUCH_PAGE; + } } + private static final String TOP = """ + You must have a printer that supports custom paper size of + at least 12 x 14 inches to perform this test. It requires + user interaction and you must have a 12 x 14 inch paper available. - public static void printInstructions( String[] instructions ) - { - dialog.printInstructions( instructions ); - } + """; + private static final String BOTTOM = """ - public static void println( String messageIn ) - { - dialog.displayMessage( messageIn ); - } + Visual inspection of the one-page printout is needed. A passing + test will print a rectangle of the imageable area which is + approximately 10 x 12 inches. + """; -}// Sysout class - -/** - This is part of the standard test machinery. It provides a place for the - test instructions to be displayed, and a place for interactive messages - to the user to be displayed. - To have the test instructions displayed, see Sysout. - To have a message to the user be displayed, see Sysout. - Do not call anything in this dialog directly. - */ -class TestDialog extends Dialog { - - TextArea instructionsText; - TextArea messageText; - int maxStringLength = 80; - - //DO NOT call this directly, go through Sysout - public TestDialog( Frame frame, String name ) - { - super( frame, name ); - int scrollBoth = TextArea.SCROLLBARS_BOTH; - instructionsText = new TextArea( "", 15, maxStringLength, scrollBoth ); - add( "North", instructionsText ); - - messageText = new TextArea( "", 5, maxStringLength, scrollBoth ); - add("Center", messageText); - - pack(); - - show(); - }// TestDialog() - - //DO NOT call this directly, go through Sysout - public void printInstructions( String[] instructions ) - { - //Clear out any current instructions - instructionsText.setText( "" ); - - //Go down array of instruction strings - - String printStr, remainingStr; - for( int i=0; i < instructions.length; i++ ) - { - //chop up each into pieces maxSringLength long - remainingStr = instructions[ i ]; - while( remainingStr.length() > 0 ) - { - //if longer than max then chop off first max chars to print - if( remainingStr.length() >= maxStringLength ) - { - //Try to chop on a word boundary - int posOfSpace = remainingStr. - lastIndexOf( ' ', maxStringLength - 1 ); - - if( posOfSpace <= 0 ) posOfSpace = maxStringLength - 1; - - printStr = remainingStr.substring( 0, posOfSpace + 1 ); - remainingStr = remainingStr.substring( posOfSpace + 1 ); - } - //else just print - else - { - printStr = remainingStr; - remainingStr = ""; - } - - instructionsText.append( printStr + "\n" ); - - }// while - - }// for - - }//printInstructions() - - //DO NOT call this directly, go through Sysout - public void displayMessage( String messageIn ) - { - messageText.append( messageIn + "\n" ); - } + private static final String INSTRUCTIONS_4355514 = """ + Select the printer in the Print Setup dialog and add a custom + paper size under 'Printer properties' Paper selection menu. + Set the dimension to width=12 inches and height=14 inches. + Select this custom paper size before proceeding to print. + """; + + private static final String INSTRUCTIONS_4385157 = """ + Click OK on print dialog box to print. + """; + + public static void main(String[] args) throws Exception { + String instructions; + + if (PrinterJob.lookupPrintServices().length == 0) { + throw new SkippedException("Printer not configured or available." + + " Test cannot continue."); + } - }// TestDialog class + if (args.length != 1) { + throw new RuntimeException("Select a test by passing 4355514 or 4385157"); + } + + instructions = switch (args[0]) { + case "4355514" -> TOP + INSTRUCTIONS_4355514 + BOTTOM; + case "4385157" -> TOP + INSTRUCTIONS_4385157 + BOTTOM; + default -> throw new RuntimeException("Unknown bugid " + args[0] + "." + + "Valid values: 4355514 or 4385157"); + }; + + PassFailJFrame passFailJFrame = new PassFailJFrame.Builder() + .title("CustomPaper Test Instructions") + .instructions(instructions) + .testTimeOut(5) + .rows((int) instructions.lines().count() + 1) + .columns(45) + .build(); + + CustomPaper pt = new CustomPaper(); + pt.print(); + passFailJFrame.awaitAndCheck(); + } +} diff --git a/test/jdk/java/awt/print/PrinterJob/PageDlgPrnButton.java b/test/jdk/java/awt/print/PrinterJob/PageDlgPrnButton.java index 6c000dc7f5f..2ede9c53dc4 100644 --- a/test/jdk/java/awt/print/PrinterJob/PageDlgPrnButton.java +++ b/test/jdk/java/awt/print/PrinterJob/PageDlgPrnButton.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,209 +21,93 @@ * questions. */ -/** - * @test - * @bug 4956397 - * @key printer - * @run main/manual PageDlgPrnButton - */ - -import java.awt.print.PrinterJob; -import java.awt.print.PageFormat; -import java.awt.print.Printable; -import java.awt.print.PrinterException; - import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Rectangle; -import java.awt.* ; - -public class PageDlgPrnButton implements Printable -{ - public static void main ( String args[] ) { +import java.awt.print.PageFormat; +import java.awt.print.Printable; +import java.awt.print.PrinterException; +import java.awt.print.PrinterJob; - String[] instructions = - {"For non-windows OS, this test PASSes.", - "You must have at least 2 printers available to perform this test.", - "This test brings up a native Windows page dialog.", - "Click on the Printer... button and change the selected printer. ", - "Test passes if the printout comes from the new selected printer.", - }; +import jtreg.SkippedException; - Sysout.createDialog( ); - Sysout.printInstructions( instructions ); +/* + * @test + * @bug 4956397 + * @key printer + * @requires os.family=="windows" + * @library /test/lib /java/awt/regtesthelpers + * @build PassFailJFrame jtreg.SkippedException + * @run main/manual PageDlgPrnButton + */ +public class PageDlgPrnButton implements Printable { + private static final String INSTRUCTIONS = + "This test brings up a native Windows page dialog.\n" + + "Click on the Printer... button and change the selected printer. \n" + + "Test passes if the printout comes from the new selected printer."; + + public static void main(String[] args) throws Exception { + final int serviceCount = PrinterJob.lookupPrintServices().length; + if (serviceCount == 0) { + throw new RuntimeException("Printer not configured or available."); + } + if (serviceCount < 2) { + throw new SkippedException("The test requires at least 2 printers."); + } - PageDlgPrnButton pdpb = new PageDlgPrnButton() ; - } + PassFailJFrame passFailJFrame = PassFailJFrame.builder() + .instructions(INSTRUCTIONS) + .rows((int) INSTRUCTIONS.lines().count() + 1) + .columns(45) + .build(); - public PageDlgPrnButton() - { - try - { - pageDialogExample(); - } - catch(Exception e) - {e.printStackTrace(System.err);} + pageDialogExample(); + passFailJFrame.awaitAndCheck(); } - // This example just displays the page dialog - you cannot change // the printer (press the "Printer..." button and choose one if you like). - public void pageDialogExample() throws PrinterException - { + public static void pageDialogExample() throws PrinterException { PrinterJob job = PrinterJob.getPrinterJob(); PageFormat originalPageFormat = job.defaultPage(); PageFormat pageFormat = job.pageDialog(originalPageFormat); - if(originalPageFormat == pageFormat) return; - - job.setPrintable(this,pageFormat); - job.print(); + job.setPrintable(new PageDlgPrnButton(), pageFormat); + if (job.printDialog()) { + job.print(); + } } - - - public int print(Graphics g, PageFormat pageFormat, int pageIndex) - { + @Override + public int print(Graphics g, PageFormat pageFormat, int pageIndex) { final int boxWidth = 100; final int boxHeight = 100; - final Rectangle rect = new Rectangle(0,0,boxWidth,boxHeight); + final Rectangle rect = new Rectangle(0, 0, boxWidth, boxHeight); final double pageH = pageFormat.getImageableHeight(); final double pageW = pageFormat.getImageableWidth(); + final Graphics2D g2d = (Graphics2D) g; - if (pageIndex > 0) return (NO_SUCH_PAGE); - - final Graphics2D g2d = (Graphics2D)g; + if (pageIndex > 0) { + return NO_SUCH_PAGE; + } // Move the (x,y) origin to account for the left-hand and top margins g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY()); // Draw the page bounding box - g2d.drawRect(0,0,(int)pageW,(int)pageH); + g2d.drawRect(0, 0, (int) pageW, (int) pageH); // Select the smaller scaling factor so that the figure // fits on the page in both dimensions - final double scale = Math.min( (pageW/boxWidth), (pageH/boxHeight) ); + final double scale = Math.min((pageW / boxWidth), (pageH / boxHeight)); - if(scale < 1.0) g2d.scale(scale, scale); + if (scale < 1.0) { + g2d.scale(scale, scale); + } // Paint the scaled component on the printer g2d.fillRect(rect.x, rect.y, rect.width, rect.height); - return(PAGE_EXISTS); + return PAGE_EXISTS; } } - -class Sysout { - private static TestDialog dialog; - - public static void createDialogWithInstructions( String[] instructions ) - { - dialog = new TestDialog( new Frame(), "Instructions" ); - dialog.printInstructions( instructions ); - dialog.show(); - println( "Any messages for the tester will display here." ); - } - - public static void createDialog( ) - { - dialog = new TestDialog( new Frame(), "Instructions" ); - String[] defInstr = { "Instructions will appear here. ", "" } ; - dialog.printInstructions( defInstr ); - dialog.show(); - println( "Any messages for the tester will display here." ); - } - - - public static void printInstructions( String[] instructions ) - { - dialog.printInstructions( instructions ); - } - - - public static void println( String messageIn ) - { - dialog.displayMessage( messageIn ); - } - -}// Sysout class - -/** - This is part of the standard test machinery. It provides a place for the - test instructions to be displayed, and a place for interactive messages - to the user to be displayed. - To have the test instructions displayed, see Sysout. - To have a message to the user be displayed, see Sysout. - Do not call anything in this dialog directly. - */ -class TestDialog extends Dialog { - - TextArea instructionsText; - TextArea messageText; - int maxStringLength = 80; - - //DO NOT call this directly, go through Sysout - public TestDialog( Frame frame, String name ) - { - super( frame, name ); - int scrollBoth = TextArea.SCROLLBARS_BOTH; - instructionsText = new TextArea( "", 15, maxStringLength, scrollBoth ); - add( "North", instructionsText ); - - messageText = new TextArea( "", 5, maxStringLength, scrollBoth ); - add("Center", messageText); - - pack(); - - show(); - }// TestDialog() - - //DO NOT call this directly, go through Sysout - public void printInstructions( String[] instructions ) - { - //Clear out any current instructions - instructionsText.setText( "" ); - - //Go down array of instruction strings - - String printStr, remainingStr; - for( int i=0; i < instructions.length; i++ ) - { - //chop up each into pieces maxSringLength long - remainingStr = instructions[ i ]; - while( remainingStr.length() > 0 ) - { - //if longer than max then chop off first max chars to print - if( remainingStr.length() >= maxStringLength ) - { - //Try to chop on a word boundary - int posOfSpace = remainingStr. - lastIndexOf( ' ', maxStringLength - 1 ); - - if( posOfSpace <= 0 ) posOfSpace = maxStringLength - 1; - - printStr = remainingStr.substring( 0, posOfSpace + 1 ); - remainingStr = remainingStr.substring( posOfSpace + 1 ); - } - //else just print - else - { - printStr = remainingStr; - remainingStr = ""; - } - - instructionsText.append( printStr + "\n" ); - - }// while - - }// for - - }//printInstructions() - - //DO NOT call this directly, go through Sysout - public void displayMessage( String messageIn ) - { - messageText.append( messageIn + "\n" ); - } - - }// TestDialog class diff --git a/test/jdk/java/awt/print/PrinterJob/PrintCompoundString.java b/test/jdk/java/awt/print/PrinterJob/PrintCompoundString.java index 95cebd99765..14443d76ae8 100644 --- a/test/jdk/java/awt/print/PrinterJob/PrintCompoundString.java +++ b/test/jdk/java/awt/print/PrinterJob/PrintCompoundString.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,226 +21,87 @@ * questions. */ -/** +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.print.PageFormat; +import java.awt.print.Printable; +import java.awt.print.PrinterException; +import java.awt.print.PrinterJob; + +import javax.swing.BorderFactory; +import javax.swing.Box; +import javax.swing.JButton; +import javax.swing.JComponent; +import javax.swing.JOptionPane; + +/* * @test * @bug 4396835 * @summary Compound font string not printing. * @key printer + * @library /java/awt/regtesthelpers + * @build PassFailJFrame * @run main/manual PrintCompoundString */ +public class PrintCompoundString implements Printable { + private static final String STR = "Test string compound printing \u2203\u2200\u2211"; + + private static final String INSTRUCTIONS = + "This test should print following text\n\n" + + STR +"\n\n" + + "If an exception is thrown, or the page doesn't print properly\n" + + "then the test fails"; + + public static void main(String[] args) throws Exception { + if (PrinterJob.lookupPrintServices().length == 0) { + throw new RuntimeException("Printer not configured or available."); + } + + PassFailJFrame.builder() + .instructions(INSTRUCTIONS) + .splitUI(PrintCompoundString::createTestUI) + .rows((int) INSTRUCTIONS.lines().count() + 1) + .columns(45) + .build() + .awaitAndCheck(); + } - -import java.awt.*; -import java.awt.event.*; -import java.awt.print.*; -import java.text.*; - -public class PrintCompoundString extends Frame implements ActionListener { - - private TextCanvas c; - - public static void main(String args[]) { - - String[] instructions = - { - "You must have a printer available to perform this test", - "This test should print a page which contains the same", - "text message as in the test window on the screen", - "You should also monitor the command line to see if any exceptions", - "were thrown", - "If an exception is thrown, or the page doesn't print properly", - "then the test fails", - }; - Sysout.createDialog( ); - Sysout.printInstructions( instructions ); - - PrintCompoundString f = new PrintCompoundString(); - f.show(); - } - - public PrintCompoundString() { - super("JDK 1.2 drawString Printing"); - - c = new TextCanvas(); - add("Center", c); - - Button printButton = new Button("Print"); - printButton.addActionListener(this); - add("South", printButton); - - addWindowListener(new WindowAdapter() { - public void windowClosing(WindowEvent e) { - System.exit(0); + private static JComponent createTestUI() { + JButton b = new JButton("Print"); + b.addActionListener((ae) -> { + try { + PrinterJob job = PrinterJob.getPrinterJob(); + job.setPrintable(new PrintCompoundString()); + if (job.printDialog()) { + job.print(); + } + } catch (PrinterException ex) { + ex.printStackTrace(); + String msg = "PrinterException: " + ex.getMessage(); + JOptionPane.showMessageDialog(b, msg, "Error occurred", + JOptionPane.ERROR_MESSAGE); + PassFailJFrame.forceFail(msg); } - }); - - pack(); - } - - public void actionPerformed(ActionEvent e) { - - PrinterJob pj = PrinterJob.getPrinterJob(); - - if (pj != null && pj.printDialog()) { - - pj.setPrintable(c); - try { - pj.print(); - } catch (PrinterException pe) { - } finally { - System.err.println("PRINT RETURNED"); - } - } - } - - class TextCanvas extends Panel implements Printable { - - String nullStr = null; - String emptyStr = new String(); - AttributedString nullAttStr = null; - AttributedString emptyAttStr = new AttributedString(emptyStr); - AttributedCharacterIterator nullIterator = null; - AttributedCharacterIterator emptyIterator = emptyAttStr.getIterator(); - - public int print(Graphics g, PageFormat pgFmt, int pgIndex) { - - if (pgIndex > 0) - return Printable.NO_SUCH_PAGE; - - Graphics2D g2d = (Graphics2D)g; - g2d.translate(pgFmt.getImageableX(), pgFmt.getImageableY()); - - paint(g); - - return Printable.PAGE_EXISTS; + }); + + Box main = Box.createHorizontalBox(); + main.setBorder(BorderFactory.createEmptyBorder(8, 8, 8, 8)); + main.add(Box.createHorizontalGlue()); + main.add(b); + main.add(Box.createHorizontalGlue()); + return main; } - public void paint(Graphics g1) { - Graphics2D g = (Graphics2D)g1; - - String str = "Test string compound printing \u2203\u2200\u2211"; - g.drawString(str, 20, 40); + @Override + public int print(Graphics g, PageFormat pgFmt, int pgIndex) { + if (pgIndex > 0) { + return Printable.NO_SUCH_PAGE; + } - } + Graphics2D g2d = (Graphics2D) g; + g2d.translate(pgFmt.getImageableX(), pgFmt.getImageableY()); + g2d.drawString(STR, 20, 40); - public Dimension getPreferredSize() { - return new Dimension(450, 250); + return Printable.PAGE_EXISTS; } - } - } - -class Sysout - { - private static TestDialog dialog; - - public static void createDialogWithInstructions( String[] instructions ) - { - dialog = new TestDialog( new Frame(), "Instructions" ); - dialog.printInstructions( instructions ); - dialog.show(); - println( "Any messages for the tester will display here." ); - } - - public static void createDialog( ) - { - dialog = new TestDialog( new Frame(), "Instructions" ); - String[] defInstr = { "Instructions will appear here. ", "" } ; - dialog.printInstructions( defInstr ); - dialog.show(); - println( "Any messages for the tester will display here." ); - } - - - public static void printInstructions( String[] instructions ) - { - dialog.printInstructions( instructions ); - } - - - public static void println( String messageIn ) - { - dialog.displayMessage( messageIn ); - } - - }// Sysout class - -/** - This is part of the standard test machinery. It provides a place for the - test instructions to be displayed, and a place for interactive messages - to the user to be displayed. - To have the test instructions displayed, see Sysout. - To have a message to the user be displayed, see Sysout. - Do not call anything in this dialog directly. - */ -class TestDialog extends Dialog { - - TextArea instructionsText; - TextArea messageText; - int maxStringLength = 80; - - //DO NOT call this directly, go through Sysout - public TestDialog( Frame frame, String name ) - { - super( frame, name ); - int scrollBoth = TextArea.SCROLLBARS_BOTH; - instructionsText = new TextArea( "", 15, maxStringLength, scrollBoth ); - add( "North", instructionsText ); - - messageText = new TextArea( "", 5, maxStringLength, scrollBoth ); - add("Center", messageText); - - pack(); - - show(); - }// TestDialog() - - //DO NOT call this directly, go through Sysout - public void printInstructions( String[] instructions ) - { - //Clear out any current instructions - instructionsText.setText( "" ); - - //Go down array of instruction strings - - String printStr, remainingStr; - for( int i=0; i < instructions.length; i++ ) - { - //chop up each into pieces maxSringLength long - remainingStr = instructions[ i ]; - while( remainingStr.length() > 0 ) - { - //if longer than max then chop off first max chars to print - if( remainingStr.length() >= maxStringLength ) - { - //Try to chop on a word boundary - int posOfSpace = remainingStr. - lastIndexOf( ' ', maxStringLength - 1 ); - - if( posOfSpace <= 0 ) posOfSpace = maxStringLength - 1; - - printStr = remainingStr.substring( 0, posOfSpace + 1 ); - remainingStr = remainingStr.substring( posOfSpace + 1 ); - } - //else just print - else - { - printStr = remainingStr; - remainingStr = ""; - } - - instructionsText.append( printStr + "\n" ); - - }// while - - }// for - - }//printInstructions() - - //DO NOT call this directly, go through Sysout - public void displayMessage( String messageIn ) - { - messageText.append( messageIn + "\n" ); - } - - }// TestDialog class diff --git a/test/jdk/java/awt/print/PrinterJob/PrintImage.java b/test/jdk/java/awt/print/PrinterJob/PrintImage.java index 7eed8c2c276..a3fe19ff5cf 100644 --- a/test/jdk/java/awt/print/PrinterJob/PrintImage.java +++ b/test/jdk/java/awt/print/PrinterJob/PrintImage.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,276 +21,152 @@ * questions. */ -/** - * @test %I %W +import java.awt.BorderLayout; +import java.awt.Canvas; +import java.awt.Color; +import java.awt.Font; +import java.awt.Frame; +import java.awt.Graphics; +import java.awt.Menu; +import java.awt.MenuBar; +import java.awt.MenuItem; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.print.PageFormat; +import java.awt.print.Printable; +import java.awt.print.PrinterException; +import java.awt.print.PrinterJob; + +/* + * @test * @bug 4298489 * @summary Confirm that output is same as screen. * @key printer + * @requires os.family=="windows" + * @library /java/awt/regtesthelpers + * @build PassFailJFrame * @run main/manual PrintImage */ -import java.awt.*; -import java.awt.print.*; -import java.awt.event.*; - public class PrintImage extends Frame implements ActionListener { - - private PrintImageCanvas printImageCanvas; - - private MenuItem print1Menu = new MenuItem("PrintTest1"); - private MenuItem print2Menu = new MenuItem("PrintTest2"); - private MenuItem exitMenu = new MenuItem("Exit"); - - public static void main(String[] argv) { - String[] instructions = - { "You must have a printer available to perform this test,", - "prefererably Canon LaserShot A309GII.", - "Printing must be done in Win 98 Japanese 2nd Edition.", - "", - "Passing test : Output of text image for PrintTest1 and PrintTest2 should be same as that on the screen.", - }; - - Sysout.createDialog( ); - Sysout.printInstructions( instructions ); - - new PrintImage(); - } - - public PrintImage() { - super("PrintImage"); - initPrintImage(); - } - - public void initPrintImage() { - - printImageCanvas = new PrintImageCanvas(this); - - initMenu(); - - addWindowListener(new WindowAdapter() { - public void windowClosing(WindowEvent ev) { - dispose(); - } - public void windowClosed(WindowEvent ev) { - System.exit(0); - } - }); - - setLayout(new BorderLayout()); - add(printImageCanvas, BorderLayout.CENTER); - pack(); - - setSize(500,500); - setVisible(true); + private final PrintImageCanvas printImageCanvas = new PrintImageCanvas(); + private final MenuItem print1Menu = new MenuItem("PrintTest1"); + private final MenuItem print2Menu = new MenuItem("PrintTest2"); + private static final String INSTRUCTIONS = + "Select PrintTest1 in the File menu.\n" + + "Print Dialog will appear.\n" + + "Click OK to start the first print job.\n" + + "\n" + + "Select PrintTest2 in the File menu.\n" + + "Page Setup Dialog will appear.\n" + + "Click OK.\n" + + "Print Dialog will appear.\n" + + "Click OK to start the second print job.\n" + + "\n" + + "The text in the printouts for PrintTest1 and PrintTest2 should be\n" + + "same as that on the screen.\n" + + "Press Pass if they are, otherwise press Fail."; + + public static void main(String[] argv) throws Exception { + if (PrinterJob.lookupPrintServices().length == 0) { + throw new RuntimeException("Printer not configured or available."); } - private void initMenu() { - MenuBar mb = new MenuBar(); - Menu me = new Menu("File"); - me.add(print1Menu); - me.add(print2Menu); - me.add("-"); - me.add(exitMenu); - mb.add(me); - this.setMenuBar(mb); - - print1Menu.addActionListener(this); - print2Menu.addActionListener(this); - exitMenu.addActionListener(this); - } + PassFailJFrame.builder() + .instructions(INSTRUCTIONS) + .testUI(PrintImage::new) + .rows((int) INSTRUCTIONS.lines().count() + 1) + .columns(45) + .build() + .awaitAndCheck(); + } - public void actionPerformed(ActionEvent e) { - Object target = e.getSource(); - if( target.equals(print1Menu) ) { - printMain1(); - } - else if( target.equals(print2Menu) ) { - printMain2(); - } - else if( target.equals(exitMenu) ) { - dispose(); - } - } + public PrintImage() { + super("PrintImage"); + initPrintImage(); + } - private void printMain1(){ + public void initPrintImage() { + initMenu(); + setLayout(new BorderLayout()); + add(printImageCanvas, BorderLayout.CENTER); + setSize(500, 300); + } - PrinterJob printerJob = PrinterJob.getPrinterJob(); - PageFormat pageFormat = printerJob.defaultPage(); + private void initMenu() { + MenuBar mb = new MenuBar(); + Menu me = new Menu("File"); + me.add(print1Menu); + me.add(print2Menu); + mb.add(me); + setMenuBar(mb); - printerJob.setPrintable((Printable)printImageCanvas, pageFormat); + print1Menu.addActionListener(this); + print2Menu.addActionListener(this); + } - if(printerJob.printDialog()){ - try { - printerJob.print(); - } - catch(PrinterException p){ - } - } - else - printerJob.cancel(); + public void actionPerformed(ActionEvent e) { + Object target = e.getSource(); + if (target.equals(print1Menu)) { + printMain1(); + } else if (target.equals(print2Menu)) { + printMain2(); } + } - private void printMain2(){ - - PrinterJob printerJob = PrinterJob.getPrinterJob(); - PageFormat pageFormat = printerJob.pageDialog(printerJob.defaultPage()); - - printerJob.setPrintable((Printable)printImageCanvas, pageFormat); - - if(printerJob.printDialog()){ - try { - printerJob.print(); - } - catch(PrinterException p){ - } - } - else - printerJob.cancel(); + private void printMain1() { + PrinterJob printerJob = PrinterJob.getPrinterJob(); + PageFormat pageFormat = printerJob.defaultPage(); + + printerJob.setPrintable(printImageCanvas, pageFormat); + + if (printerJob.printDialog()) { + try { + printerJob.print(); + } catch (PrinterException e) { + PassFailJFrame.forceFail("Print Failed"); + e.printStackTrace(); + } + } else { + printerJob.cancel(); } + } -} - -class PrintImageCanvas extends Canvas implements Printable { - - private PrintImage pdsFrame; - - public PrintImageCanvas(PrintImage pds) { - pdsFrame = pds; + private void printMain2() { + PrinterJob printerJob = PrinterJob.getPrinterJob(); + PageFormat pageFormat = printerJob.pageDialog(printerJob.defaultPage()); + + printerJob.setPrintable(printImageCanvas, pageFormat); + + if (printerJob.printDialog()) { + try { + printerJob.print(); + } catch (PrinterException e) { + PassFailJFrame.forceFail("Print Failed"); + e.printStackTrace(); + } + } else { + printerJob.cancel(); } + } + private static class PrintImageCanvas extends Canvas implements Printable { + @Override public void paint(Graphics g) { - Font drawFont = new Font("MS Mincho",Font.ITALIC,50); - g.setFont(drawFont); - g.drawString("PrintSample!",100,150); + Font drawFont = new Font("MS Mincho", Font.ITALIC, 50); + g.setFont(drawFont); + g.setColor(new Color(0, 0, 0, 200)); + g.drawString("PrintSample!", 100, 150); } + @Override public int print(Graphics g, PageFormat pf, int pi) throws PrinterException { - - if(pi>=1) - return NO_SUCH_PAGE; - else{ - Graphics2D g2 = (Graphics2D)g; - g.setColor(new Color(0,0,0,200)); - - Font drawFont = new Font("MS Mincho",Font.ITALIC,50); - g.setFont(drawFont); - g.drawString("PrintSample!",100,150); - return PAGE_EXISTS; - } + if (pi > 0) { + return NO_SUCH_PAGE; + } + paint(g); + return PAGE_EXISTS; } -} - - -class Sysout { - private static TestDialog dialog; - - public static void createDialogWithInstructions( String[] instructions ) - { - dialog = new TestDialog( new Frame(), "Instructions" ); - dialog.printInstructions( instructions ); - dialog.show(); - println( "Any messages for the tester will display here." ); - } - - public static void createDialog( ) - { - dialog = new TestDialog( new Frame(), "Instructions" ); - String[] defInstr = { "Instructions will appear here. ", "" } ; - dialog.printInstructions( defInstr ); - dialog.show(); - println( "Any messages for the tester will display here." ); - } - - - public static void printInstructions( String[] instructions ) - { - dialog.printInstructions( instructions ); - } - - - public static void println( String messageIn ) - { - dialog.displayMessage( messageIn ); - } - -}// Sysout class - -/** - This is part of the standard test machinery. It provides a place for the - test instructions to be displayed, and a place for interactive messages - to the user to be displayed. - To have the test instructions displayed, see Sysout. - To have a message to the user be displayed, see Sysout. - Do not call anything in this dialog directly. - */ -class TestDialog extends Dialog { - - TextArea instructionsText; - TextArea messageText; - int maxStringLength = 80; - - //DO NOT call this directly, go through Sysout - public TestDialog( Frame frame, String name ) - { - super( frame, name ); - int scrollBoth = TextArea.SCROLLBARS_BOTH; - instructionsText = new TextArea( "", 15, maxStringLength, scrollBoth ); - add( "North", instructionsText ); - - messageText = new TextArea( "", 5, maxStringLength, scrollBoth ); - add("Center", messageText); - - pack(); - - show(); - }// TestDialog() - - //DO NOT call this directly, go through Sysout - public void printInstructions( String[] instructions ) - { - //Clear out any current instructions - instructionsText.setText( "" ); - - //Go down array of instruction strings - - String printStr, remainingStr; - for( int i=0; i < instructions.length; i++ ) - { - //chop up each into pieces maxSringLength long - remainingStr = instructions[ i ]; - while( remainingStr.length() > 0 ) - { - //if longer than max then chop off first max chars to print - if( remainingStr.length() >= maxStringLength ) - { - //Try to chop on a word boundary - int posOfSpace = remainingStr. - lastIndexOf( ' ', maxStringLength - 1 ); - - if( posOfSpace <= 0 ) posOfSpace = maxStringLength - 1; - - printStr = remainingStr.substring( 0, posOfSpace + 1 ); - remainingStr = remainingStr.substring( posOfSpace + 1 ); - } - //else just print - else - { - printStr = remainingStr; - remainingStr = ""; - } - - instructionsText.append( printStr + "\n" ); - - }// while - - }// for - - }//printInstructions() - - //DO NOT call this directly, go through Sysout - public void displayMessage( String messageIn ) - { - messageText.append( messageIn + "\n" ); } +} - }// TestDialog class diff --git a/test/jdk/java/awt/print/PrinterJob/PrintLatinCJKTest.java b/test/jdk/java/awt/print/PrinterJob/PrintLatinCJKTest.java index 5ffb34540ce..8ffe5fc9310 100644 --- a/test/jdk/java/awt/print/PrinterJob/PrintLatinCJKTest.java +++ b/test/jdk/java/awt/print/PrinterJob/PrintLatinCJKTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2024, Oracle and/or its affiliates. All rights reserved. * 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,7 +31,6 @@ * @run main/manual PrintLatinCJKTest */ -import java.awt.BorderLayout; import java.awt.Font; import java.awt.Graphics; import java.awt.print.PageFormat; @@ -39,51 +38,57 @@ import java.awt.print.PrinterException; import java.awt.print.PrinterJob; import java.lang.reflect.InvocationTargetException; -import javax.swing.JButton; -import javax.swing.JFrame; -import static javax.swing.SwingUtilities.invokeAndWait; +import javax.swing.BorderFactory; +import javax.swing.Box; +import javax.swing.JButton; +import javax.swing.JComponent; +import javax.swing.JOptionPane; public class PrintLatinCJKTest implements Printable { - private static PrintLatinCJKTest testInstance = new PrintLatinCJKTest(); - private static JFrame frame; - private static final String info = """ - You need a printer for this test. If you have none, let - the test pass. If there is a printer, press Print, send - the output to the printer, and examine it. It should have - text looking like this : \u4e00\u4e01\u4e02\u4e03\u4e04English + private static final String TEXT = "\u4e00\u4e01\u4e02\u4e03\u4e04English"; + + private static final String INFO = """ + Press Print, send the output to the printer and examine it. + The printout should have text looking like this: + + """ + + TEXT + """ + + + Press Pass if the text is printed correctly. + If Japanese and English text overlap, press Fail. + To test 8022536, if a remote printer is the system default, it should show in the dialog as the selected printer. """; - public static void showFrame() throws InterruptedException, InvocationTargetException { - invokeAndWait( () -> { - frame = new JFrame("Test Frame"); - JButton b = new JButton("Print"); - b.addActionListener((ae) -> { - try { - PrinterJob job = PrinterJob.getPrinterJob(); - job.setPrintable(testInstance); - if (job.printDialog()) { - job.print(); - } - } catch (PrinterException ex) { - ex.printStackTrace(); + private static JComponent createTestUI() { + JButton b = new JButton("Print"); + b.addActionListener((ae) -> { + try { + PrinterJob job = PrinterJob.getPrinterJob(); + job.setPrintable(new PrintLatinCJKTest()); + if (job.printDialog()) { + job.print(); } - }); - frame.getContentPane().add(b, BorderLayout.SOUTH); - frame.pack(); - - // add the test frame to dispose - PassFailJFrame.addTestWindow(frame); - - // Arrange the test instruction frame and test frame side by side - PassFailJFrame.positionTestWindow(frame, - PassFailJFrame.Position.HORIZONTAL); - frame.setVisible(true); + } catch (PrinterException ex) { + ex.printStackTrace(); + String msg = "PrinterException: " + ex.getMessage(); + JOptionPane.showMessageDialog(b, msg, "Error occurred", + JOptionPane.ERROR_MESSAGE); + PassFailJFrame.forceFail(msg); + } }); + + Box main = Box.createHorizontalBox(); + main.setBorder(BorderFactory.createEmptyBorder(8, 8, 8, 8)); + main.add(Box.createHorizontalGlue()); + main.add(b); + main.add(Box.createHorizontalGlue()); + return main; } @Override @@ -93,22 +98,24 @@ public int print(Graphics g, PageFormat pf, int pageIndex) return Printable.NO_SUCH_PAGE; } g.translate((int) pf.getImageableX(), (int) pf.getImageableY()); - g.setFont(new Font("Dialog", Font.PLAIN, 36)); - g.drawString("\u4e00\u4e01\u4e02\u4e03\u4e04English", 20, 100); + g.setFont(new Font(Font.DIALOG, Font.PLAIN, 36)); + g.drawString(TEXT, 20, 100); return Printable.PAGE_EXISTS; } public static void main(String[] args) throws InterruptedException, InvocationTargetException { - PassFailJFrame passFailJFrame = new PassFailJFrame.Builder() - .title("Test Instructions Frame") - .instructions(info) - .testTimeOut(10) - .rows(10) - .columns(45) - .build(); - showFrame(); - passFailJFrame.awaitAndCheck(); + if (PrinterJob.lookupPrintServices().length == 0) { + throw new RuntimeException("Printer not configured or available."); + } + + PassFailJFrame.builder() + .title("Print Latin CJK Test") + .instructions(INFO) + .testTimeOut(10) + .rows(12) + .columns(30) + .splitUI(PrintLatinCJKTest::createTestUI) + .build() + .awaitAndCheck(); } } - - diff --git a/test/jdk/java/awt/print/PrinterJob/PrintNullString.java b/test/jdk/java/awt/print/PrinterJob/PrintNullString.java index b46db6a1447..e4323b232a7 100644 --- a/test/jdk/java/awt/print/PrinterJob/PrintNullString.java +++ b/test/jdk/java/awt/print/PrinterJob/PrintNullString.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,308 +21,164 @@ * questions. */ -/** +import java.awt.Button; +import java.awt.Dimension; +import java.awt.Frame; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.Panel; +import java.awt.print.PageFormat; +import java.awt.print.Printable; +import java.awt.print.PrinterException; +import java.awt.print.PrinterJob; +import java.text.AttributedCharacterIterator; +import java.text.AttributedString; + +import javax.swing.JOptionPane; + +/* * @test * @bug 4223328 * @summary Printer graphics must behave the same as screen graphics * @key printer + * @library /java/awt/regtesthelpers + * @build PassFailJFrame * @run main/manual PrintNullString */ - - -import java.awt.*; -import java.awt.event.*; -import java.awt.print.*; -import java.text.*; - -public class PrintNullString extends Frame implements ActionListener { - - private TextCanvas c; - - public static void main(String args[]) { - - String[] instructions = - { - "You must have a printer available to perform this test", - "This test should print a page which contains the same", - "text messages as in the test window on the screen", - "The messages should contain only 'OK' and 'expected' messages", - "There should be no FAILURE messages.", - "You should also monitor the command line to see if any exceptions", - "were thrown", - "If the page fails to print, but there were no exceptions", - "then the problem is likely elsewhere (ie your printer)" - }; - Sysout.createDialog( ); - Sysout.printInstructions( instructions ); - - PrintNullString f = new PrintNullString(); - f.show(); - } - - public PrintNullString() { - super("JDK 1.2 drawString Printing"); - - c = new TextCanvas(); - add("Center", c); - - Button printButton = new Button("Print"); - printButton.addActionListener(this); - add("South", printButton); - - addWindowListener(new WindowAdapter() { - public void windowClosing(WindowEvent e) { - System.exit(0); - } - }); - - pack(); - } - - public void actionPerformed(ActionEvent e) { - - PrinterJob pj = PrinterJob.getPrinterJob(); - - if (pj != null && pj.printDialog()) { - - pj.setPrintable(c); - try { - pj.print(); - } catch (PrinterException pe) { - } finally { - System.err.println("PRINT RETURNED"); - } - } - } - - class TextCanvas extends Panel implements Printable { - - String nullStr = null; - String emptyStr = new String(); - AttributedString nullAttStr = null; - AttributedString emptyAttStr = new AttributedString(emptyStr); - AttributedCharacterIterator nullIterator = null; - AttributedCharacterIterator emptyIterator = emptyAttStr.getIterator(); - - public int print(Graphics g, PageFormat pgFmt, int pgIndex) { - - if (pgIndex > 0) - return Printable.NO_SUCH_PAGE; - - Graphics2D g2d = (Graphics2D)g; - g2d.translate(pgFmt.getImageableX(), pgFmt.getImageableY()); - - paint(g); - - return Printable.PAGE_EXISTS; - } - - public void paint(Graphics g1) { - Graphics2D g = (Graphics2D)g1; - - // API 1: null & empty drawString(String, int, int); - try { - g.drawString(nullStr, 20, 40); - g.drawString("FAILURE: No NPE for null String, int", 20, 40); - } catch (NullPointerException e) { - g.drawString("caught expected NPE for null String, int", 20, 40); - }/* catch (Exception e) { - g.drawString("FAILURE: unexpected exception for null String, int", - 20, 40); - }*/ - - //try { - g.drawString(emptyStr, 20, 60); - g.drawString("OK for empty String, int", 20, 60); - /*} catch (Exception e) { - g.drawString("FAILURE: unexpected exception for empty String, int", - 20, 60); - }*/ - - - // API 2: null & empty drawString(String, float, float); - try { - g.drawString(nullStr, 20.0f, 80.0f); - g.drawString("FAILURE: No NPE for null String, float", 20, 80); - } catch (NullPointerException e) { - g.drawString("caught expected NPE for null String, float", 20, 80); - } /*catch (Exception e) { - g.drawString("FAILURE: unexpected exception for null String, float", - 20, 80); - }*/ - //try { - g.drawString(emptyStr, 20.0f, 100.0f); - g.drawString("OK for empty String, float", 20.0f, 100.f); - /* } catch (Exception e) { - g.drawString("FAILURE: unexpected exception for empty String, float", - 20, 100); - }*/ - - // API 3: null & empty drawString(Iterator, int, int); - try { - g.drawString(nullIterator, 20, 120); - g.drawString("FAILURE: No NPE for null iterator, float", 20, 120); - } catch (NullPointerException e) { - g.drawString("caught expected NPE for null iterator, int", 20, 120); - } /*catch (Exception e) { - g.drawString("FAILURE: unexpected exception for null iterator, int", - 20, 120); - } */ - try { - g.drawString(emptyIterator, 20, 140); - g.drawString("FAILURE: No IAE for empty iterator, int", - 20, 140); - } catch (IllegalArgumentException e) { - g.drawString("caught expected IAE for empty iterator, int", - 20, 140); - } /*catch (Exception e) { - g.drawString("FAILURE: unexpected exception for empty iterator, int", - 20, 140); - } */ - - - // API 4: null & empty drawString(Iterator, float, int); - try { - g.drawString(nullIterator, 20.0f, 160.0f); - g.drawString("FAILURE: No NPE for null iterator, float", 20, 160); - } catch (NullPointerException e) { - g.drawString("caught expected NPE for null iterator, float", 20, 160); - } /*catch (Exception e) { - g.drawString("FAILURE: unexpected exception for null iterator, float", - 20, 160); - } */ - - try { - g.drawString(emptyIterator, 20, 180); - g.drawString("FAILURE: No IAE for empty iterator, float", - 20, 180); - } catch (IllegalArgumentException e) { - g.drawString("caught expected IAE for empty iterator, float", - 20, 180); - } /*catch (Exception e) { - g.drawString("FAILURE: unexpected exception for empty iterator, float", - 20, 180); - } */ - } - - public Dimension getPreferredSize() { - return new Dimension(450, 250); - } - } - -} - -class Sysout - { - private static TestDialog dialog; - - public static void createDialogWithInstructions( String[] instructions ) - { - dialog = new TestDialog( new Frame(), "Instructions" ); - dialog.printInstructions( instructions ); - dialog.show(); - println( "Any messages for the tester will display here." ); - } - - public static void createDialog( ) - { - dialog = new TestDialog( new Frame(), "Instructions" ); - String[] defInstr = { "Instructions will appear here. ", "" } ; - dialog.printInstructions( defInstr ); - dialog.show(); - println( "Any messages for the tester will display here." ); - } - - - public static void printInstructions( String[] instructions ) - { - dialog.printInstructions( instructions ); +public class PrintNullString extends Frame { + private static final String INSTRUCTIONS = + "This test should print a page which contains the same\n" + + "text messages as in the test window on the screen.\n" + + "\n" + + "The messages should contain only 'OK' and 'expected' messages.\n" + + "Press Pass if it's the case; otherwise press Fail.\n" + + "\n" + + "If the page fails to print, but there were no exceptions\n" + + "then the problem is likely elsewhere (i.e. your printer)"; + + public static void main(String[] args) throws Exception { + if (PrinterJob.lookupPrintServices().length == 0) { + throw new RuntimeException("Printer not configured or available."); + } + + PassFailJFrame.builder() + .instructions(INSTRUCTIONS) + .testUI(PrintNullString::new) + .rows((int) INSTRUCTIONS.lines().count() + 1) + .columns(45) + .build() + .awaitAndCheck(); } - - public static void println( String messageIn ) - { - dialog.displayMessage( messageIn ); + public PrintNullString() { + super("PrintNullString"); + + TextCanvas c = new TextCanvas(); + add("Center", c); + + Button b = new Button("Print"); + add("South", b); + b.addActionListener(e -> { + PrinterJob pj = PrinterJob.getPrinterJob(); + if (pj.printDialog()) { + pj.setPrintable(c); + try { + pj.print(); + } catch (PrinterException ex) { + ex.printStackTrace(); + String msg = "PrinterException: " + ex.getMessage(); + JOptionPane.showMessageDialog(b, msg, "Error occurred", + JOptionPane.ERROR_MESSAGE); + PassFailJFrame.forceFail(msg); + } + } + }); + pack(); } - }// Sysout class - -/** - This is part of the standard test machinery. It provides a place for the - test instructions to be displayed, and a place for interactive messages - to the user to be displayed. - To have the test instructions displayed, see Sysout. - To have a message to the user be displayed, see Sysout. - Do not call anything in this dialog directly. - */ -class TestDialog extends Dialog { - - TextArea instructionsText; - TextArea messageText; - int maxStringLength = 80; - - //DO NOT call this directly, go through Sysout - public TestDialog( Frame frame, String name ) - { - super( frame, name ); - int scrollBoth = TextArea.SCROLLBARS_BOTH; - instructionsText = new TextArea( "", 15, maxStringLength, scrollBoth ); - add( "North", instructionsText ); - - messageText = new TextArea( "", 5, maxStringLength, scrollBoth ); - add("Center", messageText); - - pack(); + private static class TextCanvas extends Panel implements Printable { + private final String nullStr = null; + private final String emptyStr = ""; + private final AttributedString emptyAttStr = new AttributedString(emptyStr); + private final AttributedCharacterIterator nullIterator = null; + private final AttributedCharacterIterator emptyIterator = emptyAttStr.getIterator(); + + @Override + public void paint(Graphics g) { + Graphics2D g2d = (Graphics2D) g; + paint(g2d); + } + + @Override + public int print(Graphics g, PageFormat pgFmt, int pgIndex) { + if (pgIndex > 0) { + return NO_SUCH_PAGE; + } - show(); - }// TestDialog() + Graphics2D g2d = (Graphics2D) g; + g2d.translate(pgFmt.getImageableX(), pgFmt.getImageableY()); + paint(g2d); - //DO NOT call this directly, go through Sysout - public void printInstructions( String[] instructions ) - { - //Clear out any current instructions - instructionsText.setText( "" ); + return PAGE_EXISTS; + } - //Go down array of instruction strings + private void paint(Graphics2D g2d) { + // API 1: null & empty drawString(String, int, int); + try { + g2d.drawString(nullStr, 20, 40); + g2d.drawString("FAILURE: No NPE for null String, int", 20, 40); + } catch (NullPointerException e) { + g2d.drawString("caught expected NPE for null String, int", 20, 40); + } - String printStr, remainingStr; - for( int i=0; i < instructions.length; i++ ) - { - //chop up each into pieces maxSringLength long - remainingStr = instructions[ i ]; - while( remainingStr.length() > 0 ) - { - //if longer than max then chop off first max chars to print - if( remainingStr.length() >= maxStringLength ) - { - //Try to chop on a word boundary - int posOfSpace = remainingStr. - lastIndexOf( ' ', maxStringLength - 1 ); + g2d.drawString(emptyStr, 20, 60); + g2d.drawString("OK for empty String, int", 20, 60); - if( posOfSpace <= 0 ) posOfSpace = maxStringLength - 1; + // API 2: null & empty drawString(String, float, float); + try { + g2d.drawString(nullStr, 20.0f, 80.0f); + g2d.drawString("FAILURE: No NPE for null String, float", 20, 80); + } catch (NullPointerException e) { + g2d.drawString("caught expected NPE for null String, float", 20, 80); + } - printStr = remainingStr.substring( 0, posOfSpace + 1 ); - remainingStr = remainingStr.substring( posOfSpace + 1 ); - } - //else just print - else - { - printStr = remainingStr; - remainingStr = ""; - } + g2d.drawString(emptyStr, 20.0f, 100.0f); + g2d.drawString("OK for empty String, float", 20.0f, 100.f); - instructionsText.append( printStr + "\n" ); + // API 3: null & empty drawString(Iterator, int, int); + try { + g2d.drawString(nullIterator, 20, 120); + g2d.drawString("FAILURE: No NPE for null iterator, float", 20, 120); + } catch (NullPointerException e) { + g2d.drawString("caught expected NPE for null iterator, int", 20, 120); + } - }// while + try { + g2d.drawString(emptyIterator, 20, 140); + g2d.drawString("FAILURE: No IAE for empty iterator, int", 20, 140); + } catch (IllegalArgumentException e) { + g2d.drawString("caught expected IAE for empty iterator, int", 20, 140); + } - }// for + // API 4: null & empty drawString(Iterator, float, int); + try { + g2d.drawString(nullIterator, 20.0f, 160.0f); + g2d.drawString("FAILURE: No NPE for null iterator, float", 20, 160); + } catch (NullPointerException e) { + g2d.drawString("caught expected NPE for null iterator, float", 20, 160); + } - }//printInstructions() + try { + g2d.drawString(emptyIterator, 20, 180); + g2d.drawString("FAILURE: No IAE for empty iterator, float", 20, 180); + } catch (IllegalArgumentException e) { + g2d.drawString("caught expected IAE for empty iterator, float", 20, 180); + } + } - //DO NOT call this directly, go through Sysout - public void displayMessage( String messageIn ) - { - messageText.append( messageIn + "\n" ); + @Override + public Dimension getPreferredSize() { + return new Dimension(450, 250); + } } - - }// TestDialog class +} diff --git a/test/jdk/java/awt/print/PrinterJob/PrintParenString.java b/test/jdk/java/awt/print/PrinterJob/PrintParenString.java index f3ed7ec1f3e..25d88126c52 100644 --- a/test/jdk/java/awt/print/PrinterJob/PrintParenString.java +++ b/test/jdk/java/awt/print/PrinterJob/PrintParenString.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,226 +21,87 @@ * questions. */ -/** +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.print.PageFormat; +import java.awt.print.Printable; +import java.awt.print.PrinterException; +import java.awt.print.PrinterJob; + +import javax.swing.BorderFactory; +import javax.swing.Box; +import javax.swing.JButton; +import javax.swing.JComponent; +import javax.swing.JOptionPane; + +/* * @test * @bug 4399442 * @summary Brackets should be quoted in Postscript output * @key printer + * @library /java/awt/regtesthelpers + * @build PassFailJFrame * @run main/manual PrintParenString */ +public class PrintParenString implements Printable { + private static final String STR = "String containing unclosed parenthesis (."; + + private static final String INSTRUCTIONS = + "This test should print a page with following text\n\n" + + STR + "\n\n" + + "If an exception is thrown, or the page doesn't print properly\n" + + "then the test fails"; + + public static void main(String[] args) throws Exception { + if (PrinterJob.lookupPrintServices().length == 0) { + throw new RuntimeException("Printer not configured or available."); + } + + PassFailJFrame.builder() + .instructions(INSTRUCTIONS) + .splitUI(PrintParenString::createTestUI) + .rows((int) INSTRUCTIONS.lines().count() + 1) + .columns(45) + .build() + .awaitAndCheck(); + } - -import java.awt.*; -import java.awt.event.*; -import java.awt.print.*; -import java.text.*; - -public class PrintParenString extends Frame implements ActionListener { - - private TextCanvas c; - - public static void main(String args[]) { - - String[] instructions = - { - "You must have a printer available to perform this test", - "This test should print a page which contains the same", - "text message as in the test window on the screen", - "You should also monitor the command line to see if any exceptions", - "were thrown", - "If an exception is thrown, or the page doesn't print properly", - "then the test fails", - }; - Sysout.createDialog( ); - Sysout.printInstructions( instructions ); - - PrintParenString f = new PrintParenString(); - f.show(); - } - - public PrintParenString() { - super("JDK 1.2 drawString Printing"); - - c = new TextCanvas(); - add("Center", c); - - Button printButton = new Button("Print"); - printButton.addActionListener(this); - add("South", printButton); - - addWindowListener(new WindowAdapter() { - public void windowClosing(WindowEvent e) { - System.exit(0); + private static JComponent createTestUI() { + JButton b = new JButton("Print"); + b.addActionListener((ae) -> { + try { + PrinterJob job = PrinterJob.getPrinterJob(); + job.setPrintable(new PrintParenString()); + if (job.printDialog()) { + job.print(); + } + } catch (PrinterException ex) { + ex.printStackTrace(); + String msg = "PrinterException: " + ex.getMessage(); + JOptionPane.showMessageDialog(b, msg, "Error occurred", + JOptionPane.ERROR_MESSAGE); + PassFailJFrame.forceFail(msg); } - }); - - pack(); - } - - public void actionPerformed(ActionEvent e) { - - PrinterJob pj = PrinterJob.getPrinterJob(); - - if (pj != null && pj.printDialog()) { - - pj.setPrintable(c); - try { - pj.print(); - } catch (PrinterException pe) { - } finally { - System.err.println("PRINT RETURNED"); - } - } - } - - class TextCanvas extends Panel implements Printable { - - String nullStr = null; - String emptyStr = new String(); - AttributedString nullAttStr = null; - AttributedString emptyAttStr = new AttributedString(emptyStr); - AttributedCharacterIterator nullIterator = null; - AttributedCharacterIterator emptyIterator = emptyAttStr.getIterator(); - - public int print(Graphics g, PageFormat pgFmt, int pgIndex) { - - if (pgIndex > 0) - return Printable.NO_SUCH_PAGE; - - Graphics2D g2d = (Graphics2D)g; - g2d.translate(pgFmt.getImageableX(), pgFmt.getImageableY()); - - paint(g); - - return Printable.PAGE_EXISTS; + }); + + Box main = Box.createHorizontalBox(); + main.setBorder(BorderFactory.createEmptyBorder(8, 8, 8, 8)); + main.add(Box.createHorizontalGlue()); + main.add(b); + main.add(Box.createHorizontalGlue()); + return main; } - public void paint(Graphics g1) { - Graphics2D g = (Graphics2D)g1; - - String str = "String containing unclosed parenthesis (."; - g.drawString(str, 20, 40); + @Override + public int print(Graphics g, PageFormat pgFmt, int pgIndex) { + if (pgIndex > 0) { + return Printable.NO_SUCH_PAGE; + } - } + Graphics2D g2d = (Graphics2D) g; + g2d.translate(pgFmt.getImageableX(), pgFmt.getImageableY()); + g2d.drawString(STR, 20, 40); - public Dimension getPreferredSize() { - return new Dimension(450, 250); + return Printable.PAGE_EXISTS; } - } - } - -class Sysout - { - private static TestDialog dialog; - - public static void createDialogWithInstructions( String[] instructions ) - { - dialog = new TestDialog( new Frame(), "Instructions" ); - dialog.printInstructions( instructions ); - dialog.show(); - println( "Any messages for the tester will display here." ); - } - - public static void createDialog( ) - { - dialog = new TestDialog( new Frame(), "Instructions" ); - String[] defInstr = { "Instructions will appear here. ", "" } ; - dialog.printInstructions( defInstr ); - dialog.show(); - println( "Any messages for the tester will display here." ); - } - - - public static void printInstructions( String[] instructions ) - { - dialog.printInstructions( instructions ); - } - - - public static void println( String messageIn ) - { - dialog.displayMessage( messageIn ); - } - - }// Sysout class - -/** - This is part of the standard test machinery. It provides a place for the - test instructions to be displayed, and a place for interactive messages - to the user to be displayed. - To have the test instructions displayed, see Sysout. - To have a message to the user be displayed, see Sysout. - Do not call anything in this dialog directly. - */ -class TestDialog extends Dialog { - - TextArea instructionsText; - TextArea messageText; - int maxStringLength = 80; - - //DO NOT call this directly, go through Sysout - public TestDialog( Frame frame, String name ) - { - super( frame, name ); - int scrollBoth = TextArea.SCROLLBARS_BOTH; - instructionsText = new TextArea( "", 15, maxStringLength, scrollBoth ); - add( "North", instructionsText ); - - messageText = new TextArea( "", 5, maxStringLength, scrollBoth ); - add("Center", messageText); - - pack(); - - show(); - }// TestDialog() - - //DO NOT call this directly, go through Sysout - public void printInstructions( String[] instructions ) - { - //Clear out any current instructions - instructionsText.setText( "" ); - - //Go down array of instruction strings - - String printStr, remainingStr; - for( int i=0; i < instructions.length; i++ ) - { - //chop up each into pieces maxSringLength long - remainingStr = instructions[ i ]; - while( remainingStr.length() > 0 ) - { - //if longer than max then chop off first max chars to print - if( remainingStr.length() >= maxStringLength ) - { - //Try to chop on a word boundary - int posOfSpace = remainingStr. - lastIndexOf( ' ', maxStringLength - 1 ); - - if( posOfSpace <= 0 ) posOfSpace = maxStringLength - 1; - - printStr = remainingStr.substring( 0, posOfSpace + 1 ); - remainingStr = remainingStr.substring( posOfSpace + 1 ); - } - //else just print - else - { - printStr = remainingStr; - remainingStr = ""; - } - - instructionsText.append( printStr + "\n" ); - - }// while - - }// for - - }//printInstructions() - - //DO NOT call this directly, go through Sysout - public void displayMessage( String messageIn ) - { - messageText.append( messageIn + "\n" ); - } - - }// TestDialog class diff --git a/test/jdk/java/awt/print/PrinterJob/PrintTranslatedFont.java b/test/jdk/java/awt/print/PrinterJob/PrintTranslatedFont.java index 51ff6ce57a7..de80a1e9ee7 100644 --- a/test/jdk/java/awt/print/PrinterJob/PrintTranslatedFont.java +++ b/test/jdk/java/awt/print/PrinterJob/PrintTranslatedFont.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,237 +21,126 @@ * questions. */ -/** +import java.awt.Button; +import java.awt.Dimension; +import java.awt.Font; +import java.awt.FontMetrics; +import java.awt.Frame; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.Panel; +import java.awt.geom.AffineTransform; +import java.awt.print.PageFormat; +import java.awt.print.Printable; +import java.awt.print.PrinterException; +import java.awt.print.PrinterJob; + +import javax.swing.JOptionPane; + +/* * @test * @bug 6359734 * @key printer + * @library /java/awt/regtesthelpers + * @build PassFailJFrame * @summary Test that fonts with a translation print where they should. * @run main/manual PrintTranslatedFont */ +public class PrintTranslatedFont extends Frame { + private static final String INSTRUCTIONS = + "This test should print a page which contains the same\n" + + "content as the test window on the screen, in particular the lines\n" + + "should be immediately under the text\n\n" + + "If an exception is thrown, or the page doesn't print properly\n" + + "then the test fails"; + + public static void main(String[] args) throws Exception { + if (PrinterJob.lookupPrintServices().length == 0) { + throw new RuntimeException("Printer not configured or available."); + } + + PassFailJFrame.builder() + .instructions(INSTRUCTIONS) + .testUI(PrintTranslatedFont::new) + .rows((int) INSTRUCTIONS.lines().count() + 1) + .columns(45) + .build() + .awaitAndCheck(); + } - -import java.awt.*; -import java.awt.event.*; -import java.awt.geom.*; -import java.awt.print.*; -import java.text.*; - -public class PrintTranslatedFont extends Frame implements ActionListener { - - private TextCanvas c; - - public static void main(String args[]) { - - String[] instructions = - { - "You must have a printer available to perform this test", - "This test should print a page which contains the same", - "content as the test window on the screen, in particular the lines", - "should be immediately under the text", - "You should also monitor the command line to see if any exceptions", - "were thrown", - "If an exception is thrown, or the page doesn't print properly", - "then the test fails", - }; - Sysout.createDialog( ); - Sysout.printInstructions( instructions ); - - PrintTranslatedFont f = new PrintTranslatedFont(); - f.show(); - } - - public PrintTranslatedFont() { - super("JDK 1.2 drawString Printing"); - - c = new TextCanvas(); - add("Center", c); - - Button printButton = new Button("Print"); - printButton.addActionListener(this); - add("South", printButton); - - addWindowListener(new WindowAdapter() { - public void windowClosing(WindowEvent e) { - System.exit(0); + public PrintTranslatedFont() { + super("PrintTranslatedFont"); + + TextCanvas c = new TextCanvas(); + add("Center", c); + + Button b = new Button("Print"); + add("South", b); + b.addActionListener(e -> { + PrinterJob pj = PrinterJob.getPrinterJob(); + if (pj.printDialog()) { + pj.setPrintable(c); + try { + pj.print(); + } catch (PrinterException ex) { + ex.printStackTrace(); + String msg = "PrinterException: " + ex.getMessage(); + JOptionPane.showMessageDialog(b, msg, "Error occurred", + JOptionPane.ERROR_MESSAGE); + PassFailJFrame.forceFail(msg); + } } - }); - - pack(); - } - - public void actionPerformed(ActionEvent e) { + }); - PrinterJob pj = PrinterJob.getPrinterJob(); - - if (pj != null && pj.printDialog()) { - - pj.setPrintable(c); - try { - pj.print(); - } catch (PrinterException pe) { - } finally { - System.err.println("PRINT RETURNED"); - } - } - } - - class TextCanvas extends Panel implements Printable { - - public int print(Graphics g, PageFormat pgFmt, int pgIndex) { - - if (pgIndex > 0) - return Printable.NO_SUCH_PAGE; - - Graphics2D g2d = (Graphics2D)g; - g2d.translate(pgFmt.getImageableX(), pgFmt.getImageableY()); - - paint(g); - - return Printable.PAGE_EXISTS; + pack(); } - public void paint(Graphics g1) { - Graphics2D g = (Graphics2D)g1; - - Font f = new Font("Dialog", Font.PLAIN, 20); - int tx = 20; - int ty = 20; - AffineTransform at = AffineTransform.getTranslateInstance(tx, ty); - f = f.deriveFont(at); - g.setFont(f); - - FontMetrics fm = g.getFontMetrics(); - String str = "Basic ascii string"; - int sw = fm.stringWidth(str); - int posx = 20, posy = 40; - g.drawString(str, posx, posy); - g.drawLine(posx+tx, posy+ty+2, posx+tx+sw, posy+ty+2); - - posx = 20; posy = 70; - str = "Test string compound printing \u2203\u2200"; - sw = fm.stringWidth(str); - g.drawString(str, posx, posy); - g.drawLine(posx+tx, posy+ty+2, posx+tx+sw, posy+ty+2); - } + private static class TextCanvas extends Panel implements Printable { + @Override + public void paint(Graphics g) { + Graphics2D g2d = (Graphics2D) g; + paint(g2d); + } + + @Override + public int print(Graphics g, PageFormat pgFmt, int pgIndex) { + if (pgIndex > 0) { + return Printable.NO_SUCH_PAGE; + } - public Dimension getPreferredSize() { - return new Dimension(450, 250); + Graphics2D g2d = (Graphics2D) g; + g2d.translate(pgFmt.getImageableX(), pgFmt.getImageableY()); + paint(g2d); + return Printable.PAGE_EXISTS; + } + + private void paint(Graphics2D g2d) { + Font f = new Font("Dialog", Font.PLAIN, 20); + int tx = 20; + int ty = 20; + AffineTransform at = AffineTransform.getTranslateInstance(tx, ty); + f = f.deriveFont(at); + g2d.setFont(f); + + FontMetrics fm = g2d.getFontMetrics(); + String str = "Basic ascii string"; + int sw = fm.stringWidth(str); + int posx = 20; + int posy = 40; + g2d.drawString(str, posx, posy); + g2d.drawLine(posx + tx, posy + ty + 2, posx + tx + sw, posy + ty + 2); + + posx = 20; + posy = 70; + str = "Test string compound printing \u2203\u2200"; + sw = fm.stringWidth(str); + g2d.drawString(str, posx, posy); + g2d.drawLine(posx + tx, posy + ty + 2, posx + tx + sw, posy + ty + 2); + } + + @Override + public Dimension getPreferredSize() { + return new Dimension(450, 250); + } } - } - } - -class Sysout - { - private static TestDialog dialog; - - public static void createDialogWithInstructions( String[] instructions ) - { - dialog = new TestDialog( new Frame(), "Instructions" ); - dialog.printInstructions( instructions ); - dialog.show(); - println( "Any messages for the tester will display here." ); - } - - public static void createDialog( ) - { - dialog = new TestDialog( new Frame(), "Instructions" ); - String[] defInstr = { "Instructions will appear here. ", "" } ; - dialog.printInstructions( defInstr ); - dialog.show(); - println( "Any messages for the tester will display here." ); - } - - - public static void printInstructions( String[] instructions ) - { - dialog.printInstructions( instructions ); - } - - - public static void println( String messageIn ) - { - dialog.displayMessage( messageIn ); - } - - }// Sysout class - -/** - This is part of the standard test machinery. It provides a place for the - test instructions to be displayed, and a place for interactive messages - to the user to be displayed. - To have the test instructions displayed, see Sysout. - To have a message to the user be displayed, see Sysout. - Do not call anything in this dialog directly. - */ -class TestDialog extends Dialog { - - TextArea instructionsText; - TextArea messageText; - int maxStringLength = 80; - - //DO NOT call this directly, go through Sysout - public TestDialog( Frame frame, String name ) - { - super( frame, name ); - int scrollBoth = TextArea.SCROLLBARS_BOTH; - instructionsText = new TextArea( "", 15, maxStringLength, scrollBoth ); - add( "North", instructionsText ); - - messageText = new TextArea( "", 5, maxStringLength, scrollBoth ); - add("Center", messageText); - - pack(); - - show(); - }// TestDialog() - - //DO NOT call this directly, go through Sysout - public void printInstructions( String[] instructions ) - { - //Clear out any current instructions - instructionsText.setText( "" ); - - //Go down array of instruction strings - - String printStr, remainingStr; - for( int i=0; i < instructions.length; i++ ) - { - //chop up each into pieces maxSringLength long - remainingStr = instructions[ i ]; - while( remainingStr.length() > 0 ) - { - //if longer than max then chop off first max chars to print - if( remainingStr.length() >= maxStringLength ) - { - //Try to chop on a word boundary - int posOfSpace = remainingStr. - lastIndexOf( ' ', maxStringLength - 1 ); - - if( posOfSpace <= 0 ) posOfSpace = maxStringLength - 1; - - printStr = remainingStr.substring( 0, posOfSpace + 1 ); - remainingStr = remainingStr.substring( posOfSpace + 1 ); - } - //else just print - else - { - printStr = remainingStr; - remainingStr = ""; - } - - instructionsText.append( printStr + "\n" ); - - }// while - - }// for - - }//printInstructions() - - //DO NOT call this directly, go through Sysout - public void displayMessage( String messageIn ) - { - messageText.append( messageIn + "\n" ); - } - - }// TestDialog class diff --git a/test/jdk/java/awt/print/PrinterJob/SecurityDialogTest.java b/test/jdk/java/awt/print/PrinterJob/SecurityDialogTest.java index d6a9efeb97c..b16dfed43fd 100644 --- a/test/jdk/java/awt/print/PrinterJob/SecurityDialogTest.java +++ b/test/jdk/java/awt/print/PrinterJob/SecurityDialogTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,210 +21,110 @@ * questions. */ -/** +import java.awt.Frame; +import java.awt.print.PageFormat; +import java.awt.print.PrinterJob; +import java.lang.reflect.InvocationTargetException; + +import javax.print.PrintService; +import javax.print.attribute.HashPrintRequestAttributeSet; +import javax.print.attribute.PrintRequestAttributeSet; +import javax.swing.BorderFactory; +import javax.swing.Box; +import javax.swing.JComponent; +import javax.swing.JLabel; +import javax.swing.SwingUtilities; + +/* * @test * @bug 4937672 5100706 6252456 * @key printer - * @run main/othervm/manual -Djava.security.manager=allow SecurityDialogTest + * @summary Verifies "Print to file" option is disable if reading/writing files + * is not allowed by Security Manager. + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @run main/manual/othervm -Djava.security.manager=allow SecurityDialogTest */ - -import java.awt.* ; -import java.awt.print.* ; -import java.io.*; -import java.security.*; -import javax.print.*; -import javax.print.attribute.*; - public class SecurityDialogTest { + private static final String INSTRUCTIONS = + "This test brings up a native and cross-platform page and print dialogs.\n" + + "\n" + + "If the dialog has an option to save to file, the option ought " + + "to be disabled.\n" + + "\n" + + "Press the Pass button if the \"Print to file\" option was disabled in\n" + + "all the dialogs where it was present.\n" + + "Otherwise, press the Fail button.\n" + + "\n" + + "The dialogs should be displayed even when \n" + + "there is no queuePrintJob permission."; + + private static JLabel dialogType; + + public static void main(String[] args) throws Exception { + if (PrinterJob.lookupPrintServices().length == 0) { + throw new RuntimeException("Printer not configured or available."); + } + PassFailJFrame passFailJFrame = PassFailJFrame.builder() + .instructions(INSTRUCTIONS) + .splitUIBottom(SecurityDialogTest::createTestUI) + .rows((int) INSTRUCTIONS.lines().count() + 1) + .columns(45) + .build(); - public static void main ( String args[] ) { - - String[] instructions = - { - "You must have a printer available to perform this test.", - "This test brings up a native and cross-platform page and", - "print dialogs.", - "The dialogs should be displayed even when ", - "there is no queuePrintJob permission.", - "If the dialog has an option to save to file, the option ought", - "to be disabled if there is no read/write file permission.", - "You should test this by trying different policy files." - }; - - Sysout.createDialog( ); - Sysout.printInstructions( instructions ); + displayDialogs(); - SecurityDialogTest pjc = new SecurityDialogTest() ; + passFailJFrame.awaitAndCheck(); } + private static JComponent createTestUI() { + dialogType = new JLabel(" "); - public SecurityDialogTest() { - - PrinterJob pj = PrinterJob.getPrinterJob() ; - - // Install a security manager which does not allow reading and - // writing of files. - //PrintTestSecurityManager ptsm = new PrintTestSecurityManager(); - SecurityManager ptsm = new SecurityManager(); - - try { - System.setSecurityManager(ptsm); - } catch (SecurityException e) { - System.out.println("Could not run test - security exception"); - } - - try { - PrintJob pjob = Toolkit.getDefaultToolkit().getPrintJob(new Frame(), "Printing", null, null); - Sysout.println("If the value of pjob is null, the test fails.\n"); - Sysout.println(" pjob = "+pjob); - } catch (SecurityException e) { - } - - PrintService[] services = PrinterJob.lookupPrintServices(); - for (int i=0; i 0 ) - { - //if longer than max then chop off first max chars to print - if( remainingStr.length() >= maxStringLength ) - { - //Try to chop on a word boundary - int posOfSpace = remainingStr. - lastIndexOf( ' ', maxStringLength - 1 ); - - if( posOfSpace <= 0 ) posOfSpace = maxStringLength - 1; - - printStr = remainingStr.substring( 0, posOfSpace + 1 ); - remainingStr = remainingStr.substring( posOfSpace + 1 ); - } - //else just print - else - { - printStr = remainingStr; - remainingStr = ""; - } - - instructionsText.append( printStr + "\n" ); - - }// while - - }// for - - }//printInstructions() - - //DO NOT call this directly, go through Sysout - public void displayMessage( String messageIn ) - { - messageText.append( messageIn + "\n" ); + private static void setDialogType(String type) + throws InterruptedException, InvocationTargetException { + SwingUtilities.invokeAndWait(() -> dialogType.setText(type)); } - - }// TestDialog class +} \ No newline at end of file diff --git a/test/jdk/java/awt/regtesthelpers/PassFailJFrame.java b/test/jdk/java/awt/regtesthelpers/PassFailJFrame.java index 6290d14b428..6e762925a36 100644 --- a/test/jdk/java/awt/regtesthelpers/PassFailJFrame.java +++ b/test/jdk/java/awt/regtesthelpers/PassFailJFrame.java @@ -24,6 +24,7 @@ import java.awt.AWTException; import java.awt.BorderLayout; import java.awt.Dimension; +import java.awt.Font; import java.awt.GraphicsConfiguration; import java.awt.GraphicsDevice; import java.awt.GraphicsEnvironment; @@ -47,12 +48,14 @@ import java.util.Arrays; import java.util.Collection; import java.util.List; +import java.util.Locale; import java.util.Objects; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import javax.imageio.ImageIO; +import javax.swing.Box; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JComponent; @@ -155,6 +158,7 @@ *
  • the title of the instruction UI,
  • *
  • the timeout of the test,
  • *
  • the size of the instruction UI via rows and columns, and
  • + *
  • to add a log area
  • , *
  • to enable screenshots.
  • * */ @@ -186,7 +190,7 @@ public final class PassFailJFrame { private static final CountDownLatch latch = new CountDownLatch(1); - private static TimeoutHandler timeoutHandler; + private static TimeoutHandlerPanel timeoutHandlerPanel; /** * The description of why the test fails. @@ -204,6 +208,8 @@ public final class PassFailJFrame { private static Robot robot; + private static JTextArea logArea; + public enum Position {HORIZONTAL, VERTICAL, TOP_LEFT_CORNER} public PassFailJFrame(String instructions) throws InterruptedException, @@ -373,6 +379,20 @@ private static void invokeOnEDT(Runnable doRun) } } + /** + * Does the same as {@link #invokeOnEDT(Runnable)}, but does not throw + * any checked exceptions. + * + * @param doRun an operation to run on EDT + */ + private static void invokeOnEDTUncheckedException(Runnable doRun) { + try { + invokeOnEDT(doRun); + } catch (InterruptedException | InvocationTargetException e) { + throw new RuntimeException(e); + } + } + private static void createUI(String title, String instructions, long testTimeOut, int rows, int columns, boolean enableScreenCapture) { @@ -384,7 +404,8 @@ private static void createUI(String title, String instructions, frame.add(createInstructionUIPanel(instructions, testTimeOut, rows, columns, - enableScreenCapture), + enableScreenCapture, + false, 0), BorderLayout.CENTER); frame.pack(); frame.setLocationRelativeTo(null); @@ -401,8 +422,9 @@ private static void createUI(Builder builder) { createInstructionUIPanel(builder.instructions, builder.testTimeOut, builder.rows, builder.columns, - builder.screenCapture); - + builder.screenCapture, + builder.addLogArea, + builder.logAreaRows); if (builder.splitUI) { JSplitPane splitPane = new JSplitPane( builder.splitUIOrientation, @@ -421,12 +443,12 @@ private static void createUI(Builder builder) { private static JComponent createInstructionUIPanel(String instructions, long testTimeOut, int rows, int columns, - boolean enableScreenCapture) { + boolean enableScreenCapture, + boolean addLogArea, + int logAreaRows) { JPanel main = new JPanel(new BorderLayout()); - - JLabel testTimeoutLabel = new JLabel("", JLabel.CENTER); - timeoutHandler = new TimeoutHandler(testTimeoutLabel, testTimeOut); - main.add(testTimeoutLabel, BorderLayout.NORTH); + timeoutHandlerPanel = new TimeoutHandlerPanel(testTimeOut); + main.add(timeoutHandlerPanel, BorderLayout.NORTH); JTextComponent text = instructions.startsWith("") ? configureHTML(instructions, rows, columns) @@ -438,13 +460,13 @@ private static JComponent createInstructionUIPanel(String instructions, JButton btnPass = new JButton("Pass"); btnPass.addActionListener((e) -> { latch.countDown(); - timeoutHandler.stop(); + timeoutHandlerPanel.stop(); }); JButton btnFail = new JButton("Fail"); btnFail.addActionListener((e) -> { requestFailureReason(); - timeoutHandler.stop(); + timeoutHandlerPanel.stop(); }); JPanel buttonsPanel = new JPanel(); @@ -455,7 +477,20 @@ private static JComponent createInstructionUIPanel(String instructions, buttonsPanel.add(createCapturePanel()); } - main.add(buttonsPanel, BorderLayout.SOUTH); + if (addLogArea) { + logArea = new JTextArea(logAreaRows, columns); + logArea.setEditable(false); + + Box buttonsLogPanel = Box.createVerticalBox(); + + buttonsLogPanel.add(buttonsPanel); + buttonsLogPanel.add(new JScrollPane(logArea)); + + main.add(buttonsLogPanel, BorderLayout.SOUTH); + } else { + main.add(buttonsPanel, BorderLayout.SOUTH); + } + main.setMinimumSize(main.getPreferredSize()); return main; @@ -602,17 +637,35 @@ public interface InstructionUI { } - private static final class TimeoutHandler implements ActionListener { - private final long endTime; + private static final class TimeoutHandlerPanel + extends JPanel + implements ActionListener { + + private static final String PAUSE_BUTTON_LABEL = "Pause"; + private static final String RESUME_BUTTON_LABEL = "Resume"; + + private long endTime; + private long pauseTimeLeft; private final Timer timer; private final JLabel label; + private final JButton button; + + public TimeoutHandlerPanel(final long testTimeOut) { + endTime = System.currentTimeMillis() + + TimeUnit.MINUTES.toMillis(testTimeOut); + + label = new JLabel("", JLabel.CENTER); + button = new JButton(PAUSE_BUTTON_LABEL); - public TimeoutHandler(final JLabel label, final long testTimeOut) { - endTime = System.currentTimeMillis() + TimeUnit.MINUTES.toMillis(testTimeOut); + button.setFocusPainted(false); + button.setFont(new Font(Font.DIALOG, Font.BOLD, 10)); + button.addActionListener(e -> pauseToggle()); - this.label = label; + setLayout(new BorderLayout()); + add(label, BorderLayout.CENTER); + add(button, BorderLayout.EAST); timer = new Timer(1000, this); timer.start(); @@ -639,10 +692,27 @@ private void updateTime(final long leftTime) { long hours = leftTime / 3_600_000; long minutes = (leftTime - hours * 3_600_000) / 60_000; long seconds = (leftTime - hours * 3_600_000 - minutes * 60_000) / 1_000; - label.setText(String.format("Test timeout: %02d:%02d:%02d", + label.setText(String.format(Locale.ENGLISH, + "Test timeout: %02d:%02d:%02d", hours, minutes, seconds)); } + + private void pauseToggle() { + if (timer.isRunning()) { + pauseTimeLeft = endTime - System.currentTimeMillis(); + timer.stop(); + label.setEnabled(false); + button.setText(RESUME_BUTTON_LABEL); + } else { + endTime = System.currentTimeMillis() + pauseTimeLeft; + updateTime(pauseTimeLeft); + timer.start(); + label.setEnabled(true); + button.setText(PAUSE_BUTTON_LABEL); + } + } + public void stop() { timer.stop(); } @@ -1039,6 +1109,36 @@ public static void forceFail(String reason) { latch.countDown(); } + /** + * Adds a {@code message} to the log area, if enabled by + * {@link Builder#logArea()} or {@link Builder#logArea(int)}. + * + * @param message to log + */ + public static void log(String message) { + System.out.println("PassFailJFrame: " + message); + invokeOnEDTUncheckedException(() -> logArea.append(message + "\n")); + } + + /** + * Clears the log area, if enabled by + * {@link Builder#logArea()} or {@link Builder#logArea(int)}. + */ + public static void logClear() { + System.out.println("\nPassFailJFrame: log cleared\n"); + invokeOnEDTUncheckedException(() -> logArea.setText("")); + } + + /** + * Replaces the log area content with provided {@code text}, if enabled by + * {@link Builder#logArea()} or {@link Builder#logArea(int)}. + * @param text new text for the log area + */ + public static void logSet(String text) { + System.out.println("\nPassFailJFrame: log set to:\n" + text + "\n"); + invokeOnEDTUncheckedException(() -> logArea.setText(text)); + } + public static final class Builder { private String title; private String instructions; @@ -1046,6 +1146,8 @@ public static final class Builder { private int rows; private int columns; private boolean screenCapture; + private boolean addLogArea; + private int logAreaRows = 10; private List testWindows; private WindowListCreator windowListCreator; @@ -1087,6 +1189,37 @@ public Builder screenCapture() { return this; } + /** + * Adds a log area below the "Pass", "Fail" buttons. + *

    + * The log area can be controlled by {@link #log(String)}, + * {@link #logClear()} and {@link #logSet(String)}. + * + * @return this builder + */ + public Builder logArea() { + this.addLogArea = true; + return this; + } + + /** + * Adds a log area below the "Pass", "Fail" buttons. + *

    + * The log area can be controlled by {@link #log(String)}, + * {@link #logClear()} and {@link #logSet(String)}. + *

    + * The number of columns is taken from the number of + * columns in the instructional JTextArea. + * + * @param rows of the log area + * @return this builder + */ + public Builder logArea(int rows) { + this.addLogArea = true; + this.logAreaRows = rows; + return this; + } + /** * Adds a {@code WindowCreator} which the framework will use * to create the test UI window. diff --git a/test/jdk/java/beans/Introspector/DefaultMethodBeanPropertyTest.java b/test/jdk/java/beans/Introspector/DefaultMethodBeanPropertyTest.java new file mode 100644 index 00000000000..a1e528880ef --- /dev/null +++ b/test/jdk/java/beans/Introspector/DefaultMethodBeanPropertyTest.java @@ -0,0 +1,211 @@ +/* + * Copyright (c) 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute 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 8071693 + * @summary Verify that the Introspector finds default methods inherited + * from interfaces + */ + +import java.beans.IntrospectionException; +import java.beans.Introspector; +import java.beans.PropertyDescriptor; +import java.lang.reflect.Method; +import java.util.Collection; +import java.util.HashSet; +import java.util.NavigableSet; +import java.util.Set; +import java.util.stream.Collectors; + +public class DefaultMethodBeanPropertyTest { + +////////////////////////////////////// +// // +// SCENARIO 1 // +// // +////////////////////////////////////// + + public interface A1 { + default int getValue() { + return 0; + } + default Object getObj() { + return null; + } + + public static int getStaticValue() { + return 0; + } + } + + public interface B1 extends A1 { + } + + public interface C1 extends A1 { + Number getFoo(); + } + + public class D1 implements C1 { + @Override + public Integer getFoo() { + return null; + } + @Override + public Float getObj() { + return null; + } + } + + public static void testScenario1() { + verifyProperties(D1.class, + "getClass", // inherited method + "getValue", // inherited default method + "getFoo", // overridden interface method + "getObj" // overridden default method + ); + } + +////////////////////////////////////// +// // +// SCENARIO 2 // +// // +////////////////////////////////////// + + public interface A2 { + default Object getFoo() { + return null; + } + } + + public interface B2 extends A2 { + } + + public interface C2 extends A2 { + } + + public class D2 implements B2, C2 { + } + + public static void testScenario2() { + verifyProperties(D2.class, + "getClass", + "getFoo" + ); + } + +////////////////////////////////////// +// // +// SCENARIO 3 // +// // +////////////////////////////////////// + + public interface A3 { + default Object getFoo() { + return null; + } + } + + public interface B3 extends A3 { + @Override + Set getFoo(); + } + + public interface C3 extends A3 { + @Override + Collection getFoo(); + } + + public class D3 implements B3, C3 { + @Override + public NavigableSet getFoo() { + return null; + } + } + + public static void testScenario3() { + verifyProperties(D3.class, + "getClass", + "getFoo" + ); + } + +// Helper methods + + public static void verifyProperties(Class type, String... getterNames) { + + // Gather expected properties + final HashSet expected = new HashSet<>(); + for (String methodName : getterNames) { + final String suffix = methodName.substring(3); + final String propName = Introspector.decapitalize(suffix); + final Method getter; + try { + getter = type.getMethod(methodName); + } catch (NoSuchMethodException e) { + throw new Error("unexpected error", e); + } + final PropertyDescriptor propDesc; + try { + propDesc = new PropertyDescriptor(propName, getter, null); + } catch (IntrospectionException e) { + throw new Error("unexpected error", e); + } + expected.add(propDesc); + } + + // Verify properties can be found directly + expected.stream() + .map(PropertyDescriptor::getName) + .filter(name -> BeanUtils.getPropertyDescriptor(type, name) == null) + .findFirst() + .ifPresent(name -> { + throw new Error("property \"" + name + "\" not found in " + type); + }); + + // Gather actual properties + final Set actual = + Set.of(BeanUtils.getPropertyDescriptors(type)); + + // Verify the two sets are the same + if (!actual.equals(expected)) { + throw new Error("mismatch: " + type + + "\nACTUAL:\n " + + actual.stream() + .map(Object::toString) + .collect(Collectors.joining("\n ")) + + "\nEXPECTED:\n " + + expected.stream() + .map(Object::toString) + .collect(Collectors.joining("\n "))); + } + } + +// Main method + + public static void main(String[] args) throws Exception { + testScenario1(); + testScenario2(); + testScenario3(); + } +} diff --git a/test/jdk/java/io/File/MacPath.java b/test/jdk/java/io/File/MacPath.java index a9d91018783..751113b7fd8 100644 --- a/test/jdk/java/io/File/MacPath.java +++ b/test/jdk/java/io/File/MacPath.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2023, Oracle and/or its affiliates. All rights reserved. * 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,7 +38,7 @@ public class MacPath { public static void main(String args[]) throws Exception { final ProcessBuilder pb = - ProcessTools.createTestJvm(MacPathTest.class.getName()); + ProcessTools.createTestJavaProcessBuilder(MacPathTest.class.getName()); final Map env = pb.environment(); env.put("LC_ALL", "en_US.UTF-8"); Process p = ProcessTools.startProcess("Mac Path Test", pb); diff --git a/test/jdk/java/io/FileInputStream/ReadXBytes.java b/test/jdk/java/io/FileInputStream/ReadXBytes.java index 3b0fe7d0590..9a38205cb13 100644 --- a/test/jdk/java/io/FileInputStream/ReadXBytes.java +++ b/test/jdk/java/io/FileInputStream/ReadXBytes.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2021, 2024, Oracle and/or its affiliates. All rights reserved. * 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 @@ public class ReadXBytes { private static final Random RND = RandomFactory.getRandom(); public static void main(String args[]) throws IOException { - File dir = new File(System.getProperty("test.src", ".")); + File dir = new File("."); dir.deleteOnExit(); File empty = File.createTempFile("foo", "bar", dir); diff --git a/test/jdk/java/io/InputStreamReader/ReadCharBuffer.java b/test/jdk/java/io/InputStreamReader/ReadCharBuffer.java index 44abf3cb30d..8a4094c512a 100644 --- a/test/jdk/java/io/InputStreamReader/ReadCharBuffer.java +++ b/test/jdk/java/io/InputStreamReader/ReadCharBuffer.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2021, 2022, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,7 +23,7 @@ /* * @test - * @bug 4926314 + * @bug 4926314 8287003 * @summary Test for InputStreamReader#read(CharBuffer). * @run testng ReadCharBuffer */ @@ -38,9 +38,11 @@ import java.io.Reader; import java.nio.ByteBuffer; import java.nio.CharBuffer; +import java.nio.charset.CodingErrorAction; import java.util.Arrays; import static java.nio.charset.StandardCharsets.US_ASCII; +import static java.nio.charset.StandardCharsets.UTF_8; import static org.testng.Assert.assertEquals; public class ReadCharBuffer { @@ -56,6 +58,13 @@ public Object[][] createBuffers() { }; } + private void fillBuffer(CharBuffer buffer) { + char[] filler = new char[BUFFER_SIZE]; + Arrays.fill(filler, 'x'); + buffer.put(filler); + buffer.clear(); + } + @Test(dataProvider = "buffers") public void read(CharBuffer buffer) throws IOException { fillBuffer(buffer); @@ -78,11 +87,19 @@ public void read(CharBuffer buffer) throws IOException { assertEquals(buffer.toString(), "xABCDEFxGHIJKLMNxxxxxxxx"); } - private void fillBuffer(CharBuffer buffer) { - char[] filler = new char[BUFFER_SIZE]; - Arrays.fill(filler, 'x'); - buffer.put(filler); - buffer.clear(); + @Test + public void readLeftover() throws IOException { + byte[] b = new byte[] {'a', 'b', (byte) 0xC2}; + ByteArrayInputStream bais = new ByteArrayInputStream(b); + InputStreamReader r = new InputStreamReader(bais, + UTF_8.newDecoder().onMalformedInput(CodingErrorAction.IGNORE)); + int n = r.read(); + assertEquals((char)n, 'a'); + char[] c = new char[3]; + n = r.read(c, 0, 3); + assertEquals(n, 1); + assertEquals((char)c[0], 'b'); + n = r.read(); + assertEquals(n, -1); } - } diff --git a/test/jdk/java/io/Serializable/class/NonSerializableTest.java b/test/jdk/java/io/Serializable/class/NonSerializableTest.java index b2ac4e933cb..fa81b3e3ce7 100644 --- a/test/jdk/java/io/Serializable/class/NonSerializableTest.java +++ b/test/jdk/java/io/Serializable/class/NonSerializableTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -102,7 +102,7 @@ public void test(String[] args) throws Exception { Paths.get(System.getProperty("user.dir"))); assertTrue(b, "Compilation failed"); String params[] = Arrays.copyOfRange(args, 1, args.length); - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(params); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(params); Process p = ProcessTools.startProcess("Serializable Test", pb); int exitValue = p.waitFor(); assertEquals(exitValue, 0, "Test failed"); diff --git a/test/jdk/java/io/Serializable/evolution/RenamePackage/RenamePackageTest.java b/test/jdk/java/io/Serializable/evolution/RenamePackage/RenamePackageTest.java index faccc09bb4b..bf51dc66c54 100644 --- a/test/jdk/java/io/Serializable/evolution/RenamePackage/RenamePackageTest.java +++ b/test/jdk/java/io/Serializable/evolution/RenamePackage/RenamePackageTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2023, Oracle and/or its affiliates. All rights reserved. * 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,7 +81,7 @@ private static void setup() throws Exception { } private static void runTestSerialDriver() throws Exception { - ProcessBuilder pb = ProcessTools.createTestJvm( + ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder( "-classpath", SHARE.toString() + File.pathSeparator @@ -93,7 +93,7 @@ private static void runTestSerialDriver() throws Exception { } private static void runInstallSerialDriver() throws Exception { - ProcessBuilder pb = ProcessTools.createTestJvm( + ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder( "-classpath", SHARE.toString() + File.pathSeparator diff --git a/test/jdk/java/lang/ClassLoader/GetSystemPackage.java b/test/jdk/java/lang/ClassLoader/GetSystemPackage.java index 25967bca620..2af81f3c416 100644 --- a/test/jdk/java/lang/ClassLoader/GetSystemPackage.java +++ b/test/jdk/java/lang/ClassLoader/GetSystemPackage.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -118,7 +118,7 @@ private static void buildJar(String name, Manifest man) throws Exception { private static void runSubProcess(String messageOnError, String ... args) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(args); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(args); int res = pb.directory(tmpFolder).inheritIO().start().waitFor(); if (res != 0) { throw new RuntimeException(messageOnError); diff --git a/test/jdk/java/lang/ProcessBuilder/Basic.java b/test/jdk/java/lang/ProcessBuilder/Basic.java index f8dfd4f9b68..548967ac099 100644 --- a/test/jdk/java/lang/ProcessBuilder/Basic.java +++ b/test/jdk/java/lang/ProcessBuilder/Basic.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -38,6 +38,7 @@ * @summary Basic tests for Process and Environment Variable code * @modules java.base/java.lang:open * @requires !vm.musl + * @requires vm.flagless * @library /test/lib * @run main/othervm/native/timeout=300 -Djava.security.manager=allow Basic * @run main/othervm/native/timeout=300 -Djava.security.manager=allow -Djdk.lang.Process.launchMechanism=fork Basic diff --git a/test/jdk/java/lang/ProcessBuilder/InheritIOTest.java b/test/jdk/java/lang/ProcessBuilder/InheritIOTest.java index 340507cb37b..a372eeefbf8 100644 --- a/test/jdk/java/lang/ProcessBuilder/InheritIOTest.java +++ b/test/jdk/java/lang/ProcessBuilder/InheritIOTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2020, 2023, Oracle and/or its affiliates. All rights reserved. * 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,6 +25,7 @@ * @test * @bug 8023130 8166026 * @summary Unit test for java.lang.ProcessBuilder inheritance of standard output and standard error streams + * @requires vm.flagless * @library /test/lib * @build jdk.test.lib.process.* * @run testng InheritIOTest @@ -54,7 +55,7 @@ public Object[][] testCases() { @Test(dataProvider = "testCases") public void testInheritWithoutRedirect(List arguments) throws Throwable { - ProcessBuilder processBuilder = ProcessTools.createJavaProcessBuilder(arguments); + ProcessBuilder processBuilder = ProcessTools.createLimitedTestJavaProcessBuilder(arguments); OutputAnalyzer outputAnalyzer = ProcessTools.executeCommand(processBuilder); outputAnalyzer.shouldHaveExitValue(0); assertEquals(outputAnalyzer.getStdout(), EXPECTED_RESULT_STDOUT); diff --git a/test/jdk/java/lang/ProcessBuilder/JspawnhelperProtocol.java b/test/jdk/java/lang/ProcessBuilder/JspawnhelperProtocol.java index ca257a96430..d31905ccc63 100644 --- a/test/jdk/java/lang/ProcessBuilder/JspawnhelperProtocol.java +++ b/test/jdk/java/lang/ProcessBuilder/JspawnhelperProtocol.java @@ -27,6 +27,7 @@ * @bug 8307990 * @requires (os.family == "linux") | (os.family == "aix") | (os.family == "mac") * @requires vm.debug + * @requires vm.flagless * @library /test/lib * @run main/othervm/timeout=300 JspawnhelperProtocol */ @@ -78,9 +79,9 @@ private static void parentCode(String arg) throws IOException, InterruptedExcept private static void normalExec() throws Exception { ProcessBuilder pb; - pb = ProcessTools.createJavaProcessBuilder("-Djdk.lang.Process.launchMechanism=posix_spawn", - "JspawnhelperProtocol", - "normalExec"); + pb = ProcessTools.createLimitedTestJavaProcessBuilder("-Djdk.lang.Process.launchMechanism=posix_spawn", + "JspawnhelperProtocol", + "normalExec"); pb.inheritIO(); Process p = pb.start(); if (!p.waitFor(TIMEOUT, TimeUnit.SECONDS)) { @@ -93,9 +94,9 @@ private static void normalExec() throws Exception { private static void simulateCrashInChild(int stage) throws Exception { ProcessBuilder pb; - pb = ProcessTools.createJavaProcessBuilder("-Djdk.lang.Process.launchMechanism=posix_spawn", - "JspawnhelperProtocol", - "simulateCrashInChild" + stage); + pb = ProcessTools.createLimitedTestJavaProcessBuilder("-Djdk.lang.Process.launchMechanism=posix_spawn", + "JspawnhelperProtocol", + "simulateCrashInChild" + stage); pb.environment().put(ENV_KEY, Integer.toString(stage)); Process p = pb.start(); @@ -126,9 +127,9 @@ private static void simulateCrashInChild(int stage) throws Exception { private static void simulateCrashInParent(int stage) throws Exception { ProcessBuilder pb; - pb = ProcessTools.createJavaProcessBuilder("-Djdk.lang.Process.launchMechanism=posix_spawn", - "JspawnhelperProtocol", - "simulateCrashInParent" + stage); + pb = ProcessTools.createLimitedTestJavaProcessBuilder("-Djdk.lang.Process.launchMechanism=posix_spawn", + "JspawnhelperProtocol", + "simulateCrashInParent" + stage); pb.environment().put(ENV_KEY, Integer.toString(stage)); Process p = pb.start(); @@ -172,9 +173,9 @@ private static void simulateCrashInParent(int stage) throws Exception { private static void simulateTruncatedWriteInParent(int stage) throws Exception { ProcessBuilder pb; - pb = ProcessTools.createJavaProcessBuilder("-Djdk.lang.Process.launchMechanism=posix_spawn", - "JspawnhelperProtocol", - "simulateTruncatedWriteInParent" + stage); + pb = ProcessTools.createLimitedTestJavaProcessBuilder("-Djdk.lang.Process.launchMechanism=posix_spawn", + "JspawnhelperProtocol", + "simulateTruncatedWriteInParent" + stage); pb.environment().put(ENV_KEY, Integer.toString(stage)); Process p = pb.start(); diff --git a/test/jdk/java/lang/ProcessBuilder/ReaderWriterTest.java b/test/jdk/java/lang/ProcessBuilder/ReaderWriterTest.java index efe4f842c7f..a73451417bf 100644 --- a/test/jdk/java/lang/ProcessBuilder/ReaderWriterTest.java +++ b/test/jdk/java/lang/ProcessBuilder/ReaderWriterTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2021, 2023, Oracle and/or its affiliates. All rights reserved. * 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,6 +49,7 @@ /* * @test + * @requires vm.flagless * @library /test/lib * @build jdk.test.lib.process.ProcessTools jdk.test.lib.hexdump.HexPrinter * @run testng ReaderWriterTest @@ -82,7 +83,7 @@ void testCaseNativeEncoding() throws IOException { Charset cs = Charset.forName(nativeEncoding); System.out.println("Native.encoding Charset: " + cs); - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("ReaderWriterTest$ChildWithCharset"); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("ReaderWriterTest$ChildWithCharset"); Process p = pb.start(); writeTestChars(p.outputWriter()); checkReader(p.inputReader(), cs, "Out"); @@ -121,7 +122,7 @@ void testRedirects() throws IOException { // 2: redirectErrorStream(true); no redirect of errorOutput // 3: redirectErrorStream(true); redirect of errorOutput to a file - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("ReaderWriterTest$ChildWithCharset"); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("ReaderWriterTest$ChildWithCharset"); pb.redirectInput(inPath.toFile()); pb.redirectOutput(outPath.toFile()); if (errType == 1 || errType == 3) { @@ -191,7 +192,7 @@ void testCase(String encoding) throws IOException { } String cleanCSName = cleanCharsetName(cs); - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-Dsun.stdout.encoding=" + cleanCSName, // Encode in the child using the charset "-Dsun.stderr.encoding=" + cleanCSName, "ReaderWriterTest$ChildWithCharset"); @@ -217,7 +218,7 @@ void testCase(String encoding) throws IOException { @Test void testNullCharsets() throws IOException { // Launch a child; its behavior is not interesting and is ignored - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "ReaderWriterTest$ChildWithCharset"); Process p = pb.start(); @@ -263,7 +264,7 @@ void testIllegalArgCharsets() throws IOException { : StandardCharsets.UTF_8; // Launch a child; its behavior is not interesting and is ignored - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "ReaderWriterTest$ChildWithCharset"); Process p = pb.start(); diff --git a/test/jdk/java/lang/ProcessBuilder/SkipTest.java b/test/jdk/java/lang/ProcessBuilder/SkipTest.java index 329e3a1affb..cad2adaa6fe 100644 --- a/test/jdk/java/lang/ProcessBuilder/SkipTest.java +++ b/test/jdk/java/lang/ProcessBuilder/SkipTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -24,6 +24,7 @@ /* * @test * @bug 8155808 + * @requires vm.flagless * @run main SkipTest * @summary verify skip method of Process Input Stream */ diff --git a/test/jdk/java/lang/ProcessHandle/OnExitTest.java b/test/jdk/java/lang/ProcessHandle/OnExitTest.java index 7c1855772ec..b75775b51a2 100644 --- a/test/jdk/java/lang/ProcessHandle/OnExitTest.java +++ b/test/jdk/java/lang/ProcessHandle/OnExitTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2023, Oracle and/or its affiliates. All rights reserved. * 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,7 @@ /* * @test + * @requires vm.flagless * @library /test/lib * @modules jdk.management * @build jdk.test.lib.Utils @@ -95,6 +96,24 @@ public static void test1() { */ @Test public static void test2() { + + // Please note (JDK-8284282): + // + // On Unix, this test relies on the ability of the system to adopt orphaned processes and + // reap them in a timely fashion. In other words, the ability to prevent orphans from becoming + // zombies. + // + // Therefore, on misconfigured or broken systems, this test may fail. These failures will manifest + // as timeouts. The failures depend on timing: they may not happen at all, be intermittent or + // constant. + // + // That will rarely be a problem on bare-metal systems but may be more common when running in + // Docker. Misconfigured Docker instances may run with an initial process unable to reap. One + // infamous example would be running jtreg tests inside a Docker via Jenkins CI. + // + // This is quite difficult - and inefficient - to fix inside this test, and rather easy to + // avoid. For a detailed analysis, as well as proposed workarounds, please see JDK-8284282. + // ProcessHandle procHandle = null; try { ConcurrentHashMap processes = new ConcurrentHashMap<>(); diff --git a/test/jdk/java/lang/ProcessHandle/TreeTest.java b/test/jdk/java/lang/ProcessHandle/TreeTest.java index 854734c1c86..57dfd47a619 100644 --- a/test/jdk/java/lang/ProcessHandle/TreeTest.java +++ b/test/jdk/java/lang/ProcessHandle/TreeTest.java @@ -44,6 +44,7 @@ /* * @test + * @requires vm.flagless * @library /test/lib * @modules java.base/jdk.internal.misc * jdk.management diff --git a/test/jdk/java/lang/RuntimeTests/exec/ArgWithSpaceAndFinalBackslash.java b/test/jdk/java/lang/RuntimeTests/exec/ArgWithSpaceAndFinalBackslash.java index ed74576abbd..c5edf6c1212 100644 --- a/test/jdk/java/lang/RuntimeTests/exec/ArgWithSpaceAndFinalBackslash.java +++ b/test/jdk/java/lang/RuntimeTests/exec/ArgWithSpaceAndFinalBackslash.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2023, Oracle and/or its affiliates. All rights reserved. * 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,6 +25,7 @@ * @bug 4794652 * @summary Ensure that a command argument that contains a space and a final * backslash is handled correctly + * @requires vm.flagless */ import java.io.*; diff --git a/test/jdk/java/lang/RuntimeTests/exec/Duped.java b/test/jdk/java/lang/RuntimeTests/exec/Duped.java index d86fbdae124..f2e29cf0e04 100644 --- a/test/jdk/java/lang/RuntimeTests/exec/Duped.java +++ b/test/jdk/java/lang/RuntimeTests/exec/Duped.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -24,6 +24,7 @@ /* @test @bug 4180429 @summary Lossage in dup2 if System.in is closed. + @requires vm.flagless @run main/othervm Duped */ diff --git a/test/jdk/java/lang/RuntimeTests/exec/ExecWithLotsOfArgs.java b/test/jdk/java/lang/RuntimeTests/exec/ExecWithLotsOfArgs.java index 26267e0d6ab..454e468ce26 100644 --- a/test/jdk/java/lang/RuntimeTests/exec/ExecWithLotsOfArgs.java +++ b/test/jdk/java/lang/RuntimeTests/exec/ExecWithLotsOfArgs.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2023, Oracle and/or its affiliates. All rights reserved. * 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,6 +25,7 @@ @bug 4033560 @summary 4033560 limited args of exec to 198 on Solaris. We check that we can actually exec more args than that. + @requires vm.flagless @author Anand Palaniswamy @run main/othervm ExecWithLotsOfArgs */ diff --git a/test/jdk/java/lang/RuntimeTests/exec/ExitValue.java b/test/jdk/java/lang/RuntimeTests/exec/ExitValue.java index 03f56240cd4..96b6ed9d5f9 100644 --- a/test/jdk/java/lang/RuntimeTests/exec/ExitValue.java +++ b/test/jdk/java/lang/RuntimeTests/exec/ExitValue.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 2023, Oracle and/or its affiliates. All rights reserved. * 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,6 +25,7 @@ * @test * @bug 4680945 4873419 * @summary Check process exit code + * @requires vm.flagless * @author kladko, Martin Buchholz */ diff --git a/test/jdk/java/lang/RuntimeTests/exec/SetCwd.java b/test/jdk/java/lang/RuntimeTests/exec/SetCwd.java index 347c4d0eae3..c7bfaae33b4 100644 --- a/test/jdk/java/lang/RuntimeTests/exec/SetCwd.java +++ b/test/jdk/java/lang/RuntimeTests/exec/SetCwd.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2023, Oracle and/or its affiliates. All rights reserved. * 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 @@ * @summary Basic functional test for * Runtime.exec(String[] command, String[] env, File path) and * Runtime.exec(String command, String[] env, File path). - * + * @requires vm.flagless * @library /test/lib * @run testng/othervm SetCwd */ diff --git a/test/jdk/java/lang/RuntimeTests/shutdown/ShutdownInterruptedMain.java b/test/jdk/java/lang/RuntimeTests/shutdown/ShutdownInterruptedMain.java index e141fc35212..85040e9548e 100644 --- a/test/jdk/java/lang/RuntimeTests/shutdown/ShutdownInterruptedMain.java +++ b/test/jdk/java/lang/RuntimeTests/shutdown/ShutdownInterruptedMain.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2023, Oracle and/or its affiliates. All rights reserved. * 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,14 +31,14 @@ */ import jdk.test.lib.process.OutputAnalyzer; -import static jdk.test.lib.process.ProcessTools.createTestJvm; +import static jdk.test.lib.process.ProcessTools.createTestJavaProcessBuilder; import static jdk.test.lib.process.ProcessTools.executeProcess; public class ShutdownInterruptedMain { public static void main(String[] args) throws Exception { if (args.length > 0) { - ProcessBuilder pb = createTestJvm("ShutdownInterruptedMain"); + ProcessBuilder pb = createTestJavaProcessBuilder("ShutdownInterruptedMain"); OutputAnalyzer output = executeProcess(pb); output.shouldContain("Shutdown Hook"); output.shouldHaveExitValue(0); diff --git a/test/jdk/java/lang/SecurityManager/modules/CustomSecurityManagerTest.java b/test/jdk/java/lang/SecurityManager/modules/CustomSecurityManagerTest.java index bb346f04b2a..92b9e44f892 100644 --- a/test/jdk/java/lang/SecurityManager/modules/CustomSecurityManagerTest.java +++ b/test/jdk/java/lang/SecurityManager/modules/CustomSecurityManagerTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -64,7 +64,7 @@ public Object[][] testCases() { @Test(dataProvider = "testCases") public void testProvider(List args) throws Throwable { - ProcessBuilder processBuilder = ProcessTools.createJavaProcessBuilder(args); + ProcessBuilder processBuilder = ProcessTools.createLimitedTestJavaProcessBuilder(args); OutputAnalyzer outputAnalyzer = ProcessTools.executeCommand(processBuilder); outputAnalyzer.shouldHaveExitValue(0); } diff --git a/test/jdk/java/lang/StackWalker/CallerFromMain.java b/test/jdk/java/lang/StackWalker/CallerFromMain.java index 3cb599c6859..86e7cfb7043 100644 --- a/test/jdk/java/lang/StackWalker/CallerFromMain.java +++ b/test/jdk/java/lang/StackWalker/CallerFromMain.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2023, Oracle and/or its affiliates. All rights reserved. * 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,7 +37,7 @@ public class CallerFromMain { private static final StackWalker sw = StackWalker.getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE); public static void main(String[] args) throws Exception { if (args.length > 0) { - ProcessBuilder pb = ProcessTools.createTestJvm("CallerFromMain"); + ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder("CallerFromMain"); OutputAnalyzer output = ProcessTools.executeProcess(pb); System.out.println(output.getOutput()); output.shouldHaveExitValue(0); diff --git a/test/jdk/java/lang/System/MacEncoding/MacJNUEncoding.java b/test/jdk/java/lang/System/MacEncoding/MacJNUEncoding.java index 24cc9adab16..078dccc4d07 100644 --- a/test/jdk/java/lang/System/MacEncoding/MacJNUEncoding.java +++ b/test/jdk/java/lang/System/MacEncoding/MacJNUEncoding.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -49,7 +49,7 @@ public static void main(String[] args) throws Exception { final String locale = args[2]; System.out.println("Running test for locale: " + locale); - ProcessBuilder pb = ProcessTools.createTestJvm( + ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder( ExpectedEncoding.class.getName(), args[0], args[1]); Map env = pb.environment(); env.put("LANG", locale); diff --git a/test/jdk/java/lang/Thread/UncaughtExceptionsTest.java b/test/jdk/java/lang/Thread/UncaughtExceptionsTest.java index 552dfd3253a..58005c11162 100644 --- a/test/jdk/java/lang/Thread/UncaughtExceptionsTest.java +++ b/test/jdk/java/lang/Thread/UncaughtExceptionsTest.java @@ -65,7 +65,7 @@ public Object[][] testCases() { @Test(dataProvider = "testCases") public void test(String className, int exitValue, String stdOutMatch, String stdErrMatch) throws Throwable { - ProcessBuilder processBuilder = ProcessTools.createJavaProcessBuilder(String.format("UncaughtExitSimulator$%s",className)); + ProcessBuilder processBuilder = ProcessTools.createLimitedTestJavaProcessBuilder(String.format("UncaughtExitSimulator$%s",className)); OutputAnalyzer outputAnalyzer = ProcessTools.executeCommand(processBuilder); outputAnalyzer.shouldHaveExitValue(exitValue); outputAnalyzer.stderrShouldMatch(stdErrMatch); diff --git a/test/jdk/java/lang/annotation/LoaderLeakTest.java b/test/jdk/java/lang/annotation/LoaderLeakTest.java index e5e0a8d61c4..ed230d8df0e 100644 --- a/test/jdk/java/lang/annotation/LoaderLeakTest.java +++ b/test/jdk/java/lang/annotation/LoaderLeakTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2004, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2004, 2023, Oracle and/or its affiliates. All rights reserved. * 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,7 +55,7 @@ public void testWithReadingAnnotations() throws Throwable { } private void runJavaProcessExpectSuccessExitCode(String ... command) throws Throwable { - var processBuilder = ProcessTools.createJavaProcessBuilder(command) + var processBuilder = ProcessTools.createLimitedTestJavaProcessBuilder(command) .directory(Paths.get(Utils.TEST_CLASSES).toFile()); ProcessTools.executeCommand(processBuilder).shouldHaveExitValue(0); } diff --git a/test/jdk/java/lang/instrument/DaemonThread/TestDaemonThreadLauncher.java b/test/jdk/java/lang/instrument/DaemonThread/TestDaemonThreadLauncher.java index 728fc5d17ab..697ca7366a0 100644 --- a/test/jdk/java/lang/instrument/DaemonThread/TestDaemonThreadLauncher.java +++ b/test/jdk/java/lang/instrument/DaemonThread/TestDaemonThreadLauncher.java @@ -1,6 +1,6 @@ /* * Copyright 2014 Goldman Sachs. - * Copyright (c) 2014, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -29,7 +29,7 @@ public class TestDaemonThreadLauncher { public static void main(String args[]) throws Exception { for(int i=0; i<50; i++) { - ProcessBuilder pb = ProcessTools.createTestJvm("-javaagent:DummyAgent.jar", "TestDaemonThread", "."); + ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder("-javaagent:DummyAgent.jar", "TestDaemonThread", "."); OutputAnalyzer analyzer = ProcessTools.executeProcess(pb); analyzer.shouldNotContain("ASSERTION FAILED"); analyzer.shouldHaveExitValue(0); diff --git a/test/jdk/java/lang/instrument/NegativeAgentRunner.java b/test/jdk/java/lang/instrument/NegativeAgentRunner.java index 1b7ff2f7335..9689c323114 100644 --- a/test/jdk/java/lang/instrument/NegativeAgentRunner.java +++ b/test/jdk/java/lang/instrument/NegativeAgentRunner.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2020, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -35,7 +35,7 @@ public static void main(String argv[]) throws Exception { } String agentClassName = argv[0]; String excepClassName = argv[1]; - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-javaagent:" + agentClassName + ".jar", "-Xmx128m", "-XX:-CreateCoredumpOnCrash", agentClassName); OutputAnalyzer output = new OutputAnalyzer(pb.start()); diff --git a/test/jdk/java/lang/instrument/PremainClass/PremainClassTest.java b/test/jdk/java/lang/instrument/PremainClass/PremainClassTest.java index b59b69d3c75..ecd284fe6e0 100644 --- a/test/jdk/java/lang/instrument/PremainClass/PremainClassTest.java +++ b/test/jdk/java/lang/instrument/PremainClass/PremainClassTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -44,7 +44,7 @@ public static void main(String[] a) throws Exception { System.getProperty("test.src"), System.getProperty("test.classes", ".")); - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( Utils.addTestJavaOpts(testArgs.split("\\s+"))); System.out.println("testjvm.cmd:" + Utils.getCommandLine(pb)); diff --git a/test/jdk/java/lang/instrument/modules/AppendToClassPathModuleTest.java b/test/jdk/java/lang/instrument/modules/AppendToClassPathModuleTest.java index 9eb3cff391b..1b0e1f50dd2 100644 --- a/test/jdk/java/lang/instrument/modules/AppendToClassPathModuleTest.java +++ b/test/jdk/java/lang/instrument/modules/AppendToClassPathModuleTest.java @@ -46,7 +46,7 @@ public class AppendToClassPathModuleTest { public static void main(String... args) throws Throwable { String modulepath = System.getProperty("test.module.path"); - // can't use ProcessTools.createJavaProcessBuilder as it always adds -cp + // can't use ProcessTools.createLimitedTestJavaProcessBuilder as it always adds -cp ProcessBuilder pb = new ProcessBuilder( JDKToolFinder.getTestJDKTool("java"), "-javaagent:Agent.jar", diff --git a/test/jdk/java/lang/invoke/condy/CondyNestedResolutionTest.java b/test/jdk/java/lang/invoke/condy/CondyNestedResolutionTest.java index b5dd8befa48..914e90650da 100644 --- a/test/jdk/java/lang/invoke/condy/CondyNestedResolutionTest.java +++ b/test/jdk/java/lang/invoke/condy/CondyNestedResolutionTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -44,7 +44,7 @@ */ public class CondyNestedResolutionTest { public static void main(String args[]) throws Throwable { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("CondyNestedResolution"); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("CondyNestedResolution"); OutputAnalyzer oa = new OutputAnalyzer(pb.start()); oa.shouldContain("StackOverflowError"); oa.shouldContain("bsm1arg"); diff --git a/test/jdk/java/net/InetAddress/ptr/Lookup.java b/test/jdk/java/net/InetAddress/ptr/Lookup.java index 2b7e5b56acc..8deaf866ec1 100644 --- a/test/jdk/java/net/InetAddress/ptr/Lookup.java +++ b/test/jdk/java/net/InetAddress/ptr/Lookup.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 2024, Oracle and/or its affiliates. All rights reserved. * 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,18 +41,15 @@ import java.io.IOException; import java.net.InetAddress; import java.net.UnknownHostException; -import java.util.List; import java.util.stream.Stream; import java.util.stream.Collectors; -import jdk.test.lib.JDKToolFinder; import jdk.test.lib.process.OutputAnalyzer; +import jdk.test.lib.process.ProcessTools; public class Lookup { private static final String HOST = "icann.org"; private static final String SKIP = "SKIP"; - private static final String CLASS_PATH = System.getProperty( - "test.class.path"); public static void main(String args[]) throws IOException { String addr = null; @@ -135,20 +132,16 @@ public static void main(String args[]) throws IOException { } static String lookupWithIPv4Prefer() throws IOException { - String java = JDKToolFinder.getTestJDKTool("java"); String testClz = Lookup.class.getName(); - List cmd = List.of(java, "-Djava.net.preferIPv4Stack=true", - "-cp", CLASS_PATH, testClz); - System.out.println("Executing: " + cmd); - return new OutputAnalyzer(new ProcessBuilder(cmd).start()).getOutput(); + ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder( + "-Djava.net.preferIPv4Stack=true", testClz); + return new OutputAnalyzer(pb.start()).getOutput(); } static String reverseWithIPv4Prefer(String addr) throws IOException { - String java = JDKToolFinder.getTestJDKTool("java"); String testClz = Lookup.class.getName(); - List cmd = List.of(java, "-Djava.net.preferIPv4Stack=true", - "-cp", CLASS_PATH, testClz, "reverse", addr); - System.out.println("Executing: " + cmd); - return new OutputAnalyzer(new ProcessBuilder(cmd).start()).getOutput(); + ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder( + "-Djava.net.preferIPv4Stack=true", testClz, "reverse", addr); + return new OutputAnalyzer(pb.start()).getOutput(); } } diff --git a/test/jdk/java/net/ServerSocket/AcceptCauseFileDescriptorLeak.java b/test/jdk/java/net/ServerSocket/AcceptCauseFileDescriptorLeak.java index 5c9e7bf6990..7626ec04c72 100644 --- a/test/jdk/java/net/ServerSocket/AcceptCauseFileDescriptorLeak.java +++ b/test/jdk/java/net/ServerSocket/AcceptCauseFileDescriptorLeak.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2006, 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2006, 2024, Oracle and/or its affiliates. All rights reserved. * 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,7 +31,8 @@ * can cause fd leak. * This test may fail intermittently if foreign processes will * try to establish connection to the test server socket. - * @requires (os.family != "windows") + * @requires os.family != "windows" + * @requires vm.flagless * @library /test/lib * @build jdk.test.lib.Utils * jdk.test.lib.Asserts diff --git a/test/jdk/java/net/ServerSocket/AcceptInheritHandle.java b/test/jdk/java/net/ServerSocket/AcceptInheritHandle.java index 81bf874f593..96f09e4e044 100644 --- a/test/jdk/java/net/ServerSocket/AcceptInheritHandle.java +++ b/test/jdk/java/net/ServerSocket/AcceptInheritHandle.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -34,10 +34,12 @@ import java.nio.channels.ServerSocketChannel; import java.util.ArrayList; import java.util.Arrays; +import java.util.Collections; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.function.Supplier; import jdk.test.lib.net.IPSupport; +import jdk.test.lib.process.ProcessTools; public class AcceptInheritHandle { @@ -95,16 +97,12 @@ static void test(ServerSocketProducer ssp, String... jvmArgs) throws Exception { System.out.println("\nStarting test for " + ssp.name()); List commands = new ArrayList<>(); - commands.add(JAVA); - for (String arg : jvmArgs) - commands.add(arg); - commands.add("-cp"); - commands.add(CLASSPATH); + Collections.addAll(commands, jvmArgs); commands.add("AcceptInheritHandle"); commands.add(ssp.name()); System.out.println("Executing: "+ commands); - ProcessBuilder pb = new ProcessBuilder(commands); + ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder(commands); pb.redirectError(ProcessBuilder.Redirect.INHERIT); Process serverProcess = pb.start(); DataInputStream dis = new DataInputStream(serverProcess.getInputStream()); diff --git a/test/jdk/java/net/URLClassLoader/getresourceasstream/TestDriver.java b/test/jdk/java/net/URLClassLoader/getresourceasstream/TestDriver.java index 526689e21ea..a7cfae09c3e 100644 --- a/test/jdk/java/net/URLClassLoader/getresourceasstream/TestDriver.java +++ b/test/jdk/java/net/URLClassLoader/getresourceasstream/TestDriver.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2024, Oracle and/or its affiliates. All rights reserved. * 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,7 +36,6 @@ * @run main/othervm TestDriver */ -import jdk.test.lib.JDKToolFinder; import jdk.test.lib.process.ProcessTools; import java.io.IOException; @@ -53,33 +52,33 @@ public static void main(String[] args) throws Throwable { Path userDir = Paths.get(System.getProperty("user.dir")); - String java = JDKToolFinder.getTestJDKTool("java"); String basename = userDir.getFileName().toString(); setup(userDir); ProcessBuilder[] tests = new ProcessBuilder[]{ - new ProcessBuilder( - java, TEST_NAME, "./" + ARCHIVE_NAME + ProcessTools.createTestJavaProcessBuilder( + TEST_NAME, + "./" + ARCHIVE_NAME ), - new ProcessBuilder( - java, "-cp", ".", + ProcessTools.createTestJavaProcessBuilder( + "-cp", ".", "-Djava.security.policy=file:./policy", "-Djava.security.manager", TEST_NAME, "./" + ARCHIVE_NAME ), - new ProcessBuilder( - java, "-cp", ".", + ProcessTools.createTestJavaProcessBuilder( + "-cp", ".", "-Djava.security.policy=file:./policy", "-Djava.security.manager", TEST_NAME, "./" + ARCHIVE_NAME ), - new ProcessBuilder( - java, "-cp", "..", + ProcessTools.createTestJavaProcessBuilder( + "-cp", "..", "-Djava.security.policy=file:../policy", "-Djava.security.manager", TEST_NAME, "../" + ARCHIVE_NAME ).directory(userDir.resolve("tmp").toFile()), - new ProcessBuilder( - java, "-cp", basename, + ProcessTools.createTestJavaProcessBuilder( + "-cp", basename, "-Djava.security.policy=file:" + basename + "/policy", "-Djava.security.manager", TEST_NAME, basename + "/" + ARCHIVE_NAME diff --git a/test/jdk/java/net/URLClassLoader/sealing/CheckSealedTest.java b/test/jdk/java/net/URLClassLoader/sealing/CheckSealedTest.java index b733b678871..cb474645e45 100644 --- a/test/jdk/java/net/URLClassLoader/sealing/CheckSealedTest.java +++ b/test/jdk/java/net/URLClassLoader/sealing/CheckSealedTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2024, Oracle and/or its affiliates. All rights reserved. * 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,6 +46,8 @@ import java.util.List; import static java.nio.file.StandardCopyOption.REPLACE_EXISTING; +import static jdk.test.lib.process.ProcessTools.createTestJavaProcessBuilder; +import static jdk.test.lib.process.ProcessTools.executeCommand; public class CheckSealedTest { private static final String ARCHIVE_NAME = "b.jar"; @@ -55,31 +57,30 @@ public static void main(String[] args) String baseDir = System.getProperty("user.dir") + File.separator; String javac = JDKToolFinder.getTestJDKTool("javac"); - String java = JDKToolFinder.getTestJDKTool("java"); setup(baseDir); String srcDir = System.getProperty("test.src"); String cp = srcDir + File.separator + "a" + File.pathSeparator + srcDir + File.separator + "b.jar" + File.pathSeparator + "."; + + // Compile + ProcessTools.executeCommand(javac, "-cp", cp, "-d", ".", + srcDir + File.separator + TEST_NAME + ".java"); + List allCMDs = List.of( - // Compile command - new String[]{ - javac, "-cp", cp, "-d", ".", - srcDir + File.separator + TEST_NAME + ".java" - }, // Run test the first time new String[]{ - java, "-cp", cp, TEST_NAME, "1" + "-cp", cp, TEST_NAME, "1" }, // Run test the second time new String[]{ - java, "-cp", cp, TEST_NAME, "2" + "-cp", cp, TEST_NAME, "2" } ); for (String[] cmd : allCMDs) { - ProcessTools.executeCommand(cmd) + executeCommand(createTestJavaProcessBuilder(cmd)) .outputTo(System.out) .errorTo(System.out) .shouldHaveExitValue(0); diff --git a/test/jdk/java/net/URLConnection/6212146/TestDriver.java b/test/jdk/java/net/URLConnection/6212146/TestDriver.java index d6bffb198de..5f474759031 100644 --- a/test/jdk/java/net/URLConnection/6212146/TestDriver.java +++ b/test/jdk/java/net/URLConnection/6212146/TestDriver.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2024, Oracle and/or its affiliates. All rights reserved. * 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,6 +27,7 @@ * @summary URLConnection.connect() fails on JAR Entry it creates * file handler leak * @library /test/lib + * @requires vm.flagless * @build jdk.test.lib.Utils * jdk.test.lib.Asserts * jdk.test.lib.JDKToolFinder diff --git a/test/jdk/java/net/URLConnection/ContentHandlers/ContentHandlersTest.java b/test/jdk/java/net/URLConnection/ContentHandlers/ContentHandlersTest.java index 49b2d7a6b64..b15d5aca8ec 100644 --- a/test/jdk/java/net/URLConnection/ContentHandlers/ContentHandlersTest.java +++ b/test/jdk/java/net/URLConnection/ContentHandlers/ContentHandlersTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,6 +21,8 @@ * questions. */ +import jdk.test.lib.process.ProcessTools; + import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; @@ -56,6 +58,7 @@ /* * @test * @bug 8064925 + * @library /test/lib * @summary Basic test for ContentHandler. Ensures discovery paths for content * handlers follow a particular order. */ @@ -268,14 +271,10 @@ private static Result java(Map properties, Collection classpath, String classname, String... args) { - String java = getJDKTool("java"); - - List commands = new ArrayList<>(); - commands.add(java); - commands.addAll(properties.entrySet() + List commands = properties.entrySet() .stream() .map(e -> "-D" + e.getKey() + "=" + e.getValue()) - .collect(Collectors.toList())); + .collect(Collectors.toList()); String cp = classpath.stream() .map(Path::toString) @@ -285,7 +284,7 @@ private static Result java(Map properties, commands.add(classname); commands.addAll(Arrays.asList(args)); - return run(new ProcessBuilder(commands)); + return run(ProcessTools.createTestJavaProcessBuilder(commands)); } private static Result run(ProcessBuilder b) { diff --git a/test/jdk/java/net/httpclient/AsFileDownloadTest.java b/test/jdk/java/net/httpclient/AsFileDownloadTest.java index 78da28ca28b..72131bfa03c 100644 --- a/test/jdk/java/net/httpclient/AsFileDownloadTest.java +++ b/test/jdk/java/net/httpclient/AsFileDownloadTest.java @@ -24,7 +24,6 @@ import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpHandler; import com.sun.net.httpserver.HttpServer; -import com.sun.net.httpserver.HttpsConfigurator; import com.sun.net.httpserver.HttpsServer; import java.io.IOException; import java.io.InputStream; @@ -51,6 +50,7 @@ import jdk.test.lib.net.SimpleSSLContext; import jdk.test.lib.util.FileUtils; import jdk.httpclient.test.lib.common.HttpServerAdapters; +import jdk.httpclient.test.lib.common.TestServerConfigurator; import jdk.httpclient.test.lib.http2.Http2TestServer; import jdk.httpclient.test.lib.http2.Http2TestExchange; import jdk.httpclient.test.lib.http2.Http2Handler; @@ -73,6 +73,7 @@ * @library /test/lib /test/jdk/java/net/httpclient/lib * @build jdk.httpclient.test.lib.http2.Http2TestServer jdk.test.lib.net.SimpleSSLContext * jdk.test.lib.Platform jdk.test.lib.util.FileUtils + * jdk.httpclient.test.lib.common.TestServerConfigurator * @run testng/othervm AsFileDownloadTest * @run testng/othervm/java.security.policy=AsFileDownloadTest.policy AsFileDownloadTest */ @@ -299,7 +300,7 @@ public void setup() throws Exception { httpURI = "http://" + serverAuthority(httpTestServer) + "/http1/afdt"; httpsTestServer = HttpsServer.create(sa, 0); - httpsTestServer.setHttpsConfigurator(new HttpsConfigurator(sslContext)); + httpsTestServer.setHttpsConfigurator(new TestServerConfigurator(sa.getAddress(), sslContext)); httpsTestServer.createContext("/https1/afdt", new Http1FileDispoHandler()); httpsURI = "https://" + serverAuthority(httpsTestServer) + "/https1/afdt"; diff --git a/test/jdk/java/net/httpclient/AuthFilterCacheTest.java b/test/jdk/java/net/httpclient/AuthFilterCacheTest.java index ecdf132f464..4561fc2a687 100644 --- a/test/jdk/java/net/httpclient/AuthFilterCacheTest.java +++ b/test/jdk/java/net/httpclient/AuthFilterCacheTest.java @@ -37,6 +37,7 @@ import com.sun.net.httpserver.HttpServer; import com.sun.net.httpserver.HttpsConfigurator; import com.sun.net.httpserver.HttpsServer; +import jdk.httpclient.test.lib.common.TestServerConfigurator; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.DataProvider; @@ -53,7 +54,7 @@ * @summary AuthenticationFilter.Cache::remove may throw ConcurrentModificationException * @library /test/lib /test/jdk/java/net/httpclient/lib * @build jdk.httpclient.test.lib.common.HttpServerAdapters jdk.test.lib.net.SimpleSSLContext - * DigestEchoServer + * DigestEchoServer jdk.httpclient.test.lib.common.TestServerConfigurator * @run testng/othervm -Dtest.requiresHost=true * -Djdk.httpclient.HttpClient.log=headers * -Djdk.internal.httpclient.debug=false @@ -131,7 +132,7 @@ public void setUp() throws Exception { // HTTPS/1.1 HttpsServer sserver1 = HttpsServer.create(sa, 100); sserver1.setExecutor(executor); - sserver1.setHttpsConfigurator(new HttpsConfigurator(context)); + sserver1.setHttpsConfigurator(new TestServerConfigurator(sa.getAddress(), context)); https1Server = HttpTestServer.of(sserver1); https1Server.addHandler(new TestHandler(), "/AuthFilterCacheTest/https1/"); https1Server.start(); diff --git a/test/jdk/java/net/httpclient/ConcurrentResponses.java b/test/jdk/java/net/httpclient/ConcurrentResponses.java index ad1af440b1d..74795a431ff 100644 --- a/test/jdk/java/net/httpclient/ConcurrentResponses.java +++ b/test/jdk/java/net/httpclient/ConcurrentResponses.java @@ -28,6 +28,7 @@ * unprocessed HTTP data * @library /test/lib /test/jdk/java/net/httpclient/lib * @build jdk.httpclient.test.lib.http2.Http2TestServer jdk.test.lib.net.SimpleSSLContext + * jdk.httpclient.test.lib.common.TestServerConfigurator * @run testng/othervm * -Djdk.httpclient.HttpClient.log=headers,errors,channel * ConcurrentResponses @@ -51,7 +52,6 @@ import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpHandler; import com.sun.net.httpserver.HttpServer; -import com.sun.net.httpserver.HttpsConfigurator; import com.sun.net.httpserver.HttpsServer; import java.net.http.HttpClient; import java.net.http.HttpRequest; @@ -60,6 +60,8 @@ import java.net.http.HttpResponse.BodyHandlers; import java.net.http.HttpResponse.BodySubscriber; import java.net.http.HttpResponse.BodySubscribers; + +import jdk.httpclient.test.lib.common.TestServerConfigurator; import jdk.httpclient.test.lib.common.HttpServerAdapters; import jdk.httpclient.test.lib.http2.Http2TestServer; import jdk.httpclient.test.lib.http2.Http2TestExchange; @@ -267,7 +269,7 @@ public void setup() throws Exception { httpChunkedURI = "http://" + serverAuthority(httpTestServer) + "/http1/chunked"; httpsTestServer = HttpsServer.create(sa, 0); - httpsTestServer.setHttpsConfigurator(new HttpsConfigurator(sslContext)); + httpsTestServer.setHttpsConfigurator(new TestServerConfigurator(sa.getAddress(), sslContext)); httpsTestServer.createContext("/https1/fixed", new Http1FixedHandler()); httpsFixedURI = "https://" + serverAuthority(httpsTestServer) + "/https1/fixed"; httpsTestServer.createContext("/https1/chunked", new Http1ChunkedHandler()); diff --git a/test/jdk/java/net/httpclient/CustomResponseSubscriber.java b/test/jdk/java/net/httpclient/CustomResponseSubscriber.java index e0bee8cc74f..be71278a450 100644 --- a/test/jdk/java/net/httpclient/CustomResponseSubscriber.java +++ b/test/jdk/java/net/httpclient/CustomResponseSubscriber.java @@ -26,6 +26,7 @@ * @summary Tests response body subscribers's onComplete is not invoked before onSubscribe * @library /test/lib /test/jdk/java/net/httpclient/lib * @build jdk.test.lib.net.SimpleSSLContext jdk.httpclient.test.lib.http2.Http2TestServer + * jdk.httpclient.test.lib.common.TestServerConfigurator * @run testng/othervm CustomResponseSubscriber */ @@ -43,7 +44,6 @@ import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpHandler; import com.sun.net.httpserver.HttpServer; -import com.sun.net.httpserver.HttpsConfigurator; import com.sun.net.httpserver.HttpsServer; import java.net.http.HttpClient; import java.net.http.HttpHeaders; @@ -52,6 +52,8 @@ import java.net.http.HttpResponse.BodyHandler; import java.net.http.HttpResponse.BodySubscriber; import java.net.http.HttpResponse.BodySubscribers; + +import jdk.httpclient.test.lib.common.TestServerConfigurator; import jdk.httpclient.test.lib.http2.Http2TestServer; import jdk.httpclient.test.lib.http2.Http2TestExchange; import jdk.httpclient.test.lib.http2.Http2Handler; @@ -200,7 +202,7 @@ public void setup() throws Exception { httpURI_chunk = "http://" + serverAuthority(httpTestServer) + "/http1/chunk"; httpsTestServer = HttpsServer.create(sa, 0); - httpsTestServer.setHttpsConfigurator(new HttpsConfigurator(sslContext)); + httpsTestServer.setHttpsConfigurator(new TestServerConfigurator(sa.getAddress(), sslContext)); httpsTestServer.createContext("/https1/fixed", h1_fixedLengthHandler); httpsTestServer.createContext("/https1/chunk", h1_chunkHandler); httpsURI_fixed = "https://" + serverAuthority(httpsTestServer) + "/https1/fixed"; diff --git a/test/jdk/java/net/httpclient/ExpectContinue.java b/test/jdk/java/net/httpclient/ExpectContinue.java index f3bed36c75c..43c65781413 100644 --- a/test/jdk/java/net/httpclient/ExpectContinue.java +++ b/test/jdk/java/net/httpclient/ExpectContinue.java @@ -24,17 +24,16 @@ /* * @test * @summary Basic test for Expect 100-Continue ( HTTP/1.1 only ) - * @modules java.net.http + * @library /test/lib /test/jdk/java/net/httpclient/lib + * @build jdk.test.lib.net.SimpleSSLContext jdk.httpclient.test.lib.common.TestServerConfigurator + * @modules java.net.http/jdk.internal.net.http.common * jdk.httpserver - * @library /test/lib - * @build jdk.test.lib.net.SimpleSSLContext * @run testng/othervm ExpectContinue */ import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpHandler; import com.sun.net.httpserver.HttpServer; -import com.sun.net.httpserver.HttpsConfigurator; import com.sun.net.httpserver.HttpsServer; import java.io.IOException; import java.io.InputStream; @@ -49,6 +48,8 @@ import java.net.http.HttpResponse.BodyHandlers; import java.util.List; import javax.net.ssl.SSLContext; + +import jdk.httpclient.test.lib.common.TestServerConfigurator; import jdk.test.lib.net.SimpleSSLContext; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeTest; @@ -148,7 +149,7 @@ public void setup() throws Exception { httpURI = "http://" + serverAuthority(httpTestServer) + "/http1/ec"; httpsTestServer = HttpsServer.create(sa, 0); - httpsTestServer.setHttpsConfigurator(new HttpsConfigurator(sslContext)); + httpsTestServer.setHttpsConfigurator(new TestServerConfigurator(sa.getAddress(), sslContext)); httpsTestServer.createContext("/https1/ec", new Http1ExpectContinueHandler()); httpsURI = "https://" + serverAuthority(httpsTestServer) + "/https1/ec"; diff --git a/test/jdk/java/net/httpclient/HttpRedirectTest.java b/test/jdk/java/net/httpclient/HttpRedirectTest.java index 0cfb009adbf..dedcc36dda7 100644 --- a/test/jdk/java/net/httpclient/HttpRedirectTest.java +++ b/test/jdk/java/net/httpclient/HttpRedirectTest.java @@ -20,9 +20,8 @@ * or visit www.oracle.com if you need additional information or have any * questions. */ -import com.sun.net.httpserver.HttpServer; -import com.sun.net.httpserver.HttpsConfigurator; import com.sun.net.httpserver.HttpsServer; +import jdk.httpclient.test.lib.common.TestServerConfigurator; import jdk.test.lib.net.SimpleSSLContext; import org.testng.annotations.BeforeClass; import org.testng.annotations.AfterClass; @@ -60,7 +59,6 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import jdk.httpclient.test.lib.common.HttpServerAdapters; -import jdk.httpclient.test.lib.http2.Http2TestServer; /** * @test @@ -69,6 +67,7 @@ * @library /test/lib /test/jdk/java/net/httpclient/lib * @build jdk.test.lib.net.SimpleSSLContext DigestEchoServer HttpRedirectTest * jdk.httpclient.test.lib.common.HttpServerAdapters + * jdk.httpclient.test.lib.common.TestServerConfigurator * @run testng/othervm -Dtest.requiresHost=true * -Djdk.httpclient.HttpClient.log=headers * -Djdk.internal.httpclient.debug=false @@ -175,7 +174,7 @@ public void setUp() throws Exception { // HTTPS/1.1 HttpsServer sserver1 = HttpsServer.create(sa, 100); sserver1.setExecutor(executor); - sserver1.setHttpsConfigurator(new HttpsConfigurator(context)); + sserver1.setHttpsConfigurator(new TestServerConfigurator(sa.getAddress(), context)); https1Server = HttpTestServer.of(sserver1); https1Server.addHandler(new HttpTestRedirectHandler("https", https1Server), "/HttpRedirectTest/https1/"); diff --git a/test/jdk/java/net/httpclient/HttpSlowServerTest.java b/test/jdk/java/net/httpclient/HttpSlowServerTest.java index a1c36e9dc16..85db9bba563 100644 --- a/test/jdk/java/net/httpclient/HttpSlowServerTest.java +++ b/test/jdk/java/net/httpclient/HttpSlowServerTest.java @@ -20,9 +20,8 @@ * or visit www.oracle.com if you need additional information or have any * questions. */ -import com.sun.net.httpserver.HttpServer; -import com.sun.net.httpserver.HttpsConfigurator; import com.sun.net.httpserver.HttpsServer; +import jdk.httpclient.test.lib.common.TestServerConfigurator; import jdk.test.lib.net.SimpleSSLContext; import javax.net.ssl.SSLContext; @@ -51,7 +50,6 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import jdk.httpclient.test.lib.common.HttpServerAdapters; -import jdk.httpclient.test.lib.http2.Http2TestServer; import static java.net.http.HttpClient.Version.HTTP_1_1; import static java.net.http.HttpClient.Version.HTTP_2; @@ -62,6 +60,7 @@ * @library /test/lib /test/jdk/java/net/httpclient/lib * @build jdk.httpclient.test.lib.common.HttpServerAdapters jdk.test.lib.net.SimpleSSLContext * DigestEchoServer HttpSlowServerTest + * jdk.httpclient.test.lib.common.TestServerConfigurator * @run main/othervm -Dtest.requiresHost=true * -Djdk.httpclient.HttpClient.log=headers * -Djdk.internal.httpclient.debug=false @@ -138,7 +137,7 @@ public void setUp() throws Exception { // HTTPS/1.1 HttpsServer sserver1 = HttpsServer.create(sa, 100); sserver1.setExecutor(executor); - sserver1.setHttpsConfigurator(new HttpsConfigurator(context)); + sserver1.setHttpsConfigurator(new TestServerConfigurator(sa.getAddress(), context)); https1Server = HttpTestServer.of(sserver1); https1Server.addHandler(new HttpTestSlowHandler(), "/HttpSlowServerTest/https1/"); https1Server.start(); diff --git a/test/jdk/java/net/httpclient/ImmutableFlowItems.java b/test/jdk/java/net/httpclient/ImmutableFlowItems.java index d917d178538..b440ad646e8 100644 --- a/test/jdk/java/net/httpclient/ImmutableFlowItems.java +++ b/test/jdk/java/net/httpclient/ImmutableFlowItems.java @@ -27,6 +27,7 @@ * and that the buffers are read-only * @library /test/lib /test/jdk/java/net/httpclient/lib * @build jdk.test.lib.net.SimpleSSLContext jdk.httpclient.test.lib.http2.Http2TestServer + * jdk.httpclient.test.lib.common.TestServerConfigurator * @run testng/othervm ImmutableFlowItems */ @@ -43,7 +44,6 @@ import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpHandler; import com.sun.net.httpserver.HttpServer; -import com.sun.net.httpserver.HttpsConfigurator; import com.sun.net.httpserver.HttpsServer; import java.net.http.HttpClient; import java.net.http.HttpHeaders; @@ -53,6 +53,8 @@ import java.net.http.HttpResponse.BodySubscriber; import java.net.http.HttpResponse.BodySubscribers; import javax.net.ssl.SSLContext; + +import jdk.httpclient.test.lib.common.TestServerConfigurator; import jdk.httpclient.test.lib.http2.Http2TestServer; import jdk.httpclient.test.lib.http2.Http2TestExchange; import jdk.httpclient.test.lib.http2.Http2Handler; @@ -189,7 +191,7 @@ public void setup() throws Exception { httpURI_chunk = "http://" + serverAuthority(httpTestServer) + "/http1/chunk"; httpsTestServer = HttpsServer.create(sa, 0); - httpsTestServer.setHttpsConfigurator(new HttpsConfigurator(sslContext)); + httpsTestServer.setHttpsConfigurator(new TestServerConfigurator(sa.getAddress(), sslContext)); httpsTestServer.createContext("/https1/fixed", h1_fixedLengthHandler); httpsTestServer.createContext("/https1/chunk", h1_chunkHandler); httpsURI_fixed = "https://" + serverAuthority(httpsTestServer) + "/https1/fixed"; diff --git a/test/jdk/java/net/httpclient/LargeHandshakeTest.java b/test/jdk/java/net/httpclient/LargeHandshakeTest.java index b5c3dfefe8c..1f4c85b361e 100644 --- a/test/jdk/java/net/httpclient/LargeHandshakeTest.java +++ b/test/jdk/java/net/httpclient/LargeHandshakeTest.java @@ -20,8 +20,6 @@ * or visit www.oracle.com if you need additional information or have any * questions. */ -import com.sun.net.httpserver.HttpServer; -import com.sun.net.httpserver.HttpsConfigurator; import com.sun.net.httpserver.HttpsServer; import javax.net.ssl.KeyManagerFactory; @@ -61,7 +59,7 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import jdk.httpclient.test.lib.common.HttpServerAdapters; -import jdk.httpclient.test.lib.http2.Http2TestServer; +import jdk.httpclient.test.lib.common.TestServerConfigurator; import static java.net.http.HttpClient.Version.HTTP_1_1; import static java.net.http.HttpClient.Version.HTTP_2; @@ -82,6 +80,7 @@ * @library /test/lib /test/jdk/java/net/httpclient/lib * @build jdk.httpclient.test.lib.common.HttpServerAdapters jdk.test.lib.net.SimpleSSLContext * DigestEchoServer + * jdk.httpclient.test.lib.common.TestServerConfigurator * @run main/othervm -Dtest.requiresHost=true * -Djdk.httpclient.HttpClient.log=headers * -Djdk.internal.httpclient.debug=true @@ -1011,7 +1010,7 @@ public void setUp() throws Exception { // HTTPS/1.1 HttpsServer sserver1 = HttpsServer.create(sa, 100); sserver1.setExecutor(executor); - sserver1.setHttpsConfigurator(new HttpsConfigurator(context)); + sserver1.setHttpsConfigurator(new TestServerConfigurator(sa.getAddress(), context)); https1Server = HttpTestServer.of(sserver1); https1Server.addHandler(new HttpTestLargeHandler(), "/LargeHandshakeTest/https1/"); https1Server.start(); diff --git a/test/jdk/java/net/httpclient/LargeResponseTest.java b/test/jdk/java/net/httpclient/LargeResponseTest.java index 1d788f62f4c..bfc7c9ca5db 100644 --- a/test/jdk/java/net/httpclient/LargeResponseTest.java +++ b/test/jdk/java/net/httpclient/LargeResponseTest.java @@ -20,9 +20,8 @@ * or visit www.oracle.com if you need additional information or have any * questions. */ -import com.sun.net.httpserver.HttpServer; -import com.sun.net.httpserver.HttpsConfigurator; import com.sun.net.httpserver.HttpsServer; +import jdk.httpclient.test.lib.common.TestServerConfigurator; import jdk.test.lib.net.SimpleSSLContext; import javax.net.ssl.SSLContext; @@ -38,7 +37,6 @@ import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; -import java.nio.charset.StandardCharsets; import java.time.Duration; import java.util.List; import java.util.Set; @@ -51,7 +49,6 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import jdk.httpclient.test.lib.common.HttpServerAdapters; -import jdk.httpclient.test.lib.http2.Http2TestServer; import static java.net.http.HttpClient.Version.HTTP_1_1; import static java.net.http.HttpClient.Version.HTTP_2; @@ -64,6 +61,7 @@ * @library /test/lib /test/jdk/java/net/httpclient/lib * @build jdk.httpclient.test.lib.common.HttpServerAdapters * jdk.test.lib.net.SimpleSSLContext DigestEchoServer + * jdk.httpclient.test.lib.common.TestServerConfigurator * @run main/othervm -Dtest.requiresHost=true * -Djdk.httpclient.HttpClient.log=headers * -Djdk.internal.httpclient.debug=true @@ -136,7 +134,7 @@ public void setUp() throws Exception { // HTTPS/1.1 HttpsServer sserver1 = HttpsServer.create(sa, 100); sserver1.setExecutor(executor); - sserver1.setHttpsConfigurator(new HttpsConfigurator(context)); + sserver1.setHttpsConfigurator(new TestServerConfigurator(sa.getAddress(), context)); https1Server = HttpTestServer.of(sserver1); https1Server.addHandler(new HttpTestLargeHandler(), "/LargeResponseTest/https1/"); https1Server.start(); diff --git a/test/jdk/java/net/httpclient/LightWeightHttpServer.java b/test/jdk/java/net/httpclient/LightWeightHttpServer.java index 92603d55d0a..c226b845527 100644 --- a/test/jdk/java/net/httpclient/LightWeightHttpServer.java +++ b/test/jdk/java/net/httpclient/LightWeightHttpServer.java @@ -33,7 +33,6 @@ import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpHandler; import com.sun.net.httpserver.HttpServer; -import com.sun.net.httpserver.HttpsConfigurator; import com.sun.net.httpserver.HttpsServer; import java.io.IOException; import java.io.InputStream; @@ -50,6 +49,8 @@ import java.util.logging.Level; import java.util.logging.Logger; import javax.net.ssl.SSLContext; + +import jdk.httpclient.test.lib.common.TestServerConfigurator; import jdk.test.lib.net.SimpleSSLContext; public class LightWeightHttpServer { @@ -111,7 +112,7 @@ public static void initServer() throws IOException { httpServer.setExecutor(executor); httpsServer.setExecutor(executor); ctx = new SimpleSSLContext().get(); - httpsServer.setHttpsConfigurator(new HttpsConfigurator(ctx)); + httpsServer.setHttpsConfigurator(new TestServerConfigurator(addr.getAddress(), ctx)); httpServer.start(); httpsServer.start(); diff --git a/test/jdk/java/net/httpclient/MappingResponseSubscriber.java b/test/jdk/java/net/httpclient/MappingResponseSubscriber.java index db74fb05663..08ced612161 100644 --- a/test/jdk/java/net/httpclient/MappingResponseSubscriber.java +++ b/test/jdk/java/net/httpclient/MappingResponseSubscriber.java @@ -26,6 +26,7 @@ * @summary Tests mapped response subscriber * @library /test/lib /test/jdk/java/net/httpclient/lib * @build jdk.test.lib.net.SimpleSSLContext jdk.httpclient.test.lib.http2.Http2TestServer + * jdk.httpclient.test.lib.common.TestServerConfigurator * @run testng/othervm * -Djdk.internal.httpclient.debug=true * MappingResponseSubscriber @@ -46,7 +47,6 @@ import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpHandler; import com.sun.net.httpserver.HttpServer; -import com.sun.net.httpserver.HttpsConfigurator; import com.sun.net.httpserver.HttpsServer; import java.net.http.HttpClient; import java.net.http.HttpHeaders; @@ -58,6 +58,8 @@ import java.net.http.HttpResponse.BodySubscriber; import java.util.function.Function; import javax.net.ssl.SSLContext; + +import jdk.httpclient.test.lib.common.TestServerConfigurator; import jdk.httpclient.test.lib.http2.Http2TestServer; import jdk.httpclient.test.lib.http2.Http2TestExchange; import jdk.httpclient.test.lib.http2.Http2Handler; @@ -207,7 +209,7 @@ public void setup() throws Exception { httpURI_chunk = "http://" + serverAuthority(httpTestServer) + "/http1/chunk"; httpsTestServer = HttpsServer.create(sa, 0); - httpsTestServer.setHttpsConfigurator(new HttpsConfigurator(sslContext)); + httpsTestServer.setHttpsConfigurator(new TestServerConfigurator(sa.getAddress(), sslContext)); httpsTestServer.createContext("/https1/fixed", h1_fixedLengthHandler); httpsTestServer.createContext("/https1/chunk", h1_chunkHandler); httpsURI_fixed = "https://" + serverAuthority(httpsTestServer) + "/https1/fixed"; diff --git a/test/jdk/java/net/httpclient/RequestBodyTest.java b/test/jdk/java/net/httpclient/RequestBodyTest.java index 805a5b490db..771192564b0 100644 --- a/test/jdk/java/net/httpclient/RequestBodyTest.java +++ b/test/jdk/java/net/httpclient/RequestBodyTest.java @@ -59,14 +59,14 @@ /* * @test * @bug 8087112 - * @modules java.net.http + * @modules java.net.http/jdk.internal.net.http.common * java.logging * jdk.httpserver - * @library /test/lib + * @library /test/lib /test/jdk/java/net/httpclient/lib * @compile ../../../com/sun/net/httpserver/LogFilter.java * @compile ../../../com/sun/net/httpserver/EchoHandler.java * @compile ../../../com/sun/net/httpserver/FileServerHandler.java - * @build jdk.test.lib.net.SimpleSSLContext + * @build jdk.test.lib.net.SimpleSSLContext jdk.httpclient.test.lib.common.TestServerConfigurator * @build LightWeightHttpServer * @build jdk.test.lib.Platform * @build jdk.test.lib.util.FileUtils diff --git a/test/jdk/java/net/httpclient/RequestBodyTest.policy b/test/jdk/java/net/httpclient/RequestBodyTest.policy index 0bfedf22b84..d1ff89cbcd5 100644 --- a/test/jdk/java/net/httpclient/RequestBodyTest.policy +++ b/test/jdk/java/net/httpclient/RequestBodyTest.policy @@ -33,6 +33,11 @@ grant codeBase "file:${test.classes}/../../../../test/lib/-" { permission java.io.FilePermission "${test.src}/../../../../lib/jdk/test/lib/net/testkeys", "read"; }; +// for jdk/httpclient/test/lib/* classes +grant codeBase "file:${test.classes}/../../../../test/jdk/java/net/httpclient/lib/-" { + permission java.lang.RuntimePermission "accessClassInPackage.jdk.internal.net.http.common"; +}; + grant codeBase "file:${test.classes}/*" { permission java.io.FilePermission "${test.src}${/}docs${/}files${/}smallfile.txt", "read"; permission java.io.FilePermission "${test.src}${/}docs${/}files${/}notsobigfile.txt", "read"; @@ -52,4 +57,6 @@ grant codeBase "file:${test.classes}/*" { permission java.util.PropertyPermission "*", "read"; permission java.lang.RuntimePermission "modifyThread"; + + permission java.lang.RuntimePermission "accessClassInPackage.jdk.internal.net.http.common"; }; diff --git a/test/jdk/java/net/httpclient/lib/jdk/httpclient/test/lib/common/HttpServerAdapters.java b/test/jdk/java/net/httpclient/lib/jdk/httpclient/test/lib/common/HttpServerAdapters.java index 6bbcc4c3741..98da7d5533f 100644 --- a/test/jdk/java/net/httpclient/lib/jdk/httpclient/test/lib/common/HttpServerAdapters.java +++ b/test/jdk/java/net/httpclient/lib/jdk/httpclient/test/lib/common/HttpServerAdapters.java @@ -30,7 +30,6 @@ import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpHandler; import com.sun.net.httpserver.HttpServer; -import com.sun.net.httpserver.HttpsConfigurator; import com.sun.net.httpserver.HttpsServer; import jdk.httpclient.test.lib.http2.Http2Handler; import jdk.httpclient.test.lib.http2.Http2TestExchange; @@ -806,14 +805,14 @@ public static HttpTestServer create(Version serverVersion, SSLContext sslContext return HttpTestServer.of(underlying); } case HTTP_1_1 -> { - InetSocketAddress sa = new InetSocketAddress( - InetAddress.getLoopbackAddress(), 0); + InetAddress loopback = InetAddress.getLoopbackAddress(); + InetSocketAddress sa = new InetSocketAddress(loopback, 0); HttpServer underlying; if (sslContext == null) { underlying = HttpServer.create(sa, 0); // HTTP } else { HttpsServer https = HttpsServer.create(sa, 0); // HTTPS - https.setHttpsConfigurator(new HttpsConfigurator(sslContext)); + https.setHttpsConfigurator(new TestServerConfigurator(loopback, sslContext)); underlying = https; } if (executor != null) { diff --git a/test/jdk/java/net/httpclient/lib/jdk/httpclient/test/lib/common/ServerNameMatcher.java b/test/jdk/java/net/httpclient/lib/jdk/httpclient/test/lib/common/ServerNameMatcher.java new file mode 100644 index 00000000000..5e7a5790807 --- /dev/null +++ b/test/jdk/java/net/httpclient/lib/jdk/httpclient/test/lib/common/ServerNameMatcher.java @@ -0,0 +1,152 @@ +/* + * Copyright (c) 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package jdk.httpclient.test.lib.common; + +import java.io.IOException; +import java.net.InetAddress; +import java.util.Objects; +import java.util.Set; + +import javax.net.ssl.SNIHostName; +import javax.net.ssl.SNIMatcher; +import javax.net.ssl.SNIServerName; +import javax.net.ssl.StandardConstants; + +import jdk.internal.net.http.common.Logger; +import jdk.internal.net.http.common.Utils; + +/** + * A (server side) SNI host name matcher. Implementation is based on the expectations set in + * section 3 of RFC-6066. + * A server can be configured with an instance of this class. + *

    + * The RFC states: + * {@code + * Currently, the only server names supported are DNS hostnames; however, this does not imply + * any dependency of TLS on DNS, + * .... + * TLS MAY treat provided server names as opaque data and pass the names and types to the application. + * } + *

    + * The implementation in this class doesn't mandate the configured/recognized SNI host name as DNS + * resolvable. However, the {@code ServerNameMatcher} can be configured to treat the SNI host name + * as DNS resolvable by passing {@code true} to the {@code attemptDNSResolution} parameter of + * the {@link #ServerNameMatcher(boolean, String) constructor} + */ +public class ServerNameMatcher extends SNIMatcher { + + private final Logger debug; + private final boolean attemptDNSResolution; + private final Set recognizedSNINames; + + /** + * Creates a ServerNameMatcher which recognizes the passed {@code recognizedSNIName} + * + * @param recognizedSNIName The SNI host name + */ + public ServerNameMatcher(final String recognizedSNIName) { + this(false, recognizedSNIName); + } + + /** + * Creates a ServerNameMatcher which recognizes the passed SNI host name + * If {@code attemptDNSResolution} is {@code true}, then when + * {@link #matches(SNIServerName) matching} a client requested SNI name against the server + * recognized SNI name, the implementation will, as a last resort do a DNS resolution of the + * client requested SNI name and the server recognized SNI name and compare them to + * try and find a match. If {@code attemptDNSResolution} is false, then no DNS resolution is + * attempted and instead the SNI names are literally compared. + * + * @param attemptDNSResolution If true then a DNS resolution will be attempted during + * {@link #matches(SNIServerName) SNI matching} + * @param recognizedSNIName SNI host name + */ + public ServerNameMatcher(final boolean attemptDNSResolution, + final String recognizedSNIName) { + super(StandardConstants.SNI_HOST_NAME); + Objects.requireNonNull(recognizedSNIName); + this.debug = Utils.getDebugLogger(() -> "SNIMatcher"); + this.recognizedSNINames = Set.of(recognizedSNIName); + this.attemptDNSResolution = attemptDNSResolution; + } + + /** + * @param clientRequestedSNI the SNI name requested by the client + * {@return true if the {@code clientRequestedSNI} is recognized by + * the server. false otherwise} + */ + @Override + public boolean matches(final SNIServerName clientRequestedSNI) { + Objects.requireNonNull(clientRequestedSNI); + if (!SNIHostName.class.isInstance(clientRequestedSNI)) { + if (debug.on()) { + debug.log("SNI match (against " + recognizedSNINames + ")" + + " failed - not a SNIHostName: " + clientRequestedSNI); + } + // we only support SNIHostName type + return false; + } + final String requestedName = ((SNIHostName) clientRequestedSNI).getAsciiName(); + if (recognizedSNINames.contains(requestedName)) { + if (debug.on()) { + debug.log("SNI match (against " + recognizedSNINames + ") passed: " + + clientRequestedSNI); + } + return true; + } + if (attemptDNSResolution) { + final boolean res = matchesAfterDNSResolution(requestedName); + if (debug.on()) { + debug.log("SNI match (against " + recognizedSNINames + ") " + + (res ? "passed" : "failed") + ": " + clientRequestedSNI); + } + return res; + } + if (debug.on()) { + debug.log("SNI match (against " + recognizedSNINames + ") failed: " + clientRequestedSNI); + } + return false; + } + + private boolean matchesAfterDNSResolution(final String clientRequestedSNI) { + final InetAddress clientRequestedAddr; + try { + clientRequestedAddr = InetAddress.getByName(clientRequestedSNI); + } catch (IOException e) { + return false; + } + for (final String recognizedSNIName : recognizedSNINames) { + final InetAddress serverRecognizedAddr; + try { + serverRecognizedAddr = InetAddress.getByName(recognizedSNIName); + } catch (IOException e) { + // try next + continue; + } + if (serverRecognizedAddr.equals(clientRequestedAddr)) { + return true; + } + } + return false; + } +} diff --git a/test/jdk/java/net/httpclient/lib/jdk/httpclient/test/lib/common/TestServerConfigurator.java b/test/jdk/java/net/httpclient/lib/jdk/httpclient/test/lib/common/TestServerConfigurator.java new file mode 100644 index 00000000000..5d16ac24155 --- /dev/null +++ b/test/jdk/java/net/httpclient/lib/jdk/httpclient/test/lib/common/TestServerConfigurator.java @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package jdk.httpclient.test.lib.common; + +import java.net.InetAddress; +import java.security.AccessController; +import java.security.PrivilegedAction; +import java.util.List; + +import javax.net.ssl.SNIMatcher; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLParameters; + +import com.sun.net.httpserver.HttpsConfigurator; +import com.sun.net.httpserver.HttpsParameters; + +/** + * A {@link HttpsConfigurator} that can be used with the HTTP1 test server over HTTPS. + * This configurator {@link #configure(HttpsParameters) configures} the server's + * {@link HttpsParameters} with the necessary {@link SSLParameters} including a + * {@link SNIMatcher} + */ +public final class TestServerConfigurator extends HttpsConfigurator { + + private final InetAddress serverAddr; + + /** + * Creates a Https configuration, with the given {@link SSLContext}. + * + * @param serverAddr the address to which the server is bound + * @param context the {@code SSLContext} to use for this configurator + * @throws NullPointerException if no {@code SSLContext} supplied + */ + public TestServerConfigurator(final InetAddress serverAddr, final SSLContext context) { + super(context); + this.serverAddr = serverAddr; + } + + @Override + public void configure(final HttpsParameters params) { + final SSLParameters sslParams = getSSLContext().getDefaultSSLParameters(); + @SuppressWarnings("removal") final SecurityManager sm = System.getSecurityManager(); + final String hostname; + if (sm == null) { + hostname = serverAddr.getHostName(); + } else { + final PrivilegedAction action = () -> serverAddr.getHostName(); + hostname = AccessController.doPrivileged(action); + } + final List sniMatchers = List.of(new ServerNameMatcher(hostname)); + sslParams.setSNIMatchers(sniMatchers); + // configure the server with these custom SSLParameters + params.setSSLParameters(sslParams); + } +} diff --git a/test/jdk/java/net/httpclient/security/Driver.java b/test/jdk/java/net/httpclient/security/Driver.java index 98094a6cdc9..fc3dc4346ff 100644 --- a/test/jdk/java/net/httpclient/security/Driver.java +++ b/test/jdk/java/net/httpclient/security/Driver.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -56,6 +56,7 @@ import java.util.List; import java.util.stream.Collectors; import jdk.test.lib.Utils; +import jdk.test.lib.process.ProcessTools; /** * Driver for tests @@ -126,12 +127,10 @@ public static void runtest(String policy, String testnum, String addProp) throws String testClassPath = System.getProperty("test.class.path", "?"); String testClasses = System.getProperty("test.classes", "?"); String sep = System.getProperty("file.separator", "?"); - String javaCmd = testJdk + sep + "bin" + sep + "java"; int retval = 10; // 10 is special exit code denoting a bind error // in which case, we retry while (retval == 10) { List cmd = new ArrayList<>(); - cmd.add(javaCmd); cmd.add("-ea"); cmd.add("-esa"); cmd.add("-Dtest.jdk=" + testJdk); @@ -150,7 +149,7 @@ public static void runtest(String policy, String testnum, String addProp) throws cmd.add("Security"); cmd.add(testnum); - ProcessBuilder processBuilder = new ProcessBuilder(cmd) + ProcessBuilder processBuilder = ProcessTools.createTestJavaProcessBuilder(cmd) .redirectOutput(ProcessBuilder.Redirect.PIPE) .redirectErrorStream(true); diff --git a/test/jdk/java/net/httpclient/websocket/HandshakeUrlEncodingTest.java b/test/jdk/java/net/httpclient/websocket/HandshakeUrlEncodingTest.java index 969ab72be55..5065563c9ec 100644 --- a/test/jdk/java/net/httpclient/websocket/HandshakeUrlEncodingTest.java +++ b/test/jdk/java/net/httpclient/websocket/HandshakeUrlEncodingTest.java @@ -25,18 +25,18 @@ * @test * @bug 8245245 * @summary Test for Websocket URI encoding during HandShake - * @library /test/lib - * @build jdk.test.lib.net.SimpleSSLContext - * @modules java.net.http + * @library /test/lib /test/jdk/java/net/httpclient/lib + * @build jdk.test.lib.net.SimpleSSLContext jdk.httpclient.test.lib.common.TestServerConfigurator + * @modules java.net.http/jdk.internal.net.http.common * jdk.httpserver * @run testng/othervm -Djdk.internal.httpclient.debug=true HandshakeUrlEncodingTest */ import com.sun.net.httpserver.HttpHandler; import com.sun.net.httpserver.HttpServer; -import com.sun.net.httpserver.HttpsConfigurator; import com.sun.net.httpserver.HttpsServer; import com.sun.net.httpserver.HttpExchange; +import jdk.httpclient.test.lib.common.TestServerConfigurator; import jdk.test.lib.net.SimpleSSLContext; import jdk.test.lib.net.URIBuilder; import org.testng.annotations.AfterTest; @@ -154,7 +154,7 @@ public void setup() throws Exception { httpTestServer.createContext("/", new UrlHandler()); httpsTestServer = HttpsServer.create(sa, 10); - httpsTestServer.setHttpsConfigurator(new HttpsConfigurator(sslContext)); + httpsTestServer.setHttpsConfigurator(new TestServerConfigurator(sa.getAddress(), sslContext)); httpsURI = URIBuilder.newBuilder() .scheme("wss") .host("localhost") diff --git a/test/jdk/java/net/httpclient/websocket/WSHandshakeExceptionTest.java b/test/jdk/java/net/httpclient/websocket/WSHandshakeExceptionTest.java index a3ca4e2b439..6a02b774929 100644 --- a/test/jdk/java/net/httpclient/websocket/WSHandshakeExceptionTest.java +++ b/test/jdk/java/net/httpclient/websocket/WSHandshakeExceptionTest.java @@ -25,16 +25,15 @@ * @test * @bug 8240666 * @summary Basic test for WebSocketHandshakeException - * @library /test/lib - * @build jdk.test.lib.net.SimpleSSLContext - * @modules java.net.http + * @library /test/lib /test/jdk/java/net/httpclient/lib + * @build jdk.test.lib.net.SimpleSSLContext jdk.httpclient.test.lib.common.TestServerConfigurator + * @modules java.net.http/jdk.internal.net.http.common * jdk.httpserver * @run testng/othervm -Djdk.internal.httpclient.debug=true WSHandshakeExceptionTest */ import com.sun.net.httpserver.HttpHandler; import com.sun.net.httpserver.HttpServer; -import com.sun.net.httpserver.HttpsConfigurator; import com.sun.net.httpserver.HttpsServer; import com.sun.net.httpserver.HttpExchange; @@ -47,6 +46,8 @@ import java.net.http.HttpClient; import java.net.http.WebSocket; import java.net.http.WebSocketHandshakeException; + +import jdk.httpclient.test.lib.common.TestServerConfigurator; import jdk.test.lib.net.SimpleSSLContext; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeTest; @@ -172,7 +173,7 @@ public void setup() throws Exception { httpTestServer.createContext("/nonutf8body", new BodyHandler()); httpsTestServer = HttpsServer.create(sa, 0); - httpsTestServer.setHttpsConfigurator(new HttpsConfigurator(sslContext)); + httpsTestServer.setHttpsConfigurator(new TestServerConfigurator(sa.getAddress(), sslContext)); httpsURI = "wss://localhost:" + httpsTestServer.getAddress().getPort() + "/"; httpsNonUtf8URI = "wss://localhost:" + httpsTestServer.getAddress().getPort() + "/nonutf8body"; httpsTestServer.createContext("/nonutf8body", new BodyHandler()); diff --git a/test/jdk/java/net/spi/URLStreamHandlerProvider/Basic.java b/test/jdk/java/net/spi/URLStreamHandlerProvider/Basic.java index d2c635fb9ec..fc62594e032 100644 --- a/test/jdk/java/net/spi/URLStreamHandlerProvider/Basic.java +++ b/test/jdk/java/net/spi/URLStreamHandlerProvider/Basic.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2024, Oracle and/or its affiliates. All rights reserved. * 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,6 +45,8 @@ import javax.tools.StandardJavaFileManager; import javax.tools.StandardLocation; import javax.tools.ToolProvider; + +import jdk.test.lib.process.ProcessTools; import jdk.test.lib.util.FileUtils; import jdk.test.lib.JDKToolFinder; import static java.lang.String.format; @@ -234,12 +236,8 @@ static void quickFail(Result r) { static Result java(List sysProps, Collection classpath, String classname, String arg) { - String java = getJDKTool("java"); - List commands = new ArrayList<>(); - commands.add(java); - for (String prop : sysProps) - commands.add(prop); + List commands = new ArrayList<>(sysProps); String cp = classpath.stream() .map(Path::toString) @@ -249,7 +247,7 @@ static Result java(List sysProps, Collection classpath, commands.add(classname); commands.add(arg); - return run(new ProcessBuilder(commands)); + return run(ProcessTools.createTestJavaProcessBuilder(commands)); } static Result run(ProcessBuilder pb) { diff --git a/test/jdk/java/nio/MappedByteBuffer/ForceException.java b/test/jdk/java/nio/MappedByteBuffer/ForceException.java index dea63db42bf..c8bd06967d0 100644 --- a/test/jdk/java/nio/MappedByteBuffer/ForceException.java +++ b/test/jdk/java/nio/MappedByteBuffer/ForceException.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2021, 2024, Oracle and/or its affiliates. All rights reserved. * 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,7 +40,7 @@ public static void main(String[] args) throws IOException { int numberOfBlocks = 200; int fileLength = numberOfBlocks * blockSize; - File file = new File(System.getProperty("test.src", "."), "test.dat"); + File file = new File(".", "test.dat"); file.deleteOnExit(); try (RandomAccessFile raf = new RandomAccessFile(file, "rw")) { raf.setLength(fileLength); diff --git a/test/jdk/java/nio/MappedByteBuffer/ForceViews.java b/test/jdk/java/nio/MappedByteBuffer/ForceViews.java index 83727f80968..57ddac28cdf 100644 --- a/test/jdk/java/nio/MappedByteBuffer/ForceViews.java +++ b/test/jdk/java/nio/MappedByteBuffer/ForceViews.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2021, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -51,7 +51,7 @@ static record Segment(int position, int length) {} @BeforeTest(alwaysRun=true) public void openChannel() throws IOException { - Path file = Path.of(System.getProperty("test.src", "."), "junk"); + Path file = Path.of(".", "junk"); fc = FileChannel.open(file, CREATE_NEW, READ, WRITE, DELETE_ON_CLOSE); ByteBuffer buf = ByteBuffer.wrap(new byte[1024]); fc.write(buf); diff --git a/test/jdk/java/nio/channels/DatagramChannel/Disconnect.java b/test/jdk/java/nio/channels/DatagramChannel/Disconnect.java index cdc5882fefd..16120f85168 100644 --- a/test/jdk/java/nio/channels/DatagramChannel/Disconnect.java +++ b/test/jdk/java/nio/channels/DatagramChannel/Disconnect.java @@ -52,7 +52,7 @@ public static void main(String[] args) throws IOException { if (IPSupport.hasIPv4()) { // test with IPv4 only try (DatagramChannel dc = DatagramChannel.open(StandardProtocolFamily.INET)) { - InetAddress lo4 = InetAddress.ofLiteral("127.0.0.1"); + InetAddress lo4 = InetAddress.getByName("127.0.0.1"); System.out.println("Testing with INET family and " + lo4); test(dc, lo4); test(dc, lo4); @@ -62,7 +62,7 @@ public static void main(String[] args) throws IOException { if (IPSupport.hasIPv6()) { // test with IPv6 only try (DatagramChannel dc = DatagramChannel.open(StandardProtocolFamily.INET6)) { - InetAddress lo6 = InetAddress.ofLiteral("::1"); + InetAddress lo6 = InetAddress.getByName("::1"); System.out.println("Testing with INET6 family and " + lo6); test(dc, lo6); test(dc, lo6); diff --git a/test/jdk/java/nio/channels/Selector/LotsOfUpdatesTest.java b/test/jdk/java/nio/channels/Selector/LotsOfUpdatesTest.java index ef2c389ef39..86c3c828f70 100644 --- a/test/jdk/java/nio/channels/Selector/LotsOfUpdatesTest.java +++ b/test/jdk/java/nio/channels/Selector/LotsOfUpdatesTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2023, Oracle and/or its affiliates. All rights reserved. * 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 LotsOfUpdatesTest { private static final String ULIMIT_SET_CMD = "ulimit -n 2048"; private static final String JAVA_CMD = ProcessTools.getCommandLine( - ProcessTools.createJavaProcessBuilder(LotsOfUpdates.class.getName())); + ProcessTools.createLimitedTestJavaProcessBuilder(LotsOfUpdates.class.getName())); public static void main(String[] args) throws Throwable { ProcessTools.executeCommand("sh", "-c", ULIMIT_SET_CMD + " && " + JAVA_CMD) diff --git a/test/jdk/java/nio/channels/Selector/SelectWithConsumer.java b/test/jdk/java/nio/channels/Selector/SelectWithConsumer.java index 630a1ef88b8..070b4697548 100644 --- a/test/jdk/java/nio/channels/Selector/SelectWithConsumer.java +++ b/test/jdk/java/nio/channels/Selector/SelectWithConsumer.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -308,11 +308,10 @@ public void testTimeout() throws Exception { Pipe.SinkChannel sink = p.sink(); source.configureBlocking(false); source.register(sel, SelectionKey.OP_READ); - long start = System.currentTimeMillis(); + long start = millisTime(); int n = sel.select(k -> assertTrue(false), 1000L); - long duration = System.currentTimeMillis() - start; + expectDuration(start, 500, Long.MAX_VALUE); assertTrue(n == 0); - assertTrue(duration > 500, "select took " + duration + " ms"); } finally { closePipe(p); } @@ -332,11 +331,10 @@ public void testWakeupBeforeSelect() throws Exception { // select(Consumer, timeout) try (Selector sel = Selector.open()) { sel.wakeup(); - long start = System.currentTimeMillis(); + long start = millisTime(); int n = sel.select(k -> assertTrue(false), 60*1000); - long duration = System.currentTimeMillis() - start; + expectDuration(start, 0, 20_000); assertTrue(n == 0); - assertTrue(duration < 5000, "select took " + duration + " ms"); } } @@ -354,12 +352,10 @@ public void testWakeupDuringSelect() throws Exception { // select(Consumer, timeout) try (Selector sel = Selector.open()) { scheduleWakeup(sel, 1, SECONDS); - long start = System.currentTimeMillis(); + long start = millisTime(); int n = sel.select(k -> assertTrue(false), 60*1000); - long duration = System.currentTimeMillis() - start; + expectDuration(start, 0, 20_000); assertTrue(n == 0); - assertTrue(duration > 500 && duration < 10*1000, - "select took " + duration + " ms"); } } @@ -381,11 +377,10 @@ public void testInterruptBeforeSelect() throws Exception { // select(Consumer, timeout) try (Selector sel = Selector.open()) { Thread.currentThread().interrupt(); - long start = System.currentTimeMillis(); + long start = millisTime(); int n = sel.select(k -> assertTrue(false), 60*1000); - long duration = System.currentTimeMillis() - start; + expectDuration(start, 0, 20_000); assertTrue(n == 0); - assertTrue(duration < 5000, "select took " + duration + " ms"); assertTrue(Thread.currentThread().isInterrupted()); assertTrue(sel.isOpen()); } finally { @@ -764,4 +759,32 @@ static ByteBuffer messageBuffer() { throw new RuntimeException(e); } } + + /** + * Returns the current time in milliseconds. + */ + private static long millisTime() { + long now = System.nanoTime(); + return TimeUnit.MILLISECONDS.convert(now, TimeUnit.NANOSECONDS); + } + + /** + * Check the duration of a task. The method will fail with an + * AssertionError if the millisecond duration does not satisfy: + * + * duration >= min && duration <= max + * + * Note that the inequalities are not strict, i.e., are inclusive. + * + * @param start start time, in milliseconds + * @param min minimum expected duration, in milliseconds + * @param max maximum expected duration, in milliseconds + */ + private static void expectDuration(long start, long min, long max) { + long duration = millisTime() - start; + assertTrue(duration >= min, + "Duration " + duration + "ms, expected >= " + min + "ms"); + assertTrue(duration <= max, + "Duration " + duration + "ms, expected <= " + max + "ms"); + } } diff --git a/test/jdk/java/nio/channels/SocketChannel/AdaptorStreams.java b/test/jdk/java/nio/channels/SocketChannel/AdaptorStreams.java index 24fbc0ea66b..846d5cd22b6 100644 --- a/test/jdk/java/nio/channels/SocketChannel/AdaptorStreams.java +++ b/test/jdk/java/nio/channels/SocketChannel/AdaptorStreams.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -158,7 +158,7 @@ public void testTimedRead1() throws Exception { withConnection((sc, peer) -> { peer.getOutputStream().write(99); Socket s = sc.socket(); - s.setSoTimeout(1000); + s.setSoTimeout(60_000); int n = s.getInputStream().read(); assertEquals(n, 99); }); @@ -171,7 +171,7 @@ public void testTimedRead2() throws Exception { withConnection((sc, peer) -> { scheduleWrite(peer.getOutputStream(), 99, 1000); Socket s = sc.socket(); - s.setSoTimeout(5000); + s.setSoTimeout(60_000); int n = s.getInputStream().read(); assertEquals(n, 99); }); @@ -183,7 +183,7 @@ public void testTimedRead2() throws Exception { public void testTimedRead3() throws Exception { withConnection((sc, peer) -> { Socket s = sc.socket(); - s.setSoTimeout(1000); + s.setSoTimeout(500); InputStream in = s.getInputStream(); expectThrows(SocketTimeoutException.class, () -> in.read()); }); @@ -196,7 +196,7 @@ public void testTimedRead4() throws Exception { withConnection((sc, peer) -> { scheduleClose(sc, 2000); Socket s = sc.socket(); - s.setSoTimeout(60*1000); + s.setSoTimeout(60_000); InputStream in = s.getInputStream(); expectThrows(IOException.class, () -> in.read()); }); @@ -210,7 +210,7 @@ public void testTimedRead5() throws Exception { Socket s = sc.socket(); Thread.currentThread().interrupt(); try { - s.setSoTimeout(60*1000); + s.setSoTimeout(60_000); InputStream in = s.getInputStream(); expectThrows(IOException.class, () -> in.read()); } finally { @@ -228,7 +228,7 @@ public void testTimedRead6() throws Exception { Future interrupter = scheduleInterrupt(Thread.currentThread(), 2000); Socket s = sc.socket(); try { - s.setSoTimeout(60*1000); + s.setSoTimeout(60_000); InputStream in = s.getInputStream(); expectThrows(IOException.class, () -> in.read()); assertTrue(s.isClosed()); @@ -396,7 +396,7 @@ public void testConcurrentTimedReadWrite1() throws Exception { // test read when bytes are available peer.getOutputStream().write(99); - s.setSoTimeout(60*1000); + s.setSoTimeout(60_000); int n = s.getInputStream().read(); assertEquals(n, 99); }); @@ -421,7 +421,7 @@ public void testConcurrentTimedReadWrite2() throws Exception { // test read blocking until bytes are available scheduleWrite(peer.getOutputStream(), 99, 500); - s.setSoTimeout(60*1000); + s.setSoTimeout(60_000); int n = s.getInputStream().read(); assertEquals(n, 99); }); @@ -436,7 +436,7 @@ public void testConcurrentTimedReadWrite3() throws Exception { // block thread in read execute(() -> { - s.setSoTimeout(60*1000); + s.setSoTimeout(60_000); s.getInputStream().read(); }); Thread.sleep(100); // give reader time to block diff --git a/test/jdk/java/nio/charset/Charset/AliasesCopy.java b/test/jdk/java/nio/charset/Charset/AliasesCopy.java new file mode 100644 index 00000000000..66ee830c5f6 --- /dev/null +++ b/test/jdk/java/nio/charset/Charset/AliasesCopy.java @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute 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 8319817 + * @summary Check that aliases cannot be mutated + * @run junit AliasesCopy + */ + +import java.nio.charset.Charset; +import java.nio.charset.CharsetDecoder; +import java.nio.charset.CharsetEncoder; +import java.util.Set; + +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertIterableEquals; + +public class AliasesCopy { + private static final Set ALIASES_SET = Set.of("foo-alias"); + private static final String[] ALIASES_ARRAY = ALIASES_SET.toArray(String[]::new); + + @Test + public void aliasesCopy() { + final FooCharset cs = new FooCharset(ALIASES_ARRAY); + ALIASES_ARRAY[0] = "bar-alias"; + assertIterableEquals(ALIASES_SET, cs.aliases()); + } + + private static final class FooCharset extends Charset { + private FooCharset(String[] aliases) { + super("foo", aliases); + } + + @Override + public CharsetEncoder newEncoder() { + throw new RuntimeException("not implemented"); + } + + @Override + public CharsetDecoder newDecoder() { + throw new RuntimeException("not implemented"); + } + + @Override + public boolean contains(Charset cs) { + throw new RuntimeException("not implemented"); + } + } +} diff --git a/test/jdk/java/nio/charset/Charset/DefaultCharsetTest.java b/test/jdk/java/nio/charset/Charset/DefaultCharsetTest.java index 9ea2902fb0d..be33ecb70f2 100644 --- a/test/jdk/java/nio/charset/Charset/DefaultCharsetTest.java +++ b/test/jdk/java/nio/charset/Charset/DefaultCharsetTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -54,7 +54,7 @@ public class DefaultCharsetTest { private static final ProcessBuilder pb - = ProcessTools.createTestJvm(Default.class.getName()); + = ProcessTools.createTestJavaProcessBuilder(Default.class.getName()); private static final Map env = pb.environment(); private static String UNSUPPORTED = null; diff --git a/test/jdk/java/nio/file/Files/CreateDirectories.java b/test/jdk/java/nio/file/Files/CreateDirectories.java new file mode 100644 index 00000000000..f49251458c7 --- /dev/null +++ b/test/jdk/java/nio/file/Files/CreateDirectories.java @@ -0,0 +1,124 @@ +/* + * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.io.IOException; +import java.nio.file.FileAlreadyExistsException; +import java.nio.file.Files; +import java.nio.file.Path; + +import static org.testng.Assert.*; +import org.testng.SkipException; +import org.testng.annotations.Test; + +/* + * @test + * @bug 8032220 8293792 + * @summary Test java.nio.file.Files.createDirectories method + * @library .. + * @run testng CreateDirectories + */ +public class CreateDirectories { + + /** + * Test Files.createDirectories symbolic file with an existing directory. + */ + @Test + public void testSymlinkDir() throws Exception { + // create a temp dir as the "root" in which we will run our tests. + final Path top = TestUtil.createTemporaryDirectory(); + if (!TestUtil.supportsLinks(top)) { + System.out.println("Skipping tests since symbolic links isn't " + + "supported under directory "+ top); + throw new SkipException("Symbolic links not supported"); + } + System.out.println("Running tests under directory " + top.toAbsolutePath()); + final Path fooDir = Files.createDirectory(top.resolve("foo")); + assertTrue(Files.isDirectory(fooDir), + fooDir + " was expected to be a directory but wasn't"); + + // now create a symlink to the "foo" dir + final Path symlink = Files.createSymbolicLink(top.resolve("symlinkToFoo"), + fooDir.toAbsolutePath()); + assertTrue(Files.isSymbolicLink(symlink), + symlink + " was expected to be a symlink but wasn't"); + assertTrue(Files.isDirectory(symlink), + symlink + " was expected to be a directory but wasn't"); + + // now create a directory under the symlink (which effectively creates a directory under + // "foo") + final Path barDir = Files.createDirectory(symlink.resolve("bar")); + assertTrue(Files.isDirectory(barDir), + barDir + " was expected to be a directory but wasn't"); + // ultimately, we now have this directory structure: + // + // |--- foo + // | |--- bar + // | + // |--- symlinkToFoo -> (links to) /foo + + + // now call Files.createDirectories on each of these existing directory/symlink paths + // and expect each one to succeed + Files.createDirectories(fooDir); // .//foo + Files.createDirectories(symlink); // .//symlinkToFoo + Files.createDirectories(barDir); // .//symlinkToFoo/bar + } + + /** + * Tests Files.createDirectories + */ + @Test + public void testCreateDirectories() throws IOException { + final Path tmpdir = TestUtil.createTemporaryDirectory(); + // a no-op + Files.createDirectories(tmpdir); + + // create one directory + Path subdir = tmpdir.resolve("a"); + Files.createDirectories(subdir); + assertTrue(Files.isDirectory(subdir), subdir + " was expected to be a directory," + + " but wasn't"); + + // create parents + subdir = subdir.resolve("b/c/d"); + Files.createDirectories(subdir); + assertTrue(Files.isDirectory(subdir), subdir + " was expected to be a directory," + + " but wasn't"); + + // existing file is not a directory + Path file = Files.createFile(tmpdir.resolve("x")); + try { + Files.createDirectories(file); + throw new RuntimeException("failure expected"); + } catch (FileAlreadyExistsException x) { } + try { + Files.createDirectories(file.resolve("y")); + throw new RuntimeException("failure expected"); + } catch (IOException x) { } + + // the root directory always exists + Path root = Path.of("/"); + Files.createDirectories(root); + Files.createDirectories(root.toAbsolutePath()); + } +} diff --git a/test/jdk/java/nio/file/Files/Misc.java b/test/jdk/java/nio/file/Files/Misc.java index 0bfc0c410dc..1d3df155675 100644 --- a/test/jdk/java/nio/file/Files/Misc.java +++ b/test/jdk/java/nio/file/Files/Misc.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2008, 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2008, 2022, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -22,24 +22,35 @@ */ /* @test - * @bug 4313887 6838333 8005566 8032220 8215467 8255576 - * @summary Unit test for miscellenous methods in java.nio.file.Files - * @library .. + * @bug 4313887 6838333 8005566 8215467 8255576 8286160 + * @summary Unit test for miscellaneous methods in java.nio.file.Files + * @library .. /test/lib + * @build jdk.test.lib.Platform + * @run main Misc */ -import java.nio.file.*; +import java.io.IOException; +import java.io.File; +import java.nio.file.FileAlreadyExistsException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.attribute.AclEntry; +import java.nio.file.attribute.AclEntryPermission; +import java.nio.file.attribute.AclEntryType; +import java.nio.file.attribute.AclFileAttributeView; +import java.nio.file.attribute.DosFileAttributeView; +import java.nio.file.attribute.UserPrincipal; +import java.util.List; +import jdk.test.lib.Platform; + import static java.nio.file.Files.*; import static java.nio.file.LinkOption.*; -import java.nio.file.attribute.*; -import java.io.IOException; -import java.util.*; public class Misc { public static void main(String[] args) throws IOException { Path dir = TestUtil.createTemporaryDirectory(); try { - testCreateDirectories(dir); testIsHidden(dir); testIsSameFile(dir); testFileTypeMethods(dir); @@ -49,39 +60,6 @@ public static void main(String[] args) throws IOException { } } - /** - * Tests createDirectories - */ - static void testCreateDirectories(Path tmpdir) throws IOException { - // a no-op - createDirectories(tmpdir); - - // create one directory - Path subdir = tmpdir.resolve("a"); - createDirectories(subdir); - assertTrue(exists(subdir)); - - // create parents - subdir = subdir.resolve("b/c/d"); - createDirectories(subdir); - assertTrue(exists(subdir)); - - // existing file is not a directory - Path file = createFile(tmpdir.resolve("x")); - try { - createDirectories(file); - throw new RuntimeException("failure expected"); - } catch (FileAlreadyExistsException x) { } - try { - createDirectories(file.resolve("y")); - throw new RuntimeException("failure expected"); - } catch (IOException x) { } - - // the root directory always exists - Path root = Paths.get("/"); - Files.createDirectories(root); - Files.createDirectories(root.toAbsolutePath()); - } /** * Tests isHidden @@ -93,7 +71,7 @@ static void testIsHidden(Path tmpdir) throws IOException { assertTrue(!isHidden(tmpdir)); Path file = tmpdir.resolve(".foo"); - if (System.getProperty("os.name").startsWith("Windows")) { + if (Platform.isWindows()) { createFile(file); try { setAttribute(file, "dos:hidden", true); @@ -286,6 +264,13 @@ static void testAccessMethods(Path tmpdir) throws IOException { assertTrue(exists(tmpdir)); assertTrue(!notExists(tmpdir)); + if (Platform.isWindows()) { + Path pageFile = Path.of("C:\\pagefile.sys"); + if (pageFile.toFile().exists()) { + System.out.printf("Check page file %s%n", pageFile); + assertTrue(exists(pageFile)); + } + } // sym link exists if (TestUtil.supportsLinks(tmpdir)) { @@ -351,7 +336,7 @@ static void testAccessMethods(Path tmpdir) throws IOException { /** * Test: Windows DOS read-only attribute */ - if (System.getProperty("os.name").startsWith("Windows")) { + if (Platform.isWindows()) { setAttribute(file, "dos:readonly", true); try { assertTrue(!isWritable(file)); @@ -381,10 +366,10 @@ static void assertTrue(boolean okay) { } private static boolean isRoot() { - if (System.getProperty("os.name").startsWith("Windows")) + if (Platform.isWindows()) return false; - Path passwd = Paths.get("/etc/passwd"); + Path passwd = Path.of("/etc/passwd"); return Files.isWritable(passwd); } } diff --git a/test/jdk/java/nio/file/Path/MacPathTest.java b/test/jdk/java/nio/file/Path/MacPathTest.java index a65e310ff7f..9107abb0ea6 100644 --- a/test/jdk/java/nio/file/Path/MacPathTest.java +++ b/test/jdk/java/nio/file/Path/MacPathTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2023, Oracle and/or its affiliates. All rights reserved. * 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,7 +41,7 @@ public class MacPathTest { public static void main(String args[]) throws Exception { - ProcessBuilder pb = ProcessTools.createTestJvm(MacPath.class.getName()); + ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder(MacPath.class.getName()); pb.environment().put("LC_ALL", "en_US.UTF-8"); ProcessTools.executeProcess(pb) .outputTo(System.out) diff --git a/test/jdk/java/security/Security/SynchronizedAccess.java b/test/jdk/java/security/Security/SynchronizedAccess.java index 4e244a291e3..28019213b3c 100644 --- a/test/jdk/java/security/Security/SynchronizedAccess.java +++ b/test/jdk/java/security/Security/SynchronizedAccess.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,13 +23,15 @@ /* * @test - * @bug 4162583 7054918 8130181 - * @library ../testlibrary + * @bug 4162583 7054918 8130181 8028127 + * @library /test/lib ../testlibrary * @summary Make sure Provider api implementations are synchronized properly */ import java.security.*; +import jdk.test.lib.Asserts; + public class SynchronizedAccess { public static void main(String[] args) throws Exception { @@ -42,52 +44,105 @@ public static void main(String[] args) throws Exception { } public static void main0(String[] args) throws Exception { + var providersCountBefore = Security.getProviders().length; AccessorThread[] acc = new AccessorThread[200]; - for (int i=0; i < acc.length; i++) - acc[i] = new AccessorThread("thread"+i); - for (int i=0; i < acc.length; i++) + for (int i = 0; i < acc.length; i++) { + acc[i] = new AccessorThread("thread" + i); + } + for (int i = 0; i < acc.length; i++) { acc[i].start(); - for (int i=0; i < acc.length; i++) + } + for (int i = 0; i < acc.length; i++) { acc[i].join(); + } + var providersCountAfter = Security.getProviders().length; + Asserts.assertEquals(providersCountBefore, providersCountAfter); } -} -class AccessorThread extends Thread { + static class AccessorThread extends Thread { - public AccessorThread(String str) { - super(str); - } + public AccessorThread(String str) { + super(str); + } - public void run() { - Provider[] provs = new Provider[10]; - for (int i=0; i < provs.length; i++) - provs[i] = new MyProvider("name"+i, "1", "test"); + public void run() { + Provider[] provs = new Provider[10]; + for (int i = 0; i < provs.length; i++) { + provs[i] = new MyProvider("name" + i, "1", "test"); + } - int rounds = 20; - while (rounds-- > 0) { - try { - for (int i=0; i 0) { + for (int i = 0; i < provs.length; i++) { + // Might install (>=0) or not (-1) if already installed Security.addProvider(provs[i]); + Thread.yield(); + } + + try { + Signature.getInstance("sigalg"); + Thread.yield(); + } catch (NoSuchAlgorithmException nsae) { + // All providers may have been deregistered. Ok. } - Signature sig = Signature.getInstance("sigalg"); - for (int i=0; i + * The program may call InputStream.read() and BufferedReader.readLine() in + * various places. a call to B.readLine() will try to buffer as much input as + * possible. Thus, a trivial InputStream will find it impossible to feed + * anything to I.read() after a B.readLine() call. + *

    + * This is why HumanInputStream was created, which will only send a single line + * to B.readLine(), no more, no less, and the next I.read() can have a chance + * to read the exact character right after "\n". + * + */ + +public class HumanInputStream extends InputStream { + byte[] src; + int pos; + int length; + boolean inLine; + int stopIt; + + public HumanInputStream(String input) { + src = input.getBytes(); + pos = 0; + length = src.length; + stopIt = 0; + inLine = false; + } + + // the trick: when called through read(byte[], int, int), + // return -1 twice after "\n" + + @Override public int read() throws IOException { + int re; + if(pos < length) { + re = src[pos]; + if(inLine) { + if(stopIt > 0) { + stopIt--; + re = -1; + } else { + if(re == '\n') { + stopIt = 2; + } + pos++; + } + } else { + pos++; + } + } else { + re = -1; //throws new IOException("NO MORE TO READ"); + } + return re; + } + @Override public int read(byte[] buffer, int offset, int len) { + inLine = true; + try { + return super.read(buffer, offset, len); + } catch(Exception e) { + throw new RuntimeException("HumanInputStream error"); + } finally { + inLine = false; + } + } + @Override public int available() { + if (pos < length) return 1; + return 0; + } + + // test part + static void assertTrue(boolean bool) { + if (!bool) + throw new RuntimeException(); + } + + public static void test() throws Exception { + class Tester { + HumanInputStream is; + BufferedReader reader; + Tester(String s) { + is = new HumanInputStream(s); + reader = new BufferedReader(new InputStreamReader(is)); + } + + // three kinds of test method + // 1. read byte by byte from InputStream + void testStreamReadOnce(int expection) throws Exception { + assertTrue(is.read() == expection); + } + void testStreamReadMany(String expectation) throws Exception { + char[] keys = expectation.toCharArray(); + for (char key : keys) { + assertTrue(is.read() == key); + } + } + // 2. read a line with a newly created Reader + void testReaderReadline(String expectation) throws Exception { + String s = new BufferedReader(new InputStreamReader(is)).readLine(); + if(s == null) assertTrue(expectation == null); + else assertTrue(s.equals(expectation)); + } + // 3. read a line with the old Reader + void testReaderReadline2(String expectation) throws Exception { + String s = reader.readLine(); + if(s == null) assertTrue(expectation == null); + else assertTrue(s.equals(expectation)); + } + } + + Tester test; + + test = new Tester("111\n222\n\n444\n\n"); + test.testReaderReadline("111"); + test.testReaderReadline("222"); + test.testReaderReadline(""); + test.testReaderReadline("444"); + test.testReaderReadline(""); + test.testReaderReadline(null); + + test = new Tester("111\n222\n\n444\n\n"); + test.testReaderReadline2("111"); + test.testReaderReadline2("222"); + test.testReaderReadline2(""); + test.testReaderReadline2("444"); + test.testReaderReadline2(""); + test.testReaderReadline2(null); + + test = new Tester("111\n222\n\n444\n\n"); + test.testReaderReadline2("111"); + test.testReaderReadline("222"); + test.testReaderReadline2(""); + test.testReaderReadline2("444"); + test.testReaderReadline(""); + test.testReaderReadline2(null); + + test = new Tester("1\n2"); + test.testStreamReadMany("1\n2"); + test.testStreamReadOnce(-1); + + test = new Tester("12\n234"); + test.testStreamReadOnce('1'); + test.testReaderReadline("2"); + test.testStreamReadOnce('2'); + test.testReaderReadline2("34"); + test.testReaderReadline2(null); + + test = new Tester("changeit\n"); + test.testStreamReadMany("changeit\n"); + test.testReaderReadline(null); + + test = new Tester("changeit\nName\nCountry\nYes\n"); + test.testStreamReadMany("changeit\n"); + test.testReaderReadline("Name"); + test.testReaderReadline("Country"); + test.testReaderReadline("Yes"); + test.testReaderReadline(null); + + test = new Tester("Me\nHere\n"); + test.testReaderReadline2("Me"); + test.testReaderReadline2("Here"); + } +} diff --git a/test/jdk/java/util/Formatter/Basic.java b/test/jdk/java/util/Formatter/Basic.java index ea6d50ea553..099ff13b39d 100644 --- a/test/jdk/java/util/Formatter/Basic.java +++ b/test/jdk/java/util/Formatter/Basic.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2022, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,18 +21,6 @@ * questions. */ -/* @test - * @summary Unit test for formatter - * @bug 4906370 4962433 4973103 4989961 5005818 5031150 4970931 4989491 5002937 - * 5005104 5007745 5061412 5055180 5066788 5088703 6317248 6318369 6320122 - * 6344623 6369500 6534606 6282094 6286592 6476425 5063507 6469160 6476168 - * 8059175 8204229 - * - * @run shell/timeout=240 Basic.sh - */ - -import static java.lang.System.out; - public class Basic { private static int fail = 0; @@ -45,18 +33,20 @@ static void pass() { } static void fail(String fs, Class ex) { - String s = "'" + fs + "': " + ex.getName() + " not thrown"; - if (first == null) - setFirst(s); - System.err.println("FAILED: " + s); + String message = "'%s': %s not thrown".formatted(fs, ex.getName()); + if (first == null) { + setFirst(message); + } + System.err.printf("FAILED: %s%n", message); fail++; } static void fail(String fs, String exp, String got) { - String s = "'" + fs + "': Expected '" + exp + "', got '" + got + "'"; - if (first == null) - setFirst(s); - System.err.println("FAILED: " + s); + String message = "'%s': Expected '%s', got '%s'".formatted(fs, exp, got); + if (first == null) { + setFirst(message); + } + System.err.printf("FAILED: %s%n", message); fail++; } @@ -69,10 +59,11 @@ private static void setFirst(String s) { } static void ck(String fs, String exp, String got) { - if (!exp.equals(got)) + if (!exp.equals(got)) { fail(fs, exp, got); - else + } else { pass(); + } } public static void main(String[] args) { @@ -94,13 +85,15 @@ public static void main(String[] args) { BasicDouble.test(); BasicDoubleObject.test(); BasicBigDecimal.test(); - BasicDateTime.test(); - if (fail != 0) - throw new RuntimeException((fail + pass) + " tests: " - + fail + " failure(s), first", first); - else - out.println("all " + (fail + pass) + " tests passed"); + if (fail != 0) { + var tests_message = "%d tests: %d failure(s)%n".formatted(fail + pass, fail); + var trace_message = "Traceback of the first error located"; + var message = "%s %s".formatted(tests_message, trace_message); + throw new RuntimeException(message, first); + } else { + System.out.printf("All %d tests passed", pass); + } } } diff --git a/test/jdk/java/util/Formatter/Basic.sh b/test/jdk/java/util/Formatter/Basic.sh deleted file mode 100644 index 78a65dbc977..00000000000 --- a/test/jdk/java/util/Formatter/Basic.sh +++ /dev/null @@ -1,50 +0,0 @@ -# -# Copyright (c) 2004, 2019, Oracle and/or its affiliates. All rights reserved. -# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. -# -# This code is free software; you can redistribute 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. -# - -# - -EXTRAOPTS="--add-exports java.base/jdk.internal.math=ALL-UNNAMED" -LOCALEOPTS="-Djava.locale.providers=CLDR" -${COMPILEJAVA}/bin/javac ${TESTJAVACOPTS} ${TESTTOOLVMOPTS} ${EXTRAOPTS} -cp ${TESTSRC} -d . \ - ${TESTSRC}/Basic.java - -expectPass() { - if [ $1 -eq 0 ] - then echo "--- passed as expected" - else - echo "--- failed" - exit $1 - fi -} - -runTest() { - echo "Testing:" ${1} - TZ="${1}"; export TZ - echo " " $TZ - ${TESTJAVA}/bin/java ${TESTVMOPTS} ${EXTRAOPTS} ${LOCALEOPTS} Basic - expectPass $? -} - -runTest US/Pacific -runTest Asia/Novosibirsk - diff --git a/test/jdk/java/util/Formatter/BasicTestLauncher.java b/test/jdk/java/util/Formatter/BasicTestLauncher.java new file mode 100644 index 00000000000..87c43cdaa35 --- /dev/null +++ b/test/jdk/java/util/Formatter/BasicTestLauncher.java @@ -0,0 +1,100 @@ +/* + * Copyright (c) 2022, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import jdk.test.lib.process.OutputAnalyzer; +import jdk.test.lib.process.ProcessTools; +import java.io.IOException; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +/* @test + * @summary Unit tests for formatter + * @library /test/lib + * @compile Basic.java + * @compile BasicBoolean.java + * @compile BasicBooleanObject.java + * @compile BasicByte.java + * @compile BasicByteObject.java + * @compile BasicChar.java + * @compile BasicCharObject.java + * @compile BasicShort.java + * @compile BasicShortObject.java + * @compile BasicInt.java + * @compile BasicIntObject.java + * @compile BasicLong.java + * @compile BasicLongObject.java + * @compile BasicBigInteger.java + * @compile BasicFloat.java + * @compile BasicFloatObject.java + * @compile BasicDouble.java + * @compile BasicDoubleObject.java + * @compile BasicBigDecimal.java + * @compile BasicDateTime.java + * @bug 4906370 4962433 4973103 4989961 5005818 5031150 4970931 4989491 5002937 + * 5005104 5007745 5061412 5055180 5066788 5088703 6317248 6318369 6320122 + * 6344623 6369500 6534606 6282094 6286592 6476425 5063507 6469160 6476168 + * 8059175 8204229 + * + * @run junit BasicTestLauncher + */ +public class BasicTestLauncher { + // Locale flag for testJVM + private static final String JAVA_OPTS = "-Djava.locale.providers=CLDR"; + // Test class + private static final String TEST_CLASS = "Basic"; + + /** + * Executes Formatter Basic tests + * @param timeZone the time zone to run tests against + */ + @ParameterizedTest + @ValueSource(strings = { "US/Pacific", "Asia/Novosibirsk" }) + void testTimeZone(String timeZone) throws IOException{ + System.out.printf("$$$ Testing against %s!%n", timeZone); + OutputAnalyzer output = RunTest(timeZone); + CheckTest(output); + System.out.printf("$$$ %s passed as expected!%n", timeZone); + } + + /** + * Creates and runs the testJVM process using Basic class + * @param timeZone the time zone to be set in the testJVM environment + */ + private static OutputAnalyzer RunTest(String timeZone) throws IOException{ + // Build and run Basic class with correct configuration + ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder(JAVA_OPTS, TEST_CLASS); + pb.environment().put("TZ", timeZone); + Process process = pb.start(); + return new OutputAnalyzer(process); + } + + /** + * Validates if the testJVM process passed all tests + * @param output is an Output Analyzer for the testJVM + * @throws RuntimeException for all testJVM failures + */ + private static void CheckTest(OutputAnalyzer output){ + output.shouldHaveExitValue(0) + .reportDiagnosticSummary(); + } +} diff --git a/test/jdk/java/util/TimeZone/CustomTzIDCheckDST.java b/test/jdk/java/util/TimeZone/CustomTzIDCheckDST.java index 28afa8f49e1..ece90a9d7cd 100644 --- a/test/jdk/java/util/TimeZone/CustomTzIDCheckDST.java +++ b/test/jdk/java/util/TimeZone/CustomTzIDCheckDST.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2023, Oracle and/or its affiliates. All rights reserved. * 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 CustomTzIDCheckDST { private static String CUSTOM_TZ2 = "MEZ-1MESZ,M10.5.0,M3.5.0/3"; public static void main(String args[]) throws Throwable { if (args.length == 0) { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(List.of("CustomTzIDCheckDST", "runTZTest")); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(List.of("CustomTzIDCheckDST", "runTZTest")); pb.environment().put("TZ", CUSTOM_TZ); OutputAnalyzer output = ProcessTools.executeProcess(pb); output.shouldHaveExitValue(0); diff --git a/test/jdk/java/util/concurrent/tck/JSR166TestCase.java b/test/jdk/java/util/concurrent/tck/JSR166TestCase.java index 811e32a84c8..2cfa99866c5 100644 --- a/test/jdk/java/util/concurrent/tck/JSR166TestCase.java +++ b/test/jdk/java/util/concurrent/tck/JSR166TestCase.java @@ -592,7 +592,6 @@ public static Test suite() { ScheduledExecutorSubclassTest.suite(), SemaphoreTest.suite(), SynchronousQueueTest.suite(), - SystemTest.suite(), ThreadLocalTest.suite(), ThreadPoolExecutorTest.suite(), ThreadPoolExecutorSubclassTest.suite(), diff --git a/test/jdk/java/util/concurrent/tck/SystemTest.java b/test/jdk/java/util/concurrent/tck/SystemTest.java deleted file mode 100644 index c34bdabea31..00000000000 --- a/test/jdk/java/util/concurrent/tck/SystemTest.java +++ /dev/null @@ -1,75 +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. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please 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: - * - * Written by Doug Lea with assistance from members of JCP JSR-166 - * Expert Group and released to the public domain, as explained at - * http://creativecommons.org/publicdomain/zero/1.0/ - * Other contributors include Andrew Wright, Jeffrey Hayes, - * Pat Fisher, Mike Judd. - */ - -import junit.framework.Test; -import junit.framework.TestSuite; - -public class SystemTest extends JSR166TestCase { - public static void main(String[] args) { - main(suite(), args); - } - - public static Test suite() { - return new TestSuite(SystemTest.class); - } - - /** - * Worst case rounding for millisecs; set for 60 cycle millis clock. - * This value might need to be changed on JVMs with coarser - * System.currentTimeMillis clocks. - */ - static final long MILLIS_ROUND = 17; - - /** - * Nanos between readings of millis is no longer than millis (plus - * possible rounding), and vice versa. - * This shows only that nano timing not (much) worse than milli. - */ - public void testNanoTime() throws InterruptedException { - long m0 = System.currentTimeMillis(); - long n0 = System.nanoTime(); - Thread.sleep(1); - long m1 = System.currentTimeMillis(); - long n1 = System.nanoTime(); - Thread.sleep(50); // avoid possibly scaled SHORT_DELAY_MS - long m2 = System.currentTimeMillis(); - long n2 = System.nanoTime(); - Thread.sleep(1); - long m3 = System.currentTimeMillis(); - long n3 = System.nanoTime(); - assertTrue((n2 - n1) / 1_000_000 <= m3 - m0 + MILLIS_ROUND); - assertTrue(m2 - m1 <= (n3 - n0) / 1_000_000 + MILLIS_ROUND); - } -} diff --git a/test/jdk/java/util/zip/CopyZipFile.java b/test/jdk/java/util/zip/CopyZipFile.java index e6fa4bfe057..ae90e4b6400 100644 --- a/test/jdk/java/util/zip/CopyZipFile.java +++ b/test/jdk/java/util/zip/CopyZipFile.java @@ -23,99 +23,120 @@ /** * @test + * @bug 8253952 * @summary Test behaviour when copying ZipEntries between zip files. - * @run main/othervm CopyZipFile + * @run junit CopyZipFile */ -import java.io.File; -import java.io.ByteArrayOutputStream; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; import java.util.Enumeration; import java.util.regex.Matcher; import java.util.regex.Pattern; -import java.util.zip.CRC32; -import java.util.zip.Deflater; -import java.util.zip.ZipEntry; -import java.util.zip.ZipException; -import java.util.zip.ZipFile; -import java.util.zip.ZipInputStream; -import java.util.zip.ZipOutputStream; +import java.util.zip.*; + +import static org.junit.jupiter.api.Assertions.*; public class CopyZipFile { - private static final String ZIP_FILE = "first.zip"; - private static final String TEST_STRING = "TestTestTest"; + // ZIP file created in this test + private Path zip = Path.of("first.zip"); + // The content to put in each entry + private static final byte[] TEST_STRING = "TestTestTest".getBytes(StandardCharsets.UTF_8); - private static void createZip(String zipFile) throws Exception { - File f = new File(zipFile); - f.deleteOnExit(); - try (OutputStream os = new FileOutputStream(f); + /** + * Create the sample ZIP file used in this test, including a STORED entry + * and DEFLATE entries with various compression levels. + * @throws IOException if an unexpected IOException occurs + */ + @BeforeEach + public void createZip() throws IOException { + // By default, ZipOutputStream creates zip files with Local File Headers + // without size, compressed size and crc values and an extra Data + // Descriptor (see https://en.wikipedia.org/wiki/Zip_(file_format) + // after the data belonging to that entry with these values if in the + // corresponding ZipEntry one of the size, compressedSize or crc fields is + // equal to '-1' (which is the default for newly created ZipEntries). + try (OutputStream os = Files.newOutputStream(zip) ; ZipOutputStream zos = new ZipOutputStream(os)) { // First file will be compressed with DEFAULT_COMPRESSION (i.e. -1 or 6) - zos.putNextEntry(new ZipEntry("test1.txt")); - zos.write(TEST_STRING.getBytes()); - zos.closeEntry(); + zos.setLevel(Deflater.DEFAULT_COMPRESSION); + zos.putNextEntry(new ZipEntry("DEFAULT_COMPRESSION.txt")); + zos.write(TEST_STRING); + // Second file won't be compressed at all (i.e. STORED) zos.setMethod(ZipOutputStream.STORED); - ZipEntry ze = new ZipEntry("test2.txt"); - int length = TEST_STRING.length(); - ze.setSize(length); - ze.setCompressedSize(length); + ZipEntry ze = new ZipEntry("STORED.txt"); + ze.setSize(TEST_STRING.length); + ze.setCompressedSize(TEST_STRING.length); CRC32 crc = new CRC32(); - crc.update(TEST_STRING.getBytes("utf8"), 0, length); + crc.update(TEST_STRING); ze.setCrc(crc.getValue()); zos.putNextEntry(ze); - zos.write(TEST_STRING.getBytes()); + zos.write(TEST_STRING); + // Third file will be compressed with NO_COMPRESSION (i.e. 0) zos.setMethod(ZipOutputStream.DEFLATED); zos.setLevel(Deflater.NO_COMPRESSION); - zos.putNextEntry(new ZipEntry("test3.txt")); - zos.write(TEST_STRING.getBytes()); + zos.putNextEntry(new ZipEntry("NO_COMPRESSION.txt")); + zos.write(TEST_STRING); + // Fourth file will be compressed with BEST_SPEED (i.e. 1) zos.setLevel(Deflater.BEST_SPEED); - zos.putNextEntry(new ZipEntry("test4.txt")); - zos.write(TEST_STRING.getBytes()); + zos.putNextEntry(new ZipEntry("BEST_SPEED.txt")); + zos.write(TEST_STRING); + // Fifth file will be compressed with BEST_COMPRESSION (i.e. 9) zos.setLevel(Deflater.BEST_COMPRESSION); - zos.putNextEntry(new ZipEntry("test5.txt")); - zos.write(TEST_STRING.getBytes()); + zos.putNextEntry(new ZipEntry("BEST_COMPRESSION.txt")); + zos.write(TEST_STRING); } } - public static void main(String args[]) throws Exception { - // By default, ZipOutputStream creates zip files with Local File Headers - // without size, compressedSize and crc values and an extra Data - // Descriptor (see https://en.wikipedia.org/wiki/Zip_(file_format) - // after the data belonging to that entry with these values if in the - // corresponding ZipEntry one of the size, compressedSize or crc fields is - // equal to '-1' (which is the default for newly created ZipEntries). - createZip(ZIP_FILE); - - // Now read all the entries of the newly generated zip file with a ZipInputStream - // and copy them to a new zip file with the help of a ZipOutputStream. - // This only works reliably because the generated zip file has no values for the - // size, compressedSize and crc values of a zip entry in the local file header and - // therefore the ZipEntry objects created by ZipOutputStream.getNextEntry() will have - // all these fields set to '-1'. - ZipEntry entry; - byte[] buf = new byte[512]; - try (InputStream is = new FileInputStream(ZIP_FILE); - ZipInputStream zis = new ZipInputStream(is); - OutputStream os = new ByteArrayOutputStream(); - ZipOutputStream zos = new ZipOutputStream(os)) { - while((entry = zis.getNextEntry())!=null) { + /** + * Delete the ZIP file produced by this test + * @throws IOException if an unexpected IOException occurs + */ + @AfterEach + public void cleanup() throws IOException { + Files.deleteIfExists(zip); + } + + /** + * Read all entries using ZipInputStream.getNextEntry and copy them + * to a new zip file using ZipOutputStream.putNextEntry. This only works + * reliably because the input zip file has no values for the size, compressedSize + * and crc values of streamed zip entries in the local file header and + * therefore the ZipEntry objects created by ZipOutputStream.getNextEntry + * will have all these fields set to '-1'. + * + * @throws IOException if an unexpected IOException occurs + */ + @Test + public void copyFromZipInputStreamToZipOutputStream() throws IOException { + + try (ZipInputStream zis = new ZipInputStream(Files.newInputStream(zip)); + ZipOutputStream zos = new ZipOutputStream(OutputStream.nullOutputStream())) { + ZipEntry entry; + while ((entry = zis.getNextEntry()) != null) { // ZipInputStream.getNextEntry() only reads the Local File Header of a zip entry, // so for the zip file we've just generated the ZipEntry fields 'size', 'compressedSize` // and 'crc' for deflated entries should be uninitialized (i.e. '-1'). System.out.println( - String.format("name=%s, clen=%d, len=%d, crc=%d", - entry.getName(), entry.getCompressedSize(), entry.getSize(), entry.getCrc())); - if (entry.getMethod() == ZipEntry.DEFLATED && - (entry.getCompressedSize() != -1 || entry.getSize() != -1 || entry.getCrc() != -1)) { - throw new Exception("'size', 'compressedSize' and 'crc' shouldn't be initialized at this point."); + String.format("name=%s, clen=%d, len=%d, crc=%d", + entry.getName(), entry.getCompressedSize(), entry.getSize(), entry.getCrc())); + if (entry.getMethod() == ZipEntry.DEFLATED) { + // Expect size, compressed size and crc to not be initialized at this point + assertEquals(-1, entry.getCompressedSize()); + assertEquals(-1, entry.getSize()); + assertEquals(-1, entry.getCrc()); } zos.putNextEntry(entry); zis.transferTo(zos); @@ -124,29 +145,37 @@ public static void main(String args[]) throws Exception { // Descriptor (if any) after the data and will have updated the 'size', 'compressedSize' and 'crc' // fields of the ZipEntry object. System.out.println( - String.format("name=%s, clen=%d, len=%d, crc=%d\n", - entry.getName(), entry.getCompressedSize(), entry.getSize(), entry.getCrc())); - if (entry.getCompressedSize() == -1 || entry.getSize() == -1) { - throw new Exception("'size' and 'compressedSize' must be initialized at this point."); - } + String.format("name=%s, clen=%d, len=%d, crc=%d\n", + entry.getName(), entry.getCompressedSize(), entry.getSize(), entry.getCrc())); + // Expect size, compressed size and crc to be initialized at this point + assertNotEquals(-1, entry.getCompressedSize()); + assertNotEquals(-1, entry.getSize()); + assertNotEquals(-1, entry.getCrc()); } } + } - // Now we read all the entries of the initially generated zip file with the help - // of the ZipFile class. The ZipFile class reads all the zip entries from the Central - // Directory which must have accurate information for size, compressedSize and crc. - // This means that all ZipEntry objects returned from ZipFile will have correct - // settings for these fields. - // If the compression level was different in the initial zip file (which we can't find - // out any more now because the zip file format doesn't record this information) the - // size of the re-compressed entry we are writing to the ZipOutputStream might differ - // from the original compressed size recorded in the ZipEntry. This would result in an - // "invalid entry compressed size" ZipException if ZipOutputStream wouldn't ignore - // the implicitely set compressed size attribute of ZipEntries read from a ZipFile - // or ZipInputStream. - try (OutputStream os = new ByteArrayOutputStream(); - ZipOutputStream zos = new ZipOutputStream(os); - ZipFile zf = new ZipFile(ZIP_FILE)) { + /** + * Read all entries using the ZipFile class and copy them to a new zip file + * using ZipOutputStream.putNextEntry. + * The ZipFile class reads all the zip entries from the Central + * Directory, which has accurate information for size, compressedSize and crc. + * This means that all ZipEntry objects returned from ZipFile will have correct + * settings for these fields. + * If the compression level was different in the input zip file (which we can't know + * because the zip file format doesn't record this information), the + * size of the re-compressed entry we are writing to the ZipOutputStream might differ + * from the original compressed size recorded in the ZipEntry. This would result in an + * "invalid entry compressed size" ZipException if ZipOutputStream wouldn't ignore + * the implicitely set compressed size attribute of ZipEntries read from a ZipFile + * or ZipInputStream. + * @throws IOException if an unexpected IOException occurs + */ + @Test + public void copyFromZipFileToZipOutputStream() throws IOException { + try (ZipOutputStream zos = new ZipOutputStream(OutputStream.nullOutputStream()); + ZipFile zf = new ZipFile(zip.toFile())) { + ZipEntry entry; Enumeration entries = zf.entries(); while (entries.hasMoreElements()) { entry = entries.nextElement(); @@ -154,48 +183,84 @@ public static void main(String args[]) throws Exception { String.format("name=%s, clen=%d, len=%d, crc=%d\n", entry.getName(), entry.getCompressedSize(), entry.getSize(), entry.getCrc())); - if (entry.getCompressedSize() == -1 || entry.getSize() == -1) { - throw new Exception("'size' and 'compressedSize' must be initialized at this point."); - } - InputStream is = zf.getInputStream(entry); + // Expect size, compressed size and crc to be initialized at this point + assertNotEquals(-1, entry.getCompressedSize()); + assertNotEquals(-1, entry.getSize()); + assertNotEquals(-1, entry.getCrc()); + zos.putNextEntry(entry); - is.transferTo(zos); + try (InputStream is = zf.getInputStream(entry)) { + is.transferTo(zos); + } zos.closeEntry(); } } + } + + /** + * If the compressed size is set explicitly using ZipEntry.setCompressedSize(), + * then the entry will be restreamed with a data descriptor and the compressed size + * recomputed. If the source compression level was different from the target compression + * level, the compressed sizes may differ and a ZipException will be thrown + * when the entry is closed in ZipOutputStream.closeEntry + * + * @throws IOException if an unexpected IOException is thrown + */ + @Test + public void explicitCompressedSizeWithDifferentCompressionLevels() throws IOException { + try (ZipOutputStream zos = new ZipOutputStream(OutputStream.nullOutputStream()); + ZipFile zf = new ZipFile(zip.toFile())) { + // Be explicit about the default compression level + zos.setLevel(Deflater.DEFAULT_COMPRESSION); - // The compressed size attribute of a ZipEntry shouldn't be ignored if it was set - // explicitely by calling ZipEntry.setCpompressedSize() - try (OutputStream os = new ByteArrayOutputStream(); - ZipOutputStream zos = new ZipOutputStream(os); - ZipFile zf = new ZipFile(ZIP_FILE)) { Enumeration entries = zf.entries(); while (entries.hasMoreElements()) { - try { - entry = entries.nextElement(); - entry.setCompressedSize(entry.getCompressedSize()); - InputStream is = zf.getInputStream(entry); + ZipEntry entry = entries.nextElement(); + + // Explicitly setting the compressed size will disable data descriptors + // and enable validation that the compressed size in the ZipEntry matches the + // actual compressed size written by ZipOutputStream + entry.setCompressedSize(entry.getCompressedSize()); + + try (InputStream is = zf.getInputStream(entry)) { zos.putNextEntry(entry); is.transferTo(zos); - zos.closeEntry(); - if ("test3.txt".equals(entry.getName())) { - throw new Exception( - "Should throw a ZipException if ZipEntry.setCpompressedSize() was called."); - } - } catch (ZipException ze) { - if ("test1.txt".equals(entry.getName()) || "test2.txt".equals(entry.getName())) { - throw new Exception( - "Shouldn't throw a ZipExcpetion for STORED files or files compressed with DEFAULT_COMPRESSION"); + // Some compression levels lead to unexpected recompressed sizes when closing the entry + switch (entry.getName()) { + case "DEFAULT_COMPRESSION.txt" -> { + // DEFAULT_COMPRESSION matches expected size + zos.closeEntry(); + } + case "STORED.txt" -> { + // STORED should not throw + zos.closeEntry(); + } + case "NO_COMPRESSION.txt", "BEST_SPEED.txt" -> { + // NO_COMPRESSION and BEST_SPEED should lead to an unexpected recompressed size + ZipException ze = assertThrows(ZipException.class, () -> { + zos.closeEntry(); + }); + + // Hack to fix and close the offending zip entry with the correct recompressed size. + // The exception message is something like: + // "invalid entry compressed size (expected 12 but got 7 bytes)" + // and we need to extract the second integer. + Pattern cSize = Pattern.compile("\\d+"); + Matcher m = cSize.matcher(ze.getMessage()); + m.find(); + m.find(); + entry.setCompressedSize(Integer.parseInt(m.group())); + zos.closeEntry(); + } + case "BEST_COMPRESSION.txt" -> { + // BEST_COMPRESSION produces the same compressed + // size as DEFAULT_COMPRESSION for sample content + zos.closeEntry(); + } + default -> { + throw new IllegalArgumentException("Unexpected entry " + entry.getName()); + } } - // Hack to fix and close the offending zip entry with the correct compressed size. - // The exception message is something like: - // "invalid entry compressed size (expected 12 but got 7 bytes)" - // and we need to extract the second integer. - Pattern cSize = Pattern.compile("\\d+"); - Matcher m = cSize.matcher(ze.getMessage()); - m.find(); - m.find(); - entry.setCompressedSize(Integer.parseInt(m.group())); } } } diff --git a/test/jdk/java/util/zip/DeflaterDictionaryTests.java b/test/jdk/java/util/zip/DeflaterDictionaryTests.java index 17d2b735806..ebbe441e70d 100644 --- a/test/jdk/java/util/zip/DeflaterDictionaryTests.java +++ b/test/jdk/java/util/zip/DeflaterDictionaryTests.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2020, 2024 Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -95,9 +95,9 @@ public void testByteArray(int dictionary_offset) throws Exception { deflater.setInput(input); deflater.finish(); int compressedDataLength = deflater.deflate(output, 0, output.length, Deflater.NO_FLUSH); - System.out.printf("Deflater::getTotalOut:%s, Deflater::getAdler: %s," + - " compressed length: %s%n", deflater.getTotalOut(), - deflater.getTotalOut(), compressedDataLength); + System.out.printf("Deflater::getBytesWritten:%d, Deflater::getAdler: %d," + + " compressed length: %d%n", deflater.getBytesWritten(), + deflater.getAdler(), compressedDataLength); deflater.finished(); // Decompress the bytes @@ -112,7 +112,7 @@ public void testByteArray(int dictionary_offset) throws Exception { System.out.println("Did not need to use a Dictionary"); } inflater.finished(); - System.out.printf("Inflater::getAdler:%s, length: %s%n", + System.out.printf("Inflater::getAdler:%d, length: %d%n", inflater.getAdler(), resultLength); Assert.assertEquals(SRC_DATA.length(), resultLength); @@ -143,9 +143,9 @@ public void testHeapByteBuffer() throws Exception { deflater.setInput(input); deflater.finish(); int compressedDataLength = deflater.deflate(output, 0, output.length, Deflater.NO_FLUSH); - System.out.printf("Deflater::getTotalOut:%s, Deflater::getAdler: %s," + - " compressed length: %s%n", deflater.getTotalOut(), - deflater.getTotalOut(), compressedDataLength); + System.out.printf("Deflater::getBytesWritten:%d, Deflater::getAdler: %d," + + " compressed length: %d%n", deflater.getBytesWritten(), + deflater.getAdler(), compressedDataLength); deflater.finished(); // Decompress the bytes @@ -160,7 +160,7 @@ public void testHeapByteBuffer() throws Exception { System.out.println("Did not need to use a Dictionary"); } inflater.finished(); - System.out.printf("Inflater::getAdler:%s, length: %s%n", + System.out.printf("Inflater::getAdler:%d, length: %d%n", inflater.getAdler(), resultLength); Assert.assertEquals(SRC_DATA.length(), resultLength); @@ -197,9 +197,9 @@ public void testByteBufferDirect() throws Exception { deflater.setInput(input); deflater.finish(); int compressedDataLength = deflater.deflate(output, 0, output.length, Deflater.NO_FLUSH); - System.out.printf("Deflater::getTotalOut:%s, Deflater::getAdler: %s," + - " compressed length: %s%n", deflater.getTotalOut(), - deflater.getTotalOut(), compressedDataLength); + System.out.printf("Deflater::getBytesWritten:%d, Deflater::getAdler: %d," + + " compressed length: %d%n", deflater.getBytesWritten(), + deflater.getAdler(), compressedDataLength); deflater.finished(); // Decompress the bytes @@ -214,7 +214,7 @@ public void testByteBufferDirect() throws Exception { System.out.println("Did not need to use a Dictionary"); } inflater.finished(); - System.out.printf("Inflater::getAdler:%s, length: %s%n", + System.out.printf("Inflater::getAdler:%d, length: %d%n", inflater.getAdler(), resultLength); Assert.assertEquals(SRC_DATA.length(), resultLength); diff --git a/test/jdk/java/util/zip/ZipFile/CenSizeTooLarge.java b/test/jdk/java/util/zip/ZipFile/CenSizeTooLarge.java new file mode 100644 index 00000000000..4336377e0c8 --- /dev/null +++ b/test/jdk/java/util/zip/ZipFile/CenSizeTooLarge.java @@ -0,0 +1,226 @@ +/* + * Copyright (c) 2022, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute 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 8272746 + * @summary Verify that ZipFile rejects a ZIP with a CEN size which does not fit in a Java byte array + * @run junit CenSizeTooLarge + */ + +import org.junit.Before; +import org.junit.Test; + +import java.io.*; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.channels.FileChannel; +import java.nio.charset.StandardCharsets; +import java.time.LocalDateTime; +import java.util.Arrays; +import java.util.zip.ZipEntry; +import java.util.zip.ZipException; +import java.util.zip.ZipFile; +import java.util.zip.ZipOutputStream; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +public class CenSizeTooLarge { + // Maximum allowed CEN size allowed by the ZipFile implementation + static final int MAX_CEN_SIZE = Integer.MAX_VALUE - ZipFile.ENDHDR - 1; + + /** + * From the APPNOTE.txt specification: + * 4.4.10 file name length: (2 bytes) + * 4.4.11 extra field length: (2 bytes) + * 4.4.12 file comment length: (2 bytes) + * + * The length of the file name, extra field, and comment + * fields respectively. The combined length of any + * directory record and these three fields SHOULD NOT + * generally exceed 65,535 bytes. + * + * Since ZipOutputStream does not enforce the 'combined length' clause, + * we simply use 65,535 (0xFFFF) for the purpose of this test. + */ + static final int MAX_EXTRA_FIELD_SIZE = 65_535; + + // Data size (unsigned short) + // Field size minus the leading header 'tag' and 'data size' fields (2 bytes each) + static final short MAX_DATA_SIZE = (short) (MAX_EXTRA_FIELD_SIZE - 2 * Short.BYTES); + + // Tag for the 'unknown' field type, specified in APPNOTE.txt 'Third party mappings' + static final short UNKNOWN_ZIP_TAG = (short) 0x9902; + + // Entry names produced in this test are fixed-length + public static final int NAME_LENGTH = 10; + + // Use a shared LocalDateTime on all entries to save processing time + static final LocalDateTime TIME_LOCAL = LocalDateTime.now(); + + // The size of one CEN header, including the name and the extra field + static final int CEN_HEADER_SIZE = ZipFile.CENHDR + NAME_LENGTH + MAX_EXTRA_FIELD_SIZE; + + // The number of entries needed to exceed the MAX_CEN_SIZE + static final int NUM_ENTRIES = (MAX_CEN_SIZE / CEN_HEADER_SIZE) + 1; + + // Helps SparseOutputStream detect write of the last CEN entry + private static final String LAST_CEN_COMMENT = "LastCEN"; + private static final byte[] LAST_CEN_COMMENT_BYTES = LAST_CEN_COMMENT.getBytes(StandardCharsets.UTF_8); + + // Expected ZipException message when the CEN does not fit in a Java byte array + private static final String CEN_TOO_LARGE_MESSAGE = "invalid END header (central directory size too large)"; + + // Zip file to create for testing + private File hugeZipFile; + + /** + * Create a zip file with a CEN size which does not fit within a Java byte array + */ + @Before + public void setup() throws IOException { + hugeZipFile = new File("cen-too-large.zip"); + hugeZipFile.deleteOnExit(); + + try (OutputStream out = new SparseOutputStream(new FileOutputStream(hugeZipFile)); + ZipOutputStream zip = new ZipOutputStream(out)) { + + // Keep track of entries so we can update extra data before the CEN is written + ZipEntry[] entries = new ZipEntry[NUM_ENTRIES]; + + // Add entries until MAX_CEN_SIZE is reached + for (int i = 0; i < NUM_ENTRIES; i++) { + // Create a fixed-length name for the entry + String name = Integer.toString(i); + name = "0".repeat(NAME_LENGTH - name.length()) + name; + + // Create and track the entry + ZipEntry entry = entries[i] = new ZipEntry(name); + + // Use STORED for faster processing + entry.setMethod(ZipEntry.STORED); + entry.setSize(0); + entry.setCrc(0); + + // Set the time/date field for faster processing + entry.setTimeLocal(TIME_LOCAL); + + if (i == NUM_ENTRIES -1) { + // Help SparseOutputStream detect the last CEN entry write + entry.setComment(LAST_CEN_COMMENT); + } + // Add the entry + zip.putNextEntry(entry); + + + } + // Finish writing the last entry + zip.closeEntry(); + + // Before the CEN headers are written, set the extra data on each entry + byte[] extra = makeLargeExtraField(); + for (ZipEntry entry : entries) { + entry.setExtra(extra); + } + } + } + + /** + * Validates that a ZipException is thrown with the expected message when + * the ZipFile is initialized with a ZIP whose CEN exeeds {@link #MAX_CEN_SIZE} + */ + @Test + public void centralDirectoryTooLargeToFitInByteArray() { + ZipException ex = assertThrows(ZipException.class, () -> new ZipFile(hugeZipFile)); + assertEquals(CEN_TOO_LARGE_MESSAGE, ex.getMessage()); + } + + /** + * We can reduce the number of written CEN headers by making each CEN header maximally large. + * We do this by adding the extra field produced by this method to each CEN header. + *

    + * The structure of an extra field is as follows: + *

    + * Header ID (Two bytes, describes the type of the field, also called 'tag') + * Data Size (Two byte short) + * Data Block (Contents depend on field type) + */ + private byte[] makeLargeExtraField() { + // Make a maximally sized extra field + byte[] extra = new byte[MAX_EXTRA_FIELD_SIZE]; + // Little-endian ByteBuffer for updating the header fields + ByteBuffer buffer = ByteBuffer.wrap(extra).order(ByteOrder.LITTLE_ENDIAN); + + // We use the 'unknown' tag, specified in APPNOTE.TXT, 4.6.1 Third party mappings' + buffer.putShort(UNKNOWN_ZIP_TAG); + + // Size of the actual (empty) data + buffer.putShort(MAX_DATA_SIZE); + return extra; + } + + /** + * By writing sparse 'holes' until the last CEN is detected, we can save disk space + * used by this test from ~2GB to ~4K. Instances of this class should be passed + * directly to the ZipOutputStream constructor, without any buffering. Otherwise, + * writes from ZipOutputStream may not be detected correctly. + */ + private static class SparseOutputStream extends FilterOutputStream { + private final FileChannel channel; + private boolean sparse = true; // True until the last CEN is written + private long position = 0; + + public SparseOutputStream(FileOutputStream fos) { + super(fos); + this.channel = fos.getChannel(); + } + + @Override + public void write(byte[] b, int off, int len) throws IOException { + position += len; + if (sparse) { + // Until finding the last CEN, we don't actually write anything, + // but instead simply advance the position, creating a sparse file + channel.position(position); + // Check for last CEN record + if (Arrays.equals(LAST_CEN_COMMENT_BYTES, 0, LAST_CEN_COMMENT_BYTES.length, b, off, len)) { + // From here on, write actual bytes + sparse = false; + } + } else { + // Regular write + out.write(b, off, len); + } + } + + @Override + public void write(int b) throws IOException { + position++; + if (sparse) { + channel.position(position); + } else { + out.write(b); + } + } + } +} diff --git a/test/jdk/java/util/zip/ZipFile/CopyJar.java b/test/jdk/java/util/zip/ZipFile/CopyJar.java deleted file mode 100644 index abeb1f3c462..00000000000 --- a/test/jdk/java/util/zip/ZipFile/CopyJar.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please 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 1.1 99/06/01 - @bug 4239446 - @summary Make sure the ZipEntry fields are correct. - */ - -import java.io.*; -import java.util.zip.*; - -public class CopyJar { - public static void main(String args[]) throws Exception { - try (ZipFile zf = new ZipFile(new File(System.getProperty("test.src", "."), - "input.jar"))) { - ZipEntry ze = zf.getEntry("ReleaseInflater.java"); - ZipOutputStream zos = new ZipOutputStream(new ByteArrayOutputStream()); - InputStream in = zf.getInputStream(ze); - byte[] b = new byte[128]; - int n; - zos.putNextEntry(ze); - while((n = in.read(b)) != -1) { - zos.write(b, 0, n); - } - zos.close(); - } - } -} diff --git a/test/jdk/java/util/zip/ZipFile/EnumAfterClose.java b/test/jdk/java/util/zip/ZipFile/EnumAfterClose.java deleted file mode 100644 index 38c00466e8f..00000000000 --- a/test/jdk/java/util/zip/ZipFile/EnumAfterClose.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -/* @test - @bug 4290060 - @summary Check if the zip file is closed before access any - elements in the Enumeration. - */ - -import java.io.*; -import java.util.zip.*; -import java.util.Enumeration; - -public class EnumAfterClose { - public static void main(String args[]) throws Exception { - Enumeration e; - try (ZipFile zf = new ZipFile(new File(System.getProperty("test.src", "."), - "input.zip"))) { - e = zf.entries(); - } - // ensure that the ZipFile is closed before checking the Enumeration - try { - if (e.hasMoreElements()) { - ZipEntry ze = (ZipEntry)e.nextElement(); - } - } catch (IllegalStateException ie) { - } - } -} diff --git a/test/jdk/java/util/zip/ZipFile/EnumerateAfterClose.java b/test/jdk/java/util/zip/ZipFile/EnumerateAfterClose.java new file mode 100644 index 00000000000..e165e5d2a0a --- /dev/null +++ b/test/jdk/java/util/zip/ZipFile/EnumerateAfterClose.java @@ -0,0 +1,94 @@ +/* + * Copyright (c) 2000, 2024, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute 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 4290060 + @summary Check if the zip file is closed before access any + elements in the Enumeration. + @run junit EnumerateAfterClose + */ + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.io.OutputStream; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Enumeration; +import java.util.zip.ZipEntry; +import java.util.zip.ZipFile; +import java.util.zip.ZipOutputStream; + +import static org.junit.jupiter.api.Assertions.assertThrows; + +public class EnumerateAfterClose { + + // ZIP file used in this test + private Path zip = Path.of("enum-after-close.zip"); + + /** + * Create a sample ZIP file for use by this test + * @throws IOException if an unexpected IOException occurs + */ + @BeforeEach + public void setUp() throws IOException { + try (OutputStream out = Files.newOutputStream(zip); + ZipOutputStream zo = new ZipOutputStream(out)) { + zo.putNextEntry(new ZipEntry("file.txt")); + zo.write("hello".getBytes(StandardCharsets.UTF_8)); + } + } + + /** + * Delete the ZIP file produced by this test + * @throws IOException if an unexpected IOException occurs + */ + @AfterEach + public void cleanup() throws IOException { + Files.deleteIfExists(zip); + } + + /** + * Attempting to using a ZipEntry Enumeration after its backing + * ZipFile is closed should throw IllegalStateException. + * + * @throws IOException if an unexpected IOException occurs + */ + @Test + public void enumeratingAfterCloseShouldThrowISE() throws IOException { + // Retain a reference to an enumeration backed by a closed ZipFile + Enumeration e; + try (ZipFile zf = new ZipFile(zip.toFile())) { + e = zf.entries(); + } + // Using the enumeration after the ZipFile is closed should throw ISE + assertThrows(IllegalStateException.class, () -> { + if (e.hasMoreElements()) { + ZipEntry ze = (ZipEntry)e.nextElement(); + } + }); + } +} diff --git a/test/jdk/java/util/zip/ZipFile/FinalizeInflater.java b/test/jdk/java/util/zip/ZipFile/FinalizeInflater.java index e80fd749076..254f1d445ea 100644 --- a/test/jdk/java/util/zip/ZipFile/FinalizeInflater.java +++ b/test/jdk/java/util/zip/ZipFile/FinalizeInflater.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2010, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -24,20 +24,64 @@ /* @test @bug 7003462 @summary Make sure cached Inflater does not get finalized. + @run junit FinalizeInflater */ -import java.io.File; -import java.io.InputStream; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; +import java.util.zip.ZipOutputStream; public class FinalizeInflater { - public static void main(String[] args) throws Throwable { - try (ZipFile zf = new ZipFile(new File(System.getProperty("test.src", "."), "input.zip"))) - { - ZipEntry ze = zf.getEntry("ReadZip.java"); + // ZIP file produced by this test + private Path zip = Path.of("finalize-inflater.zip"); + + /** + * Create the sample ZIP used in this test + * + * @throws IOException if an unexpected IOException occurs + */ + @BeforeEach + public void setUp() throws IOException { + try (OutputStream out = Files.newOutputStream(zip); + ZipOutputStream zo = new ZipOutputStream(out)) { + zo.putNextEntry(new ZipEntry("file.txt")); + byte[] hello = "hello".getBytes(StandardCharsets.UTF_8); + for (int i = 0; i < 100; i++) { + zo.write(hello); + } + } + } + + /** + * Delete the ZIP file produced by this test + * + * @throws IOException if an unexpected IOException occurs + */ + @AfterEach + public void cleanup() throws IOException { + Files.deleteIfExists(zip); + } + + /** + * A cached Inflater should not be made invalid by finalization + * + * @throws IOException if an unexpected IOException occurs + */ + @Test + public void shouldNotFinalizeInflaterInPool() throws IOException { + try (ZipFile zf = new ZipFile(zip.toFile())) { + ZipEntry ze = zf.getEntry("file.txt"); read(zf.getInputStream(ze)); System.gc(); System.runFinalization(); @@ -51,15 +95,10 @@ private static void read(InputStream is) throws IOException { Wrapper wrapper = new Wrapper(is); - byte[] buffer = new byte[32]; - try { - while(is.read(buffer)>0){} - } catch (IOException ioe) { - ioe.printStackTrace(); - } + is.readAllBytes(); } - static class Wrapper{ + static class Wrapper { InputStream is; public Wrapper(InputStream is) { this.is = is; diff --git a/test/jdk/java/util/zip/ZipFile/ReadAfterClose.java b/test/jdk/java/util/zip/ZipFile/ReadAfterClose.java deleted file mode 100644 index 34882451751..00000000000 --- a/test/jdk/java/util/zip/ZipFile/ReadAfterClose.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (c) 2002, 2011, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -/* @test - @bug 4528128 6846616 - @summary Test if reading InputStream of a closed ZipFile crashes VM - @author kladko - */ - - -import java.util.zip.*; -import java.io.*; -import java.util.*; - -public class ReadAfterClose { - public static void main(String[] argv) throws Exception { - InputStream in; - try (ZipFile zf = new ZipFile( - new File(System.getProperty("test.src","."),"crash.jar"))) { - ZipEntry zent = zf.getEntry("Test.java"); - in = zf.getInputStream(zent); - } - // ensure zf is closed at this point - try { - in.read(); - } catch (IOException e) { - return; - } - throw new Exception("Test failed."); - } -} diff --git a/test/jdk/java/util/zip/ZipFile/ReadZip.java b/test/jdk/java/util/zip/ZipFile/ReadZip.java index 33db2552986..5aa9ee82f0f 100644 --- a/test/jdk/java/util/zip/ZipFile/ReadZip.java +++ b/test/jdk/java/util/zip/ZipFile/ReadZip.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -22,185 +22,359 @@ */ /* @test - @bug 4241361 4842702 4985614 6646605 5032358 6923692 6233323 8144977 8186464 + @bug 4241361 4842702 4985614 6646605 5032358 6923692 6233323 8144977 8186464 4401122 8322830 @summary Make sure we can read a zip file. - @key randomness @modules jdk.zipfs + @run junit ReadZip */ -import java.io.*; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; import java.net.URI; -import java.nio.file.Files; -import java.nio.file.FileSystem; -import java.nio.file.FileSystems; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.nio.file.NoSuchFileException; -import java.nio.file.StandardCopyOption; -import java.nio.file.StandardOpenOption; -import java.util.List; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import java.util.Collections; +import java.util.HexFormat; import java.util.Map; -import java.util.zip.*; +import java.util.zip.ZipEntry; +import java.util.zip.ZipException; +import java.util.zip.ZipFile; +import java.util.zip.ZipOutputStream; import static java.nio.charset.StandardCharsets.US_ASCII; +import static org.junit.jupiter.api.Assertions.*; public class ReadZip { - private static void unreached (Object o) - throws Exception - { - // Should never get here - throw new Exception ("Expected exception was not thrown"); + + // ZIP file produced during tests + private Path zip = Path.of("read-zip.zip"); + + /** + * Create a sample ZIP file for use by tests + * @param name name of the ZIP file to create + * @return a sample ZIP file + * @throws IOException if an unexpected IOException occurs + */ + private Path createZip(String name) throws IOException { + Path zip = Path.of(name); + + try (OutputStream out = Files.newOutputStream(zip); + ZipOutputStream zo = new ZipOutputStream(out)) { + zo.putNextEntry(new ZipEntry("file.txt")); + zo.write("hello".getBytes(StandardCharsets.UTF_8)); + } + + return zip; } - public static void main(String args[]) throws Exception { - try (ZipFile zf = new ZipFile(new File(System.getProperty("test.src", "."), - "input.zip"))) { - // Make sure we throw NPE on null objects - try { unreached (zf.getEntry(null)); } - catch (NullPointerException e) {} + /** + * Delete the ZIP file produced after each test method + * @throws IOException if an unexpected IOException occurs + */ + @AfterEach + public void cleanup() throws IOException { + Files.deleteIfExists(zip); + } - try { unreached (zf.getInputStream(null)); } - catch (NullPointerException e) {} + /** + * Make sure we throw NPE when calling getEntry or getInputStream with null params + * + * @throws IOException if an unexpected IOException occurs + */ + @Test + public void nullPointerExceptionOnNullParams() throws IOException { + zip = createZip("null-params.zip"); + try (ZipFile zf = new ZipFile(zip.toFile())) { - ZipEntry ze = zf.getEntry("ReadZip.java"); - if (ze == null) { - throw new Exception("cannot read from zip file"); - } + assertThrows(NullPointerException.class, () -> zf.getEntry(null)); + assertThrows(NullPointerException.class, () -> zf.getInputStream(null)); + + // Sanity check that we can still read an entry + ZipEntry ze = zf.getEntry("file.txt"); + assertNotNull(ze, "cannot read from zip file"); } + } - // Make sure we can read the zip file that has some garbage - // bytes padded at the end. - File newZip = new File(System.getProperty("test.dir", "."), "input2.zip"); - Files.copy(Paths.get(System.getProperty("test.src", ""), "input.zip"), - newZip.toPath(), StandardCopyOption.REPLACE_EXISTING); + /** + * Read the zip file that has some garbage bytes padded at the end + * @throws IOException if an unexpected IOException occurs + */ + @Test + public void bytesPaddedAtEnd() throws IOException { - newZip.setWritable(true); + zip = createZip("bytes-padded.zip"); // pad some bytes - try (OutputStream os = Files.newOutputStream(newZip.toPath(), - StandardOpenOption.APPEND)) { - os.write(1); os.write(3); os.write(5); os.write(7); + try (OutputStream os = Files.newOutputStream(zip, + StandardOpenOption.APPEND)) { + os.write(1); + os.write(3); + os.write(5); + os.write(7); } - try (ZipFile zf = new ZipFile(newZip)) { - ZipEntry ze = zf.getEntry("ReadZip.java"); - if (ze == null) { - throw new Exception("cannot read from zip file"); - } - } finally { - newZip.delete(); + try (ZipFile zf = new ZipFile(zip.toFile())) { + ZipEntry ze = zf.getEntry("file.txt"); + assertNotNull(ze, "cannot read from zip file"); + } + } + + /** + * Verify that we can read a comment from the ZIP + * file's 'End of Central Directory' header + * @throws IOException if an unexpected IOException occurs + */ + @Test + public void readZipFileComment() throws IOException { + + // Create a zip file with a comment in the 'End of Central Directory' header + try (OutputStream out = Files.newOutputStream(zip); + ZipOutputStream zos = new ZipOutputStream(out)) { + ZipEntry ze = new ZipEntry("ZipEntry"); + zos.putNextEntry(ze); + zos.write(1); + zos.write(2); + zos.write(3); + zos.write(4); + zos.closeEntry(); + zos.setComment("This is the comment for testing"); } // Read zip file comment - try { - try (FileOutputStream fos = new FileOutputStream(newZip); - ZipOutputStream zos = new ZipOutputStream(fos)) - { - ZipEntry ze = new ZipEntry("ZipEntry"); - zos.putNextEntry(ze); - zos.write(1); zos.write(2); zos.write(3); zos.write(4); - zos.closeEntry(); - zos.setComment("This is the comment for testing"); - } + try (ZipFile zf = new ZipFile(zip.toFile())) { + ZipEntry ze = zf.getEntry("ZipEntry"); + assertNotNull(ze, "cannot read entry from zip file"); + assertEquals("This is the comment for testing", zf.getComment()); + } + } - try (ZipFile zf = new ZipFile(newZip)) { - ZipEntry ze = zf.getEntry("ZipEntry"); - if (ze == null) - throw new Exception("cannot read entry from zip file"); - if (!"This is the comment for testing".equals(zf.getComment())) - throw new Exception("cannot read comment from zip file"); - } - } finally { - newZip.delete(); - } - - // Read directory entry - try { - try (FileOutputStream fos = new FileOutputStream(newZip); - ZipOutputStream zos = new ZipOutputStream(fos)) - { - ZipEntry ze = new ZipEntry("directory/"); - zos.putNextEntry(ze); - zos.closeEntry(); - } - try (ZipFile zf = new ZipFile(newZip)) { - ZipEntry ze = zf.getEntry("directory/"); - if (ze == null || !ze.isDirectory()) - throw new RuntimeException("read entry \"directory/\" failed"); - try (InputStream is = zf.getInputStream(ze)) { - is.available(); - } catch (Exception x) { - x.printStackTrace(); - } - - ze = zf.getEntry("directory"); - if (ze == null || !ze.isDirectory()) - throw new RuntimeException("read entry \"directory\" failed"); - try (InputStream is = zf.getInputStream(ze)) { - is.available(); - } catch (Exception x) { - x.printStackTrace(); - } + /** + * Verify that a directory entry can be found using the + * name 'directory/' as well as 'directory/' + * + * @throws IOException if an unexpected IOException occurs + */ + @Test + public void readDirectoryEntries() throws IOException { + + // Create a ZIP containing some directory entries + try (OutputStream fos = Files.newOutputStream(zip); + ZipOutputStream zos = new ZipOutputStream(fos)) { + // Add a META-INF directory with STORED compression type + ZipEntry metaInf = new ZipEntry("META-INF/"); + metaInf.setMethod(ZipEntry.STORED); + metaInf.setSize(0); + metaInf.setCrc(0); + zos.putNextEntry(metaInf); + + // Add a regular directory + ZipEntry dir = new ZipEntry("directory/"); + zos.putNextEntry(dir); + zos.closeEntry(); + } + + // Verify directory lookups + try (ZipFile zf = new ZipFile(zip.toFile())) { + // Look up 'directory/' using the full name + ZipEntry ze = zf.getEntry("directory/"); + assertNotNull(ze, "read entry \"directory/\" failed"); + assertTrue(ze.isDirectory(), "read entry \"directory/\" failed"); + assertEquals("directory/", ze.getName()); + + try (InputStream is = zf.getInputStream(ze)) { + is.available(); + } catch (Exception x) { + x.printStackTrace(); } - } finally { - newZip.delete(); - } - - // Throw a FNF exception when read a non-existing zip file - try { unreached (new ZipFile( - new File(System.getProperty("test.src", "."), - "input" - + String.valueOf(new java.util.Random().nextInt()) - + ".zip"))); - } catch (NoSuchFileException nsfe) {} - - // read a zip file with ZIP64 end - Path path = Paths.get(System.getProperty("test.dir", ""), "end64.zip"); - try { - URI uri = URI.create("jar:" + path.toUri()); - Map env = Map.of("create", "true", "forceZIP64End", "true"); - try (FileSystem fs = FileSystems.newFileSystem(uri, env)) { - Files.write(fs.getPath("hello"), "hello".getBytes()); + + // Look up 'directory/' without the trailing slash + ze = zf.getEntry("directory"); + assertNotNull(ze, "read entry \"directory\" failed"); + assertTrue(ze.isDirectory(), "read entry \"directory\" failed"); + assertEquals("directory/", ze.getName()); + + try (InputStream is = zf.getInputStream(ze)) { + is.available(); + } catch (Exception x) { + x.printStackTrace(); } - try (ZipFile zf = new ZipFile(path.toFile())) { - if (!"hello".equals(new String(zf.getInputStream(new ZipEntry("hello")) - .readAllBytes(), - US_ASCII))) - throw new RuntimeException("zipfile: read entry failed"); - } catch (IOException x) { - throw new RuntimeException("zipfile: zip64 end failed"); + // Sanity check that also META-INF/ can be looked up with or without the trailing slash + assertNotNull(zf.getEntry("META-INF")); + assertNotNull(zf.getEntry("META-INF/")); + assertEquals(zf.getEntry("META-INF").getName(), + zf.getEntry("META-INF/").getName()); + } + } + + /** + * Throw a NoSuchFileException exception when reading a non-existing zip file + */ + @Test + public void nonExistingFile() { + File nonExistingFile = new File("non-existing-file-f6804460f.zip"); + assertThrows(NoSuchFileException.class, () -> + new ZipFile(nonExistingFile)); + } + + /** + * Read a Zip file with a 'Zip64 End of Central Directory header' which was created + * using ZipFileSystem with the 'forceZIP64End' option. + * @throws IOException if an unexpected IOException occurs + */ + @Test + public void readZip64EndZipFs() throws IOException { + + // Create zip file with Zip64 end + Map env = Map.of("create", "true", "forceZIP64End", "true"); + try (FileSystem fs = FileSystems.newFileSystem(zip, env)) { + Files.write(fs.getPath("hello"), "hello".getBytes()); + } + // Read using ZipFile + try (ZipFile zf = new ZipFile(zip.toFile())) { + try (InputStream in = zf.getInputStream(zf.getEntry("hello"))) { + assertEquals("hello", new String(in.readAllBytes(), StandardCharsets.US_ASCII)); } - try (FileSystem fs = FileSystems.newFileSystem(uri, Map.of())) { - if (!"hello".equals(new String(Files.readAllBytes(fs.getPath("hello"))))) - throw new RuntimeException("zipfs: read entry failed"); - } catch (IOException x) { - throw new RuntimeException("zipfile: zip64 end failed"); + } + // Read using ZipFileSystem + try (FileSystem fs = FileSystems.newFileSystem(zip, Map.of())) { + assertEquals("hello", new String(Files.readAllBytes(fs.getPath("hello")))); + } + } + + /** + * Read a zip file created via Info-ZIP in streaming mode, + * which includes a 'Zip64 End of Central Directory header'. + * + * @throws IOException if an unexpected IOException occurs + * @throws InterruptedException if an unexpected InterruptedException occurs + */ + @Test + public void readZip64EndInfoZIPStreaming() throws IOException, InterruptedException { + // ZIP created using: "echo -n hello | zip zip64.zip -" + // Hex encoded using: "cat zip64.zip | xxd -ps" + byte[] zipBytes = HexFormat.of().parseHex(""" + 504b03042d0000000000c441295886a61036ffffffffffffffff01001400 + 2d010010000500000000000000050000000000000068656c6c6f504b0102 + 1e032d0000000000c441295886a610360500000005000000010000000000 + 000001000000b011000000002d504b06062c000000000000001e032d0000 + 00000000000000010000000000000001000000000000002f000000000000 + 003800000000000000504b06070000000067000000000000000100000050 + 4b050600000000010001002f000000380000000000 + """.replaceAll("\n","") + ); + + Files.write(zip, zipBytes); + + try (ZipFile zf = new ZipFile(this.zip.toFile())) { + try (InputStream in = zf.getInputStream(zf.getEntry("-"))) { + String contents = new String(in.readAllBytes(), StandardCharsets.US_ASCII); + assertEquals("hello", contents); } - } finally { - Files.deleteIfExists(path); - } - - // read a zip file created via "echo hello | zip dst.zip -", which uses - // ZIP64 end record - if (Files.notExists(Paths.get("/usr/bin/zip"))) - return; - try { - Process zip = new ProcessBuilder("zip", path.toString().toString(), "-").start(); - OutputStream os = zip.getOutputStream(); - os.write("hello".getBytes(US_ASCII)); - os.close(); - zip.waitFor(); - if (zip.exitValue() == 0 && Files.exists(path)) { - try (ZipFile zf = new ZipFile(path.toFile())) { - if (!"hello".equals(new String(zf.getInputStream(new ZipEntry("-")) - .readAllBytes()))) - throw new RuntimeException("zipfile: read entry failed"); - } catch (IOException x) { - throw new RuntimeException("zipfile: zip64 end failed"); - } + } + } + + /** + * Check that the available() method overriden by the input stream returned by + * ZipFile.getInputStream correctly returns the number of remaining uncompressed bytes + * + * @throws IOException if an unexpected IOException occurs + */ + @Test + public void availableShouldReturnRemainingUncompressedBytes() throws IOException { + // The number of uncompressed bytes to write to the sample ZIP entry + final int expectedBytes = 512; + + // Create a sample ZIP with deflated entry of a known uncompressed size + try (ZipOutputStream zo = new ZipOutputStream(Files.newOutputStream(zip))) { + zo.putNextEntry(new ZipEntry("file.txt")); + zo.write(new byte[expectedBytes]); + } + + // Verify the behavior of ZipFileInflaterInputStream.available() + try (ZipFile zf = new ZipFile(zip.toFile())) { + ZipEntry e = zf.getEntry("file.txt"); + try (InputStream in = zf.getInputStream(e)) { + // Initially, available() should return the full uncompressed size of the entry + assertEquals(expectedBytes, in.available(), + "wrong initial return value of available"); + + // Reading a few bytes should reduce the number of available bytes accordingly + int bytesToRead = 10; + in.read(new byte[bytesToRead]); + assertEquals(expectedBytes - bytesToRead, in.available()); + + // Reading all remaining bytes should reduce the number of available bytes to zero + in.transferTo(OutputStream.nullOutputStream()); + assertEquals(0, in.available()); + + // available on a closed input stream should return zero + in.close(); + assertEquals(0, in.available()); } - } finally { - Files.deleteIfExists(path); } } -} + + /** + * Verify that reading an InputStream from a closed ZipFile + * throws IOException as expected and does not crash the VM. + * See bugs: 4528128 6846616 + * + * @throws IOException if an unexpected IOException occurs + */ + @Test + public void readAfterClose() throws IOException { + zip = createZip("read-after-close.zip"); + InputStream in; + try (ZipFile zf = new ZipFile(zip.toFile())) { + ZipEntry zent = zf.getEntry("file.txt"); + in = zf.getInputStream(zent); + } + + // zf is closed at this point + assertThrows(IOException.class, () -> { + in.read(); + }); + assertThrows(IOException.class, () -> { + in.read(new byte[10]); + }); + assertThrows(IOException.class, () -> { + byte[] buf = new byte[10]; + in.read(buf, 0, buf.length); + }); + assertThrows(IOException.class, () -> { + in.readAllBytes(); + }); + } + + /** + * Verify that ZipFile can open a ZIP file with zero entries + * + * @throws IOException if an unexpected IOException occurs + */ + @Test + public void noEntries() throws IOException { + // Create a ZIP file with no entries + try (ZipOutputStream zo = new ZipOutputStream(Files.newOutputStream(zip))) { + } + + // Open the "empty" ZIP file + try (ZipFile zf = new ZipFile(zip.toFile())) { + // Verify size + assertEquals(0, zf.size()); + + // Verify entry lookup using ZipFile.getEntry() + assertNull(zf.getEntry("file.txt")); + + // Verify iteration using ZipFile.entries() + assertEquals(Collections.emptyList(), Collections.list(zf.entries())); + + // Verify iteration using ZipFile.stream() + assertEquals(Collections.emptyList(), zf.stream().toList()); + } + } +} \ No newline at end of file diff --git a/test/jdk/java/util/zip/ZipFile/ReleaseInflater.java b/test/jdk/java/util/zip/ZipFile/ReleaseInflater.java index f20fc12ecc1..49f676ba555 100644 --- a/test/jdk/java/util/zip/ZipFile/ReleaseInflater.java +++ b/test/jdk/java/util/zip/ZipFile/ReleaseInflater.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2024, Oracle and/or its affiliates. All rights reserved. * 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,31 +25,74 @@ * @bug 4214795 * @summary Make sure the same inflater will only be recycled * once. + * @run junit ReleaseInflater */ -import java.io.*; -import java.util.zip.*; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.zip.ZipEntry; +import java.util.zip.ZipFile; +import java.util.zip.ZipOutputStream; + +import static org.junit.jupiter.api.Assertions.assertEquals; public class ReleaseInflater { - public static void main(String[] args) throws Exception { - ZipFile zf = new ZipFile(new File(System.getProperty("test.src"), - "input.jar")); - ZipEntry e = zf.getEntry("ReleaseInflater.java"); + // ZIP file produced in this test + private Path zip = Path.of("release-inflater.zip"); + + /** + * Create a sample ZIP file for use by tests + * @param name name of the ZIP file to create + * @return a sample ZIP file + * @throws IOException if an unexpected IOException occurs + */ + @BeforeEach + public void setUp() throws IOException { + try (ZipOutputStream zo = new ZipOutputStream(Files.newOutputStream(zip))) { + zo.putNextEntry(new ZipEntry("file.txt")); + zo.write("helloworld".getBytes(StandardCharsets.UTF_8)); + } + } + + /** + * Delete the ZIP and JAR files produced after each test method + * @throws IOException if an unexpected IOException occurs + */ + + @AfterEach + public void cleanup() throws IOException { + Files.deleteIfExists(zip); + } + + /** + * Verify that the same Inflater is not recycled across input streams + * @throws IOException if an unexpected IOException occurs + */ + @Test + public void recycleInflaterOnlyOnce() throws IOException { + try (ZipFile zf = new ZipFile(zip.toFile())) { + ZipEntry e = zf.getEntry("file.txt"); - InputStream in1 = zf.getInputStream(e); - // close the stream, the inflater will be released - in1.close(); - // close the stream again, should be no-op - in1.close(); + InputStream in1 = zf.getInputStream(e); + // close the stream, the inflater will be released + in1.close(); + // close the stream again, should be no-op + in1.close(); - // create two new streams, allocating inflaters - InputStream in2 = zf.getInputStream(e); - InputStream in3 = zf.getInputStream(e); + // create two new streams, allocating inflaters + InputStream in2 = zf.getInputStream(e); + InputStream in3 = zf.getInputStream(e); - // check to see if they influence each other - if (in2.read() != in3.read()) { - throw new Exception("Stream is corrupted!"); + // check to see if they influence each other + assertEquals(in2.read(), in3.read(), "Stream is corrupted!"); } } } diff --git a/test/jdk/java/util/zip/ZipFile/StreamZipEntriesTest.java b/test/jdk/java/util/zip/ZipFile/StreamZipEntriesTest.java index 38199e4694c..eaa3708578e 100644 --- a/test/jdk/java/util/zip/ZipFile/StreamZipEntriesTest.java +++ b/test/jdk/java/util/zip/ZipFile/StreamZipEntriesTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,74 +23,169 @@ /** * @test - * @run testng StreamZipEntriesTest + * @run junit StreamZipEntriesTest * @summary Make sure we can stream entries of a zip file. */ -import java.io.File; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + import java.io.IOException; -import java.lang.Object; -import java.lang.System; -import java.util.jar.JarFile; +import java.io.OutputStream; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.HashSet; +import java.util.Set; import java.util.jar.JarEntry; +import java.util.jar.JarFile; +import java.util.jar.JarOutputStream; +import java.util.jar.Manifest; import java.util.stream.Stream; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; +import java.util.zip.ZipOutputStream; -import org.testng.annotations.Test; +import static org.junit.jupiter.api.Assertions.*; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; public class StreamZipEntriesTest { + // ZIP file produced in this test + private Path zip = Path.of("stream.zip"); + // JAR file produced in this test + private Path jar = Path.of("stream.jar"); + + /** + * Create sample ZIP and JAR files used in in this test + * @throws IOException if an unexpected IOException occurs + */ + @BeforeEach + public void setUp() throws IOException { + + try (OutputStream out = Files.newOutputStream(zip); + ZipOutputStream zo = new ZipOutputStream(out)) { + zo.putNextEntry(new ZipEntry("entry1.txt")); + zo.write("hello".getBytes(StandardCharsets.UTF_8)); + zo.putNextEntry(new ZipEntry("entry2.txt")); + zo.write("hello".getBytes(StandardCharsets.UTF_8)); + } + + try (OutputStream out = Files.newOutputStream(jar); + ZipOutputStream zo = new ZipOutputStream(out)) { + // A JAR file may start with a META-INF/ directory before the manifest + zo.putNextEntry(new ZipEntry("META-INF/")); + // Write the manifest + zo.putNextEntry(new ZipEntry("META-INF/MANIFEST.MF")); + new Manifest().write(zo); + + // Write two regular entries + zo.putNextEntry(new ZipEntry("entry1.txt")); + zo.write("hello".getBytes(StandardCharsets.UTF_8)); + zo.putNextEntry(new ZipEntry("entry2.txt")); + zo.write("hello".getBytes(StandardCharsets.UTF_8)); + } + } + + /** + * Delete the ZIP file produced after each test method + * @throws IOException if an unexpected IOException occurs + */ + @AfterEach + public void cleanup() throws IOException { + Files.deleteIfExists(zip); + Files.deleteIfExists(jar); + } + + /** + * Verify that ZipFile.stream() produces the expected entries + * @throws IOException if an unexpected IOException occurs + */ @Test public void testStreamZip() throws IOException { - try (ZipFile zf = new ZipFile(new File(System.getProperty("test.src", "."), "input.zip"))) { - zf.stream().forEach(e -> assertTrue(e instanceof ZipEntry)); - zf.stream().forEach(e -> assertEquals(e.toString(), "ReadZip.java")); + Set names = new HashSet<>(Set.of("entry1.txt", "entry2.txt")); + + try (ZipFile zf = new ZipFile(zip.toFile())) { + zf.stream().forEach(e -> { + assertTrue(e instanceof ZipEntry); + String name = e.getName(); + assertNotNull(names.remove(name)); + String toString = e.toString(); + assertEquals(name, toString); + }); + + // Check that all expected names were processed + assertTrue(names.isEmpty()); + // Check that Stream.toArray produces the expected result Object elements[] = zf.stream().toArray(); - assertEquals(1, elements.length); - assertEquals(elements[0].toString(), "ReadZip.java"); + assertEquals(2, elements.length); + assertEquals(elements[0].toString(), "entry1.txt"); + assertEquals(elements[1].toString(), "entry2.txt"); } } + /** + * Verify that JarFile.stream() produces the expected entries + * @throws IOException if an unexpected IOException occurs + */ @Test public void testStreamJar() throws IOException { - try (JarFile jf = new JarFile(new File(System.getProperty("test.src", "."), "input.jar"))) { - jf.stream().forEach(e -> assertTrue(e instanceof JarEntry)); + try (JarFile jf = new JarFile(jar.toFile())) { + Set names = new HashSet<>(Set.of( + "META-INF/", + "META-INF/MANIFEST.MF", + "entry1.txt", + "entry2.txt" + )); + jf.stream().forEach(e -> { + assertTrue(e instanceof JarEntry); + String name = e.getName(); + assertNotNull(names.remove(name)); + String toString = e.toString(); + assertEquals(name, toString); + } + ); + + // Check that all expected names were processed + assertTrue(names.isEmpty(), "Unprocessed entries: " + names); + + + // Check that Stream.toArray produces the expected result Object elements[] = jf.stream().toArray(); - assertEquals(3, elements.length); + assertEquals(4, elements.length); assertEquals(elements[0].toString(), "META-INF/"); assertEquals(elements[1].toString(), "META-INF/MANIFEST.MF"); - assertEquals(elements[2].toString(), "ReleaseInflater.java"); + assertEquals(elements[2].toString(), "entry1.txt"); + assertEquals(elements[3].toString(), "entry2.txt"); } } + /** + * Calling ZipFile.stream() on a closed ZipFile should throw ISE + * @throws IOException if an unexpected IOException occurs + */ @Test public void testClosedZipFile() throws IOException { - ZipFile zf = new ZipFile(new File(System.getProperty("test.src", "."), "input.zip")); + ZipFile zf = new ZipFile(zip.toFile()); zf.close(); - try { + assertThrows(IllegalStateException.class, () -> { Stream s = zf.stream(); - fail("Should have thrown IllegalStateException"); - } catch (IllegalStateException e) { - // expected; - } + }); } + /** + * Calling JarFile.stream() on a closed JarFile should throw ISE + * @throws IOException if an unexpected IOException occurs + */ @Test public void testClosedJarFile() throws IOException { - JarFile jf = new JarFile(new File(System.getProperty("test.src", "."), "input.jar")); + JarFile jf = new JarFile(jar.toFile()); jf.close(); - try { + assertThrows(IllegalStateException.class, () -> { Stream s = jf.stream(); - fail("Should have thrown IllegalStateException"); - } catch (IllegalStateException e) { - // expected; - } + }); } } diff --git a/test/jdk/java/util/zip/ZipFile/crash.jar b/test/jdk/java/util/zip/ZipFile/crash.jar deleted file mode 100644 index 8de20e7582e..00000000000 Binary files a/test/jdk/java/util/zip/ZipFile/crash.jar and /dev/null differ diff --git a/test/jdk/java/util/zip/ZipFile/input.jar b/test/jdk/java/util/zip/ZipFile/input.jar deleted file mode 100644 index f5e6f573317..00000000000 Binary files a/test/jdk/java/util/zip/ZipFile/input.jar and /dev/null differ diff --git a/test/jdk/java/util/zip/ZipFile/input.zip b/test/jdk/java/util/zip/ZipFile/input.zip deleted file mode 100644 index 2ca60bd4c06..00000000000 Binary files a/test/jdk/java/util/zip/ZipFile/input.zip and /dev/null differ diff --git a/test/jdk/javax/management/remote/mandatory/connection/DefaultAgentFilterTest.java b/test/jdk/javax/management/remote/mandatory/connection/DefaultAgentFilterTest.java index 08ea48807c4..1b036ce2f56 100644 --- a/test/jdk/javax/management/remote/mandatory/connection/DefaultAgentFilterTest.java +++ b/test/jdk/javax/management/remote/mandatory/connection/DefaultAgentFilterTest.java @@ -203,7 +203,7 @@ private static void testDefaultAgent(String propertyFile, int port) throws Excep pbArgs.addAll(Arrays.asList(args)); pbArgs.add(TEST_APP_NAME); - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( pbArgs.toArray(new String[pbArgs.size()]) ); diff --git a/test/jdk/javax/management/security/HashedPasswordFileTest.java b/test/jdk/javax/management/security/HashedPasswordFileTest.java index e7b0af4cab7..ae109b9e930 100644 --- a/test/jdk/javax/management/security/HashedPasswordFileTest.java +++ b/test/jdk/javax/management/security/HashedPasswordFileTest.java @@ -433,7 +433,7 @@ public void testDefaultAgent() throws Exception { pbArgs.add("jdk.management.agent/jdk.internal.agent=ALL-UNNAMED"); pbArgs.add(TestApp.class.getSimpleName()); - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( pbArgs.toArray(new String[0])); Process process = ProcessTools.startProcess( TestApp.class.getSimpleName(), @@ -475,7 +475,7 @@ public void testDefaultAgentNoHash() throws Exception { pbArgs.add("jdk.management.agent/jdk.internal.agent=ALL-UNNAMED"); pbArgs.add(TestApp.class.getSimpleName()); - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( pbArgs.toArray(new String[0])); Process process = ProcessTools.startProcess( TestApp.class.getSimpleName(), diff --git a/test/jdk/javax/net/ssl/DTLS/DTLSWontNegotiateV10.java b/test/jdk/javax/net/ssl/DTLS/DTLSWontNegotiateV10.java index f67a02b3052..f8b72005527 100644 --- a/test/jdk/javax/net/ssl/DTLS/DTLSWontNegotiateV10.java +++ b/test/jdk/javax/net/ssl/DTLS/DTLSWontNegotiateV10.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2023, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,13 +21,13 @@ * questions. */ +import jdk.test.lib.process.ProcessTools; import jdk.test.lib.security.SecurityUtils; import javax.net.ssl.*; import java.io.IOException; import java.net.*; import java.nio.ByteBuffer; -import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; @@ -87,14 +87,13 @@ private static void runServer(String protocol) throws Exception { Process clientProcess = null; try (DTLSServer server = new DTLSServer(protocol)) { List command = List.of( - Path.of(System.getProperty("java.home"), "bin", "java").toString(), "DTLSWontNegotiateV10", // if server is "DTLS" then the client should be v1.0 and vice versa protocol.equals(DTLS) ? DTLSV_1_0 : DTLS, Integer.toString(server.getListeningPortNumber()) ); - ProcessBuilder builder = new ProcessBuilder(command); + ProcessBuilder builder = ProcessTools.createTestJavaProcessBuilder(command); clientProcess = builder.inheritIO().start(); server.run(); System.out.println("Success: DTLSv1.0 connection was not established."); diff --git a/test/jdk/javax/net/ssl/TLSCommon/interop/AbstractServer.java b/test/jdk/javax/net/ssl/TLSCommon/interop/AbstractServer.java index a5f61ce869a..03b3aadb007 100644 --- a/test/jdk/javax/net/ssl/TLSCommon/interop/AbstractServer.java +++ b/test/jdk/javax/net/ssl/TLSCommon/interop/AbstractServer.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2020, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -22,6 +22,8 @@ */ import java.io.IOException; +import java.net.InetAddress; +import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; @@ -52,11 +54,21 @@ public void signalStop() throws Exception { } public static abstract class Builder extends AbstractPeer.Builder { + private InetAddress listenInterface = InetAddress.getLoopbackAddress(); private int port; // Indicates if requires client authentication. private boolean clientAuth = true; + public InetAddress getListenInterface() { + return listenInterface; + } + + public Builder setListenInterface(InetAddress listenInterface) { + this.listenInterface = listenInterface; + return this; + } + public int getPort() { return port; } diff --git a/test/jdk/javax/net/ssl/TLSCommon/interop/JdkServer.java b/test/jdk/javax/net/ssl/TLSCommon/interop/JdkServer.java index 6519e89febb..1521325b65a 100644 --- a/test/jdk/javax/net/ssl/TLSCommon/interop/JdkServer.java +++ b/test/jdk/javax/net/ssl/TLSCommon/interop/JdkServer.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2020, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -22,6 +22,7 @@ */ import java.io.IOException; +import java.net.InetAddress; import java.net.SocketException; import java.util.ArrayList; import java.util.List; @@ -53,7 +54,8 @@ public JdkServer(Builder builder) throws Exception { context = Utilities.createSSLContext(builder.getCertTuple()); SSLServerSocketFactory serverFactory = context.getServerSocketFactory(); serverSocket - = (SSLServerSocket) serverFactory.createServerSocket(builder.getPort()); + = (SSLServerSocket) serverFactory.createServerSocket(builder.getPort(), + 0, builder.getListenInterface()); configServerSocket(builder); } diff --git a/test/jdk/javax/net/ssl/TLSCommon/interop/ProcUtils.java b/test/jdk/javax/net/ssl/TLSCommon/interop/ProcUtils.java index 10cb3d68856..de27f538f70 100644 --- a/test/jdk/javax/net/ssl/TLSCommon/interop/ProcUtils.java +++ b/test/jdk/javax/net/ssl/TLSCommon/interop/ProcUtils.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2020, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -42,7 +42,7 @@ public class ProcUtils { */ public static OutputAnalyzer java(Path javaPath, Class clazz, Map props) { - ProcessBuilder pb = createJavaProcessBuilder(javaPath, clazz, props); + ProcessBuilder pb = createLimitedTestJavaProcessBuilder(javaPath, clazz, props); try { return ProcessTools.executeCommand(pb); } catch (Throwable e) { @@ -50,7 +50,7 @@ public static OutputAnalyzer java(Path javaPath, Class clazz, } } - private static ProcessBuilder createJavaProcessBuilder(Path javaPath, + private static ProcessBuilder createLimitedTestJavaProcessBuilder(Path javaPath, Class clazz, Map props) { List cmds = new ArrayList<>(); cmds.add(javaPath.toString()); diff --git a/test/jdk/javax/net/ssl/ciphersuites/DisabledAlgorithms.java b/test/jdk/javax/net/ssl/ciphersuites/DisabledAlgorithms.java index 855e34b57f0..1dd8be84785 100644 --- a/test/jdk/javax/net/ssl/ciphersuites/DisabledAlgorithms.java +++ b/test/jdk/javax/net/ssl/ciphersuites/DisabledAlgorithms.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2023, Oracle and/or its affiliates. All rights reserved. * 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,6 +25,7 @@ * @test * @bug 8076221 8211883 8279164 * @summary Check if weak cipher suites are disabled + * @library /javax/net/ssl/templates * @modules jdk.crypto.ec * @run main/othervm DisabledAlgorithms default * @run main/othervm DisabledAlgorithms empty @@ -35,7 +36,6 @@ import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; -import java.security.NoSuchAlgorithmException; import java.security.Security; import java.util.concurrent.TimeUnit; import javax.net.ssl.SSLContext; @@ -45,68 +45,72 @@ import javax.net.ssl.SSLSocket; import javax.net.ssl.SSLSocketFactory; +/* + * This test verifies that setEnabledProtocols() does not override the + * jdk.tls.disabledAlgorithms property. Both the client and server throw + * an exception when creating a handshake context. + * + * In the TLSWontNegotiateDisabledCipherAlgoos test, one side of the connection + * disables the cipher suites and the other side enables them and verifies + * that the handshake cannot complete successfully. + */ public class DisabledAlgorithms { - private static final String pathToStores = "../etc"; - private static final String keyStoreFile = "keystore"; - private static final String trustStoreFile = "truststore"; - private static final String passwd = "passphrase"; - - private static final String keyFilename = - System.getProperty("test.src", "./") + "/" + pathToStores + - "/" + keyStoreFile; - - private static final String trustFilename = - System.getProperty("test.src", "./") + "/" + pathToStores + - "/" + trustStoreFile; + public static final SSLContextTemplate.Cert[] CERTIFICATES = { + SSLContextTemplate.Cert.EE_DSA_SHA1_1024, + SSLContextTemplate.Cert.EE_DSA_SHA224_1024, + SSLContextTemplate.Cert.EE_DSA_SHA256_1024, + SSLContextTemplate.Cert.CA_ECDSA_SECP256R1, + SSLContextTemplate.Cert.CA_RSA_2048 + }; // disabled RC4, NULL, anon, and ECDH cipher suites - private static final String[] disabled_ciphersuites - = new String[] { - "TLS_ECDHE_ECDSA_WITH_RC4_128_SHA", - "TLS_ECDHE_RSA_WITH_RC4_128_SHA", - "SSL_RSA_WITH_RC4_128_SHA", - "TLS_ECDH_ECDSA_WITH_RC4_128_SHA", - "TLS_ECDH_RSA_WITH_RC4_128_SHA", - "SSL_RSA_WITH_RC4_128_MD5", - "TLS_ECDH_anon_WITH_RC4_128_SHA", - "SSL_DH_anon_WITH_RC4_128_MD5", - "SSL_RSA_WITH_NULL_MD5", - "SSL_RSA_WITH_NULL_SHA", - "TLS_RSA_WITH_NULL_SHA256", - "TLS_ECDH_ECDSA_WITH_NULL_SHA", - "TLS_ECDHE_ECDSA_WITH_NULL_SHA", - "TLS_ECDH_RSA_WITH_NULL_SHA", - "TLS_ECDHE_RSA_WITH_NULL_SHA", - "TLS_ECDH_anon_WITH_NULL_SHA", - "SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA", - "SSL_DH_anon_EXPORT_WITH_RC4_40_MD5", - "SSL_DH_anon_WITH_3DES_EDE_CBC_SHA", - "SSL_DH_anon_WITH_DES_CBC_SHA", - "SSL_DH_anon_WITH_RC4_128_MD5", - "TLS_DH_anon_WITH_AES_128_CBC_SHA", - "TLS_DH_anon_WITH_AES_128_CBC_SHA256", - "TLS_DH_anon_WITH_AES_128_GCM_SHA256", - "TLS_DH_anon_WITH_AES_256_CBC_SHA", - "TLS_DH_anon_WITH_AES_256_CBC_SHA256", - "TLS_DH_anon_WITH_AES_256_GCM_SHA384", - "TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA", - "TLS_ECDH_anon_WITH_AES_128_CBC_SHA", - "TLS_ECDH_anon_WITH_AES_256_CBC_SHA", - "TLS_ECDH_anon_WITH_NULL_SHA", - "TLS_ECDH_anon_WITH_RC4_128_SHA", - "TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384", - "TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384", - "TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256", - "TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256", - "TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384", - "TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384", - "TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256", - "TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256", - "TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA", - "TLS_ECDH_RSA_WITH_AES_256_CBC_SHA", - "TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA", - "TLS_ECDH_RSA_WITH_AES_128_CBC_SHA" + public static final String[] DISABLED_CIPHERSUITES + = new String[]{ + "TLS_ECDHE_ECDSA_WITH_RC4_128_SHA", + "TLS_ECDHE_RSA_WITH_RC4_128_SHA", + "SSL_RSA_WITH_RC4_128_SHA", + "TLS_ECDH_ECDSA_WITH_RC4_128_SHA", + "TLS_ECDH_RSA_WITH_RC4_128_SHA", + "SSL_RSA_WITH_RC4_128_MD5", + "TLS_ECDH_anon_WITH_RC4_128_SHA", + "SSL_DH_anon_WITH_RC4_128_MD5", + "SSL_RSA_WITH_NULL_MD5", + "SSL_RSA_WITH_NULL_SHA", + "TLS_RSA_WITH_NULL_SHA256", + "TLS_ECDH_ECDSA_WITH_NULL_SHA", + "TLS_ECDHE_ECDSA_WITH_NULL_SHA", + "TLS_ECDH_RSA_WITH_NULL_SHA", + "TLS_ECDHE_RSA_WITH_NULL_SHA", + "TLS_ECDH_anon_WITH_NULL_SHA", + "SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA", + "SSL_DH_anon_EXPORT_WITH_RC4_40_MD5", + "SSL_DH_anon_WITH_3DES_EDE_CBC_SHA", + "SSL_DH_anon_WITH_DES_CBC_SHA", + "SSL_DH_anon_WITH_RC4_128_MD5", + "TLS_DH_anon_WITH_AES_128_CBC_SHA", + "TLS_DH_anon_WITH_AES_128_CBC_SHA256", + "TLS_DH_anon_WITH_AES_128_GCM_SHA256", + "TLS_DH_anon_WITH_AES_256_CBC_SHA", + "TLS_DH_anon_WITH_AES_256_CBC_SHA256", + "TLS_DH_anon_WITH_AES_256_GCM_SHA384", + "TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA", + "TLS_ECDH_anon_WITH_AES_128_CBC_SHA", + "TLS_ECDH_anon_WITH_AES_256_CBC_SHA", + "TLS_ECDH_anon_WITH_NULL_SHA", + "TLS_ECDH_anon_WITH_RC4_128_SHA", + "TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384", + "TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384", + "TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256", + "TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256", + "TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384", + "TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384", + "TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256", + "TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256", + "TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA", + "TLS_ECDH_RSA_WITH_AES_256_CBC_SHA", + "TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA", + "TLS_ECDH_RSA_WITH_AES_128_CBC_SHA" }; public static void main(String[] args) throws Exception { @@ -114,11 +118,6 @@ public static void main(String[] args) throws Exception { throw new RuntimeException("No parameters specified"); } - System.setProperty("javax.net.ssl.keyStore", keyFilename); - System.setProperty("javax.net.ssl.keyStorePassword", passwd); - System.setProperty("javax.net.ssl.trustStore", trustFilename); - System.setProperty("javax.net.ssl.trustStorePassword", passwd); - switch (args[0]) { case "default": // use default jdk.tls.disabledAlgorithms @@ -126,7 +125,7 @@ public static void main(String[] args) throws Exception { + Security.getProperty("jdk.tls.disabledAlgorithms")); // check that disabled cipher suites can't be used by default - checkFailure(disabled_ciphersuites); + checkFailure(DISABLED_CIPHERSUITES); break; case "empty": // reset jdk.tls.disabledAlgorithms @@ -136,7 +135,7 @@ public static void main(String[] args) throws Exception { // check that disabled cipher suites can be used if // jdk.{tls,certpath}.disabledAlgorithms is empty - checkSuccess(disabled_ciphersuites); + checkSuccess(DISABLED_CIPHERSUITES); break; default: throw new RuntimeException("Wrong parameter: " + args[0]); @@ -149,7 +148,7 @@ public static void main(String[] args) throws Exception { * Checks if that specified cipher suites cannot be used. */ private static void checkFailure(String[] ciphersuites) throws Exception { - try (SSLServer server = SSLServer.init(ciphersuites)) { + try (SSLServer server = new SSLServer(ciphersuites)) { startNewThread(server); while (!server.isRunning()) { sleep(); @@ -157,7 +156,7 @@ private static void checkFailure(String[] ciphersuites) throws Exception { int port = server.getPort(); for (String ciphersuite : ciphersuites) { - try (SSLClient client = SSLClient.init(port, ciphersuite)) { + try (SSLClient client = new SSLClient(port, ciphersuite)) { client.connect(); throw new RuntimeException("Expected SSLHandshakeException " + "not thrown"); @@ -184,7 +183,7 @@ private static void checkFailure(String[] ciphersuites) throws Exception { * Checks if specified cipher suites can be used. */ private static void checkSuccess(String[] ciphersuites) throws Exception { - try (SSLServer server = SSLServer.init(ciphersuites)) { + try (SSLServer server = new SSLServer(ciphersuites)) { startNewThread(server); while (!server.isRunning()) { sleep(); @@ -192,7 +191,7 @@ private static void checkSuccess(String[] ciphersuites) throws Exception { int port = server.getPort(); for (String ciphersuite : ciphersuites) { - try (SSLClient client = SSLClient.init(port, ciphersuite)) { + try (SSLClient client = new SSLClient(port, ciphersuite)) { client.connect(); String negotiated = client.getNegotiatedCipherSuite(); System.out.println("Negotiated cipher suite: " @@ -231,7 +230,8 @@ private static void sleep() { } } - static class SSLServer implements Runnable, AutoCloseable { + static class SSLServer extends SSLContextTemplate implements Runnable, AutoCloseable { + private final SSLServerSocket ssocket; private volatile boolean stopped = false; @@ -239,7 +239,19 @@ static class SSLServer implements Runnable, AutoCloseable { private volatile boolean sslError = false; private volatile boolean otherError = false; - private SSLServer(SSLServerSocket ssocket) { + private SSLServer(String[] ciphersuites) throws Exception { + SSLContext context = createSSLContext(null, + DisabledAlgorithms.CERTIFICATES, getServerContextParameters()); + SSLServerSocketFactory ssf = context.getServerSocketFactory(); + SSLServerSocket ssocket = (SSLServerSocket) + ssf.createServerSocket(0); + + if (ciphersuites != null) { + System.out.println("Server: enable cipher suites: " + + java.util.Arrays.toString(ciphersuites)); + ssocket.setEnabledCipherSuites(ciphersuites); + } + this.ssocket = ssocket; } @@ -273,8 +285,8 @@ public void run() { } else { System.out.println("Server: run: " + e); System.out.println("The exception above occurred " - + "because socket was closed, " - + "please ignore it"); + + "because socket was closed, " + + "please ignore it"); } } } @@ -319,29 +331,23 @@ void stop() { public void close() { stop(); } - - static SSLServer init(String[] ciphersuites) - throws IOException { - SSLServerSocketFactory ssf = (SSLServerSocketFactory) - SSLServerSocketFactory.getDefault(); - SSLServerSocket ssocket = (SSLServerSocket) - ssf.createServerSocket(0); - - if (ciphersuites != null) { - System.out.println("Server: enable cipher suites: " - + java.util.Arrays.toString(ciphersuites)); - ssocket.setEnabledCipherSuites(ciphersuites); - } - - return new SSLServer(ssocket); - } } - static class SSLClient implements AutoCloseable { + static class SSLClient extends SSLContextTemplate implements AutoCloseable { private final SSLSocket socket; - private SSLClient(SSLSocket socket) { + private SSLClient(int port, String ciphersuite) throws Exception { + SSLContext context = createSSLContext(DisabledAlgorithms.CERTIFICATES, + null, getClientContextParameters()); + SSLSocketFactory ssf = context.getSocketFactory(); + SSLSocket socket = (SSLSocket) ssf.createSocket("localhost", port); + + if (ciphersuite != null) { + System.out.println("Client: enable cipher suite: " + + ciphersuite); + socket.setEnabledCipherSuites(new String[]{ciphersuite}); + } this.socket = socket; } @@ -381,29 +387,5 @@ public void close() throws Exception { } } } - - static SSLClient init(int port) - throws NoSuchAlgorithmException, IOException { - return init(port, null); - } - - static SSLClient init(int port, String ciphersuite) - throws NoSuchAlgorithmException, IOException { - SSLContext context = SSLContext.getDefault(); - SSLSocketFactory ssf = (SSLSocketFactory) - context.getSocketFactory(); - SSLSocket socket = (SSLSocket) ssf.createSocket("localhost", port); - - if (ciphersuite != null) { - System.out.println("Client: enable cipher suite: " - + ciphersuite); - socket.setEnabledCipherSuites(new String[] { ciphersuite }); - } - - return new SSLClient(socket); - } - } - - } diff --git a/test/jdk/javax/net/ssl/ciphersuites/TLSWontNegotiateDisabledCipherAlgos.java b/test/jdk/javax/net/ssl/ciphersuites/TLSWontNegotiateDisabledCipherAlgos.java new file mode 100644 index 00000000000..b22b4f02165 --- /dev/null +++ b/test/jdk/javax/net/ssl/ciphersuites/TLSWontNegotiateDisabledCipherAlgos.java @@ -0,0 +1,148 @@ +/* + * Copyright (c) 2023, 2024, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import jdk.test.lib.process.ProcessTools; + +import javax.net.ssl.*; +import java.io.IOException; +import java.net.Socket; +import java.nio.charset.StandardCharsets; +import java.security.Security; +import java.util.List; + +/* + * @test id=Server + * @bug 8301379 + * @library /test/lib + * @summary Verify that Java will not negotiate disabled cipher suites when the + * other side of the connection requests them. + * + * @library /javax/net/ssl/templates + * @run main/othervm TLSWontNegotiateDisabledCipherAlgos server true + */ + +/* + * @test id=Client + * @bug 8301379 + * @library /test/lib + * @summary Verify that Java will not negotiate disabled cipher suites when the + * other side of the connection requests them. + * + * @library /javax/net/ssl/templates + * @run main/othervm TLSWontNegotiateDisabledCipherAlgos server false + */ + + +public class TLSWontNegotiateDisabledCipherAlgos { + + public static void main(String [] args) throws Exception { + boolean useDisabledAlgo = Boolean.parseBoolean(args[1]); + if (useDisabledAlgo) { + Security.setProperty("jdk.tls.disabledAlgorithms", ""); + } + + if (args[0].equals("server")) { + try (TLSServer server = new TLSServer(useDisabledAlgo)) { + List command = List.of( + "TLSWontNegotiateDisabledCipherAlgos", + "client", + Boolean.toString(!useDisabledAlgo), + Integer.toString(server.getListeningPort()) + ); + ProcessBuilder builder = ProcessTools.createTestJavaProcessBuilder(command); + Process p = builder.inheritIO().start(); + server.run(); + p.destroy(); + } + } else if (args[0].equals("client")) { + try (TLSClient client = new TLSClient(Integer.parseInt(args[2]), useDisabledAlgo)) { + client.run(); + } + } + } + + private static class TLSClient extends SSLContextTemplate implements AutoCloseable { + private final SSLSocket socket; + + public TLSClient(int portNumber, boolean useDisableAlgo) throws Exception { + SSLContext context = createClientSSLContext(); + socket = (SSLSocket)context.getSocketFactory().createSocket("localhost", portNumber); + if (useDisableAlgo) { + socket.setEnabledCipherSuites(DisabledAlgorithms.DISABLED_CIPHERSUITES); + } + } + + public void run() throws IOException { + try { + socket.getOutputStream().write("SECRET MESSAGE".getBytes(StandardCharsets.UTF_8)); + throw new RuntimeException("SSL handshake completed successfully."); + } catch (SSLHandshakeException exc) { + if (!exc.getMessage().equals("Received fatal alert: handshake_failure")) { + throw new RuntimeException("Expected handshake_failure message. Got: " + + "\"" + exc.getMessage() + "\" message.", exc); + } + } + } + + @Override + public void close() throws Exception { + socket.close(); + } + } + + private static class TLSServer extends SSLContextTemplate implements AutoCloseable { + private SSLServerSocket serverSocket; + + public TLSServer(boolean useDisableAlgo) throws Exception { + SSLContext ctx = createServerSSLContext(); + serverSocket = (SSLServerSocket) ctx.getServerSocketFactory().createServerSocket(0); + if (useDisableAlgo) { + serverSocket.setEnabledCipherSuites(DisabledAlgorithms.DISABLED_CIPHERSUITES); + } + } + + @Override + public void close() throws Exception { + serverSocket.close(); + } + + public int getListeningPort() { + return serverSocket.getLocalPort(); + } + + public void run() throws IOException { + try (Socket clientSocket = serverSocket.accept()) { + try { + byte[] bytes = clientSocket.getInputStream().readAllBytes(); + throw new RuntimeException("The expected SSLHandshakeException was not thrown."); + } catch (SSLHandshakeException exc) { + if (!exc.getMessage().contains("no cipher suites in common")) { + throw exc; + } else { + System.out.println("Success: The connection could not be negotiated (as expected.)"); + } + } + } + } + } +} diff --git a/test/jdk/javax/net/ssl/templates/SSLContextTemplate.java b/test/jdk/javax/net/ssl/templates/SSLContextTemplate.java index 568575faaee..d06370ff919 100644 --- a/test/jdk/javax/net/ssl/templates/SSLContextTemplate.java +++ b/test/jdk/javax/net/ssl/templates/SSLContextTemplate.java @@ -645,9 +645,63 @@ enum Cert { "zjgEAwMvADAsAhQ6Y1I6LtIEBMqNo8o6GIe4LLEJuwIUbVQUKi8tvtWyRoxm8AFV\n" + "0axJYUU=\n" + "-----END CERTIFICATE-----", - "" + "" ), + CA_SHA1_RSA_2048( // for DHEKeySizing.java + "RSA", + // Signature Algorithm: sha1WithRSAEncryption + // Issuer: OU = SunJSSE Test Serivce, O = Java, C = US + // Validity + // Not Before: Sep 18 04:38:31 2013 GMT + // Not After : Dec 17 04:38:31 2013 GMT + "-----BEGIN CERTIFICATE-----\n" + + "MIIC8jCCAdqgAwIBAgIEUjkuRzANBgkqhkiG9w0BAQUFADA7MR0wGwYDVQQLExRT\n" + + "dW5KU1NFIFRlc3QgU2VyaXZjZTENMAsGA1UEChMESmF2YTELMAkGA1UEBhMCVVMw\n" + + "HhcNMTMwOTE4MDQzODMxWhcNMTMxMjE3MDQzODMxWjA7MR0wGwYDVQQLExRTdW5K\n" + + "U1NFIFRlc3QgU2VyaXZjZTENMAsGA1UEChMESmF2YTELMAkGA1UEBhMCVVMwggEi\n" + + "MA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCO+IGeaskJAvEcYc7pCl9neK3E\n" + + "a28fwWLtChufYNaC9hQfZlUdETWYjV7fZJVJKT/oLzdDNMWuVA0LKXArpI3thLNK\n" + + "QLXisdF9hKPlZRDazACL9kWUUtJ0FzpEySK4e8wW/z9FuU6e6iO19FbjxAfInJqk\n" + + "3EDiEhB5g73S2vtvPCxgq2DvWw9TDl/LIqdKG2JCS93koXCCaHmQ7MrIOqHPd+8r\n" + + "RbGpatXT9qyHKppUv9ATxVygO4rA794mgCFxpT+fkhz+NEB0twTkM65T1hnnOv5n\n" + + "ZIxkcjBggt85UlZtnP3b9P7SYxsWIa46Oc38Od2f3YejfVg6B+PqPgWNl3+/AgMB\n" + + "AAEwDQYJKoZIhvcNAQEFBQADggEBAAlrP6DFLRPSy0IgQhcI2i56tR/na8pezSte\n" + + "ZHcCdaCZPDy4UP8mpLJ9QCjEB5VJv8hPm4xdK7ULnKGOGHgYqDpV2ZHvQlhV1woQ\n" + + "TZGb/LM3c6kAs0j4j9KM2fq3iYUYexjIkS1KzsziflxMM6igS9BRMBR2LQyU+cYq\n" + + "YEsFzkF7Aj2ET4v/+tgot9mRr2NioJcaJkdsPDpMU3IKB1cczfu+OuLQ/GCG0Fqu\n" + + "6ijCeCqfnaAbemHbJeVZZ6Qgka3uC2YMntLBmLkhqEo1d9zGYLoh7oWL77y5ibQZ\n" + + "LK5/H/zikcu579TWjlDHcqL3arCwBcrtsjSaPrRSWMrWV/6c0qw=\n" + + "-----END CERTIFICATE-----", + "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCO+IGeaskJAvEc\n" + + "Yc7pCl9neK3Ea28fwWLtChufYNaC9hQfZlUdETWYjV7fZJVJKT/oLzdDNMWuVA0L\n" + + "KXArpI3thLNKQLXisdF9hKPlZRDazACL9kWUUtJ0FzpEySK4e8wW/z9FuU6e6iO1\n" + + "9FbjxAfInJqk3EDiEhB5g73S2vtvPCxgq2DvWw9TDl/LIqdKG2JCS93koXCCaHmQ\n" + + "7MrIOqHPd+8rRbGpatXT9qyHKppUv9ATxVygO4rA794mgCFxpT+fkhz+NEB0twTk\n" + + "M65T1hnnOv5nZIxkcjBggt85UlZtnP3b9P7SYxsWIa46Oc38Od2f3YejfVg6B+Pq\n" + + "PgWNl3+/AgMBAAECggEAPdb5Ycc4m4A9QBSCRcRpzbyiFLKPh0HDg1n65q4hOtYr\n" + + "kAVYTVFTSF/lqGS+Ob3w2YIKujQKSUQrvCc5UHdFuHXMgxKIWbymK0+DAMb9SlYw\n" + + "6lkkcWp9gx9E4dnJ/df2SAAxovvrKMuHlL1SFASHhVtPfH2URvSfUaANLDXxyYOs\n" + + "8BX0Nr6wazhWjLjXo9yIGnKSvFfB8XisYcA78kEgas43zhmIGCDPqaYyyffOfRbx\n" + + "pM1KNwGmlN86iWR1CbwA/wwhcMySWQueS+s7cHbpRqZIYJF9jEeELiwi0vxjealS\n" + + "EMuHYedIRFMWaDIq9XyjrvXamHb0Z25jlXBNZHaM0QKBgQDE9adl+zAezR/n79vw\n" + + "0XiX2Fx1UEo3ApZHuoA2Q/PcBk+rlKqqQ3IwTcy6Wo648wK7v6Nq7w5nEWcsf0dU\n" + + "QA2Ng/AJEev/IfF34x7sKGYxtk1gcE0EuSBA3R+ocEZxnNw1Ryd5nUU24s8d4jCP\n" + + "Mkothnyaim+zE2raDlEtVc0CaQKBgQC509av+02Uq5oMjzbQp5PBJfQFjATOQT15\n" + + "eefYnVYurkQ1kcVfixkrO2ORhg4SjmI2Z5hJDgGtXdwgidpzkad+R2epS5qLMyno\n" + + "lQVpY6bMpEZ7Mos0yQygxnm8uNohEcTExOe+nP5fNJVpzBsGmfeyYOhnPQlf6oqf\n" + + "0cHizedb5wKBgQC/l5LyMil6HOGHlhzmIm3jj7VI7QR0hJC5T6N+phVml8ESUDjA\n" + + "DYHbmSKouISTRtkG14FY+RiSjCxH7bvuKazFV2289PETquogTA/9e8MFYqfcQwG4\n" + + "sXi9gBxWlnj/9a2EKiYtOB5nKLR/BlNkSHA93tAA6N+FXEMZwMmYhxk42QKBgAuY\n" + + "HQgD3PZOsqDf+qKQIhbmAFCsSMx5o5VFtuJ8BpmJA/Z3ruHkMuDQpsi4nX4o5hXQ\n" + + "5t6AAjjH52kcUMXvK40kdWJJtk3DFnVNfvXxYsHX6hHbuHXFqYUKfSP6QJnZmvZP\n" + + "9smcz/4usLfWJUWHK740b6upUkFqx9Vq5/b3s9y3AoGAdM5TW7LkkOFsdMGVAUzR\n" + + "9iXmCWElHTK2Pcp/3yqDBHSfiQx6Yp5ANyPnE9NBM0yauCfOyBB2oxLO4Rdv3Rqk\n" + + "9V9kyR/YAGr7dJaPcQ7pZX0OpkzgueAOJYPrx5VUzPYUtklYV1ycFZTfKlpFCxT+\n" + + "Ei6KUo0NXSdUIcB4yib1J10=" + ), + + EE_DSA_SHA1_1024( // for SignatureAlgorithms test "DSA", // Signature Algorithm: dsaWithSHA1 @@ -1170,7 +1224,41 @@ enum Cert { "ofaiiWffsaytVvotmT6+atElvAMbAua42V+nAQKBgHtIn3mYMHLriYGhQzpkFEA2\n" + "8YcAMlKppueOMAKVy8nLu2r3MidmLAhMiKJQKG45I3Yg0/t/25tXLiOPJlwrOebh\n" + "xQqUBI/JUOIpGAEnr48jhOXnCS+i+z294G5U/RgjXrlR4bCPvrtCmwzWwe0h79w2\n" + - "Q2hO5ZTW6UD9CVA85whf"); + "Q2hO5ZTW6UD9CVA85whf"), + + DSA_SHA1_1024_EXPIRED( // for NullCerts test + "DSA", + // Signature Algorithm: dsaWithSHA1 + // Issuer: C = US, ST = CA, L = Cupertino, O = Dummy, OU = Dummy, CN = Example + // Validity + // Not Before: Mar 11 06:33:43 2001 GMT + // Not After : Dec 6 06:33:43 2003 GMT + "-----BEGIN CERTIFICATE-----\n" + + "MIIC9TCCArMCBDqrHEcwCwYHKoZIzjgEAwUAMGAxCzAJBgNVBAYTAlVTMQswCQYD\n" + + "VQQIEwJDQTESMBAGA1UEBxMJQ3VwZXJ0aW5vMQ4wDAYDVQQKEwVEdW1teTEOMAwG\n" + + "A1UECxMFRHVtbXkxEDAOBgNVBAMTB0V4YW1wbGUwHhcNMDEwMzExMDYzMzQzWhcN\n" + + "MDMxMjA2MDYzMzQzWjBgMQswCQYDVQQGEwJVUzELMAkGA1UECBMCQ0ExEjAQBgNV\n" + + "BAcTCUN1cGVydGlubzEOMAwGA1UEChMFRHVtbXkxDjAMBgNVBAsTBUR1bW15MRAw\n" + + "DgYDVQQDEwdFeGFtcGxlMIIBuDCCASwGByqGSM44BAEwggEfAoGBAP1/U4EddRIp\n" + + "Ut9KnC7s5Of2EbdSPO9EAMMeP4C2USZpRV1AIlH7WT2NWPq/xfW6MPbLm1Vs14E7\n" + + "gB00b/JmYLdrmVClpJ+f6AR7ECLCT7up1/63xhv4O1fnxqimFQ8E+4P208UewwI1\n" + + "VBNaFpEy9nXzrith1yrv8iIDGZ3RSAHHAhUAl2BQjxUjC8yykrmCouuEC/BYHPUC\n" + + "gYEA9+GghdabPd7LvKtcNrhXuXmUr7v6OuqC+VdMCz0HgmdRWVeOutRZT+ZxBxCB\n" + + "gLRJFnEj6EwoFhO3zwkyjMim4TwWeotUfI0o4KOuHiuzpnWRbqN/C/ohNWLx+2J6\n" + + "ASQ7zKTxvqhRkImog9/hWuWfBpKLZl6Ae1UlZAFMO/7PSSoDgYUAAoGBAPqO/boo\n" + + "m+n+tAdqetoQ2ZRoS8BpYIEFOJt4OJ8flb52T3vGNNdapq9pbjN+HKrT62ggNhZs\n" + + "hajxYwFCpaidKZuGQXvvpHkj0UHjhZFry6Dd41cfEG13dfgACf8uooeTzPGFvUPv\n" + + "TCHcPRh820BZMeOqdS4PjWPyf3HEtiTtFWR7MAsGByqGSM44BAMFAAMvADAsAhRH\n" + + "dZQef04MwUTlAALf2J6PIcgmQAIUB2H/RnW2tVg+mbCl5jQLfudsEhI=\n" + + "-----END CERTIFICATE-----", + "MIIBSwIBADCCASwGByqGSM44BAEwggEfAoGBAP1/U4EddRIpUt9KnC7s5Of2EbdS\n" + + "PO9EAMMeP4C2USZpRV1AIlH7WT2NWPq/xfW6MPbLm1Vs14E7gB00b/JmYLdrmVCl\n" + + "pJ+f6AR7ECLCT7up1/63xhv4O1fnxqimFQ8E+4P208UewwI1VBNaFpEy9nXzrith\n" + + "1yrv8iIDGZ3RSAHHAhUAl2BQjxUjC8yykrmCouuEC/BYHPUCgYEA9+GghdabPd7L\n" + + "vKtcNrhXuXmUr7v6OuqC+VdMCz0HgmdRWVeOutRZT+ZxBxCBgLRJFnEj6EwoFhO3\n" + + "zwkyjMim4TwWeotUfI0o4KOuHiuzpnWRbqN/C/ohNWLx+2J6ASQ7zKTxvqhRkImo\n" + + "g9/hWuWfBpKLZl6Ae1UlZAFMO/7PSSoEFgIUZC+jBuwAPm8ejkybfAm2gT49ApY=" + ); final String keyAlgo; final String certStr; diff --git a/test/jdk/javax/net/ssl/templates/SSLEngineTemplate.java b/test/jdk/javax/net/ssl/templates/SSLEngineTemplate.java index 08d95fcd4c9..9c044f32ebf 100644 --- a/test/jdk/javax/net/ssl/templates/SSLEngineTemplate.java +++ b/test/jdk/javax/net/ssl/templates/SSLEngineTemplate.java @@ -92,14 +92,22 @@ protected SSLEngineTemplate() throws Exception { cTOs = ByteBuffer.allocateDirect(netBufferMax); sTOc = ByteBuffer.allocateDirect(netBufferMax); - clientOut = ByteBuffer.wrap("Hi Server, I'm Client".getBytes()); - serverOut = ByteBuffer.wrap("Hello Client, I'm Server".getBytes()); + clientOut = createClientOutputBuffer(); + serverOut = createServerOutputBuffer(); + } + + protected ByteBuffer createServerOutputBuffer() { + return ByteBuffer.wrap("Hello Client, I'm Server".getBytes()); } // // Protected methods could be used to customize the test case. // + protected ByteBuffer createClientOutputBuffer() { + return ByteBuffer.wrap("Hi Server, I'm Client".getBytes()); + } + /* * Configure the client side engine. */ diff --git a/test/jdk/javax/sound/midi/SysexMessage/EmptySysExMessageTest.java b/test/jdk/javax/sound/midi/SysexMessage/EmptySysExMessageTest.java new file mode 100644 index 00000000000..03c940c2289 --- /dev/null +++ b/test/jdk/javax/sound/midi/SysexMessage/EmptySysExMessageTest.java @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import javax.sound.sampled.AudioInputStream; +import javax.sound.sampled.AudioSystem; +import javax.sound.sampled.Clip; +import javax.sound.sampled.LineUnavailableException; +import javax.sound.sampled.UnsupportedAudioFileException; +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; + +/* + * @test + * @key sound + * @bug 8282578 + * @summary AIOOBE in javax.sound.sampled.Clip + * @run main EmptySysExMessageTest + */ + +public class EmptySysExMessageTest { + public static void main(String[] args) { + String sep = System.getProperty("file.separator"); + String dir = System.getProperty("test.src", "."); + String name = "zerosysex.mid"; + try { + readAudioFile(dir + sep + name); + } catch (Throwable t) { + throw new RuntimeException("Invalid file " + name + + " caused unexpected exception during read: " + + t + System.lineSeparator()); + } + } + + static void readAudioFile(String name) throws IOException { + File soundFile = new File(name); + Path path = Paths.get(soundFile.getAbsolutePath()); + byte[] samples = Files.readAllBytes(path); + + try { + AudioInputStream audioInputStream = + AudioSystem.getAudioInputStream(new ByteArrayInputStream(samples)); + try (Clip clip = AudioSystem.getClip()) { + clip.open(audioInputStream); + clip.start(); + Thread.sleep(1000); + clip.stop(); + } + } catch (UnsupportedAudioFileException + | LineUnavailableException + | IOException + | InterruptedException + | IllegalArgumentException + | IllegalStateException + | SecurityException expected) { + // Do nothing, these types of exception are expected on invalid file + } + } +} diff --git a/test/jdk/javax/sound/midi/SysexMessage/zerosysex.mid b/test/jdk/javax/sound/midi/SysexMessage/zerosysex.mid new file mode 100644 index 00000000000..cf92458b952 Binary files /dev/null and b/test/jdk/javax/sound/midi/SysexMessage/zerosysex.mid differ diff --git a/test/jdk/javax/swing/JButton/PressedButtonRightClickTest.java b/test/jdk/javax/swing/JButton/PressedButtonRightClickTest.java index 078c9718e2e..8f3da452c21 100644 --- a/test/jdk/javax/swing/JButton/PressedButtonRightClickTest.java +++ b/test/jdk/javax/swing/JButton/PressedButtonRightClickTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -24,9 +24,12 @@ import java.awt.AWTException; import java.awt.BorderLayout; +import java.awt.EventQueue; import java.awt.Point; import java.awt.Robot; import java.awt.event.InputEvent; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.SwingUtilities; @@ -46,13 +49,7 @@ public class PressedButtonRightClickTest { public static void main(String[] args) throws Throwable { - SwingUtilities.invokeAndWait(new Runnable() { - - @Override - public void run() { - constructTestUI(); - } - }); + SwingUtilities.invokeAndWait(PressedButtonRightClickTest::constructTestUI); try { testRobot = new Robot(); @@ -61,11 +58,14 @@ public void run() { } testRobot.waitForIdle(); + testRobot.delay(500); // Method performing auto test operation - test(); - - disposeTestUI(); + try { + test(); + } finally { + EventQueue.invokeAndWait(PressedButtonRightClickTest::disposeTestUI); + } } private static void test() { @@ -74,22 +74,27 @@ private static void test() { testRobot.mouseMove((loc.x + 100), (loc.y + 100)); // Press the left mouse button + System.out.println("press BUTTON1_DOWN_MASK"); testRobot.mousePress(InputEvent.BUTTON1_DOWN_MASK); myButton.setText("Left button pressed"); - testRobot.delay(1000); + testRobot.delay(500); // Press the right mouse button + System.out.println("press BUTTON3_DOWN_MASK"); testRobot.mousePress(InputEvent.BUTTON3_DOWN_MASK); myButton.setText("Left button pressed + Right button pressed"); - testRobot.delay(1000); + testRobot.delay(500); // Release the right mouse button + System.out.println("release BUTTON3_DOWN_MASK"); testRobot.mouseRelease(InputEvent.BUTTON3_DOWN_MASK); myButton.setText("Right button released"); - testRobot.delay(1000); + testRobot.waitForIdle(); + testRobot.delay(500); // Test whether the button is still pressed boolean pressed = myButton.getModel().isPressed(); + System.out.println("release BUTTON1_DOWN_MASK"); testRobot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK); if (!pressed) { disposeTestUI(); @@ -106,6 +111,32 @@ public static void constructTestUI() { myFrame = new JFrame(); myFrame.setLayout(new BorderLayout()); myButton = new JButton("Whatever"); + myButton.addMouseListener(new MouseAdapter() { + @Override + public void mouseClicked(MouseEvent e) { + System.out.println(e); + } + + @Override + public void mousePressed(MouseEvent e) { + System.out.println(e); + } + + @Override + public void mouseReleased(MouseEvent e) { + System.out.println(e); + } + + @Override + public void mouseEntered(MouseEvent e) { + System.out.println(e); + } + + @Override + public void mouseExited(MouseEvent e) { + System.out.println(e); + } + }); myFrame.add(myButton, BorderLayout.CENTER); myFrame.setSize(400, 300); myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); diff --git a/test/jdk/javax/swing/JButton/bug4490179.java b/test/jdk/javax/swing/JButton/bug4490179.java index 94b141e5030..079c7a026f8 100644 --- a/test/jdk/javax/swing/JButton/bug4490179.java +++ b/test/jdk/javax/swing/JButton/bug4490179.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 2024, Oracle and/or its affiliates. All rights reserved. * 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,8 +31,6 @@ import java.awt.Point; import java.awt.Robot; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; import java.awt.event.InputEvent; import javax.swing.JButton; import javax.swing.JFrame; @@ -49,13 +47,16 @@ public class bug4490179 { public static void main(String[] args) throws Exception { Robot robot = new Robot(); robot.setAutoDelay(100); + robot.setAutoWaitForIdle(true); try { SwingUtilities.invokeAndWait(() -> { frame = new JFrame("bug4490179"); button = new JButton("Button"); frame.getContentPane().add(button); - button.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { + button.addActionListener(e -> { + if ((e.getModifiers() & InputEvent.BUTTON1_MASK) + != InputEvent.BUTTON1_MASK) { + System.out.println("Status: Failed"); passed = false; } }); @@ -80,6 +81,8 @@ public void actionPerformed(ActionEvent e) { robot.mousePress(InputEvent.BUTTON1_DOWN_MASK); robot.mousePress(InputEvent.BUTTON3_DOWN_MASK); robot.mouseRelease(InputEvent.BUTTON3_DOWN_MASK); + robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK); + robot.delay(500); if (!passed) { throw new RuntimeException("Test Failed"); diff --git a/test/jdk/javax/swing/JComboBox/ComboPopupBug.java b/test/jdk/javax/swing/JComboBox/ComboPopupBug.java new file mode 100644 index 00000000000..3a4fb4b8bc7 --- /dev/null +++ b/test/jdk/javax/swing/JComboBox/ComboPopupBug.java @@ -0,0 +1,92 @@ +/* + * Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import javax.swing.JButton; +import javax.swing.JComboBox; +import javax.swing.JFrame; +import javax.swing.SwingUtilities; + +/* + * @test + * @bug 8322754 + * @summary Verifies clicking JComboBox during frame closure causes Exception + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @run main/manual ComboPopupBug + */ + +public class ComboPopupBug { + private static final String instructionsText = """ + This test is used to verify that clicking on JComboBox + when frame containing it is about to close should not + cause IllegalStateException. + + A JComboBox is shown with Close button at the bottom. + Click on Close and then click on JComboBox arrow button + to try to show combobox popup. + If IllegalStateException is thrown, test will automatically Fail + otherwise click Pass. """; + + public static void main(String[] args) throws Exception { + PassFailJFrame passFailJFrame = new PassFailJFrame.Builder() + .title("ComboPopup Instructions") + .instructions(instructionsText) + .testTimeOut(5) + .rows(10) + .columns(35) + .build(); + + SwingUtilities.invokeAndWait(() -> { + JFrame frame = new JFrame("ComboPopup"); + + JComboBox cb = new JComboBox(); + cb.setEditable(true); + cb.addItem("test"); + cb.addItem("test2"); + cb.addItem("test3"); + frame.getContentPane().add(cb, "North"); + + JButton b = new JButton("Close"); + b.addActionListener( + (e)->{ + try { + Thread.sleep(3000); + } + catch (Exception ex) { + } + frame.setVisible(false); + + }); + frame.getContentPane().add(b, "South"); + frame.setSize(200, 200); + + PassFailJFrame.addTestWindow(frame); + PassFailJFrame.positionTestWindow(frame, + PassFailJFrame.Position.HORIZONTAL); + + frame.setVisible(true); + }); + + passFailJFrame.awaitAndCheck(); + } +} diff --git a/test/jdk/javax/swing/JLabel/4138746/JLabelMnemonicsTest.java b/test/jdk/javax/swing/JLabel/4138746/JLabelMnemonicsTest.java index 7cbd3232b13..ddb2ed32382 100644 --- a/test/jdk/javax/swing/JLabel/4138746/JLabelMnemonicsTest.java +++ b/test/jdk/javax/swing/JLabel/4138746/JLabelMnemonicsTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -90,6 +90,7 @@ public static void main(String[] args) throws Exception { continue; } robot.waitForIdle(); + robot.delay(500); // Verifier 1: Verifies if getDisplayedMnemonicIndex() returns the // right index set with setDisplayedMnemonicIndex method for JButton diff --git a/test/jdk/javax/swing/JTabbedPane/TestJTabbedPaneArrowDirection.java b/test/jdk/javax/swing/JTabbedPane/TestJTabbedPaneArrowDirection.java new file mode 100644 index 00000000000..50df3933f36 --- /dev/null +++ b/test/jdk/javax/swing/JTabbedPane/TestJTabbedPaneArrowDirection.java @@ -0,0 +1,108 @@ +/* + * Copyright (c) 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.awt.BorderLayout; +import java.awt.event.ActionEvent; +import java.awt.GridLayout; +import javax.swing.AbstractAction; +import javax.swing.JButton; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JTabbedPane; +import javax.swing.SwingUtilities; +import javax.swing.UIManager; + +/* + * @test + * @bug 8225220 + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @requires (os.family == "linux") + * @summary JTabbedPane arrow should point to left or right direction + * when tab layout policy is set to SCROLL_TAB_LAYOUT and tab + * placement is set to either TOP or BOTTOM + * @run main/manual TestJTabbedPaneArrowDirection + */ + +public class TestJTabbedPaneArrowDirection { + private static JFrame frame; + private static JTabbedPane tabPane; + private static final String INSTRUCTIONS = + "1. Observe the arrows are ponting to left and right direction\n" + + " for tab placement set to TOP. Default tab placement is TOP.\n\n" + + "2. Press BOTTOM to change the tab placement to bottom.\n\n" + + "3. Observe arrows are pointing to the left and right direction.\n\n" + + "4. If the behaviour is correct, press Pass else Fail."; + + public static void main(String[] args) throws Exception { + UIManager.setLookAndFeel("com.sun.java.swing.plaf.gtk.GTKLookAndFeel"); + PassFailJFrame passFailJFrame = new PassFailJFrame.Builder() + .title("JTabbedPane Arrow Direction Test Instructions") + .instructions(INSTRUCTIONS) + .testTimeOut(5) + .rows(12) + .columns(40) + .screenCapture() + .build(); + SwingUtilities.invokeAndWait( + TestJTabbedPaneArrowDirection::createAndShowUI); + passFailJFrame.awaitAndCheck(); + } + + private static void createAndShowUI() { + int NUM_TABS = 15; + frame = new JFrame("Test JTabbedPane Arrow Direction"); + JTabbedPane tabPane = new JTabbedPane(); + tabPane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT); + tabPane.setTabPlacement(JTabbedPane.TOP); + PassFailJFrame.addTestWindow(frame); + PassFailJFrame.positionTestWindow( + frame, PassFailJFrame.Position.HORIZONTAL); + for( int i = 0; i < NUM_TABS; ++i) { + tabPane.addTab("Tab " + i , new JLabel("Content Area")); + } + JPanel panel = new JPanel(new BorderLayout()); + panel.add(tabPane, BorderLayout.CENTER); + JButton topButton = new JButton(new AbstractAction() { + public void actionPerformed(ActionEvent e) { + tabPane.setTabPlacement(JTabbedPane.TOP); + } + }); + topButton.setText("TOP"); + JButton bottomButton = new JButton(new AbstractAction() { + public void actionPerformed(ActionEvent e) { + tabPane.setTabPlacement(JTabbedPane.BOTTOM); + } + }); + bottomButton.setText("BOTTOM"); + JPanel buttonPanel = new JPanel(new GridLayout(1, 2)); + buttonPanel.add(topButton); + buttonPanel.add(bottomButton); + panel.add(buttonPanel, BorderLayout.SOUTH); + frame.add(panel); + frame.setSize(500, 500); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + frame.setVisible(true); + } +} diff --git a/test/jdk/javax/swing/UI/UnninstallUIMemoryLeaks/UnninstallUIMemoryLeaks.java b/test/jdk/javax/swing/UI/UnninstallUIMemoryLeaks/UnninstallUIMemoryLeaks.java index c2d413cff25..c3bb610bb87 100644 --- a/test/jdk/javax/swing/UI/UnninstallUIMemoryLeaks/UnninstallUIMemoryLeaks.java +++ b/test/jdk/javax/swing/UI/UnninstallUIMemoryLeaks/UnninstallUIMemoryLeaks.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -224,7 +224,7 @@ private static void test(Object[] listeners) { } private static Process runProcess(LookAndFeelInfo laf) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-Dswing.defaultlaf=" + laf.getClassName(), "-mx9m", "-XX:+HeapDumpOnOutOfMemoryError", UnninstallUIMemoryLeaks.class.getSimpleName(), "mark"); diff --git a/test/jdk/javax/swing/plaf/basic/BasicComboPopup/JComboBoxPopupLocation/JComboBoxPopupLocation.java b/test/jdk/javax/swing/plaf/basic/BasicComboPopup/JComboBoxPopupLocation/JComboBoxPopupLocation.java index 588abd90861..bd210fa557a 100644 --- a/test/jdk/javax/swing/plaf/basic/BasicComboPopup/JComboBoxPopupLocation/JComboBoxPopupLocation.java +++ b/test/jdk/javax/swing/plaf/basic/BasicComboPopup/JComboBoxPopupLocation/JComboBoxPopupLocation.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -90,6 +90,7 @@ private static void step(GraphicsDevice[] sds, setup(point); }); robot.waitForIdle(); + robot.delay(500); test(comboBox); robot.waitForIdle(); validate(comboBox); @@ -110,6 +111,7 @@ private static void step(GraphicsDevice[] sds, setup(finalLeft); }); robot.waitForIdle(); + robot.delay(500); test(comboBox); robot.waitForIdle(); validate(comboBox); diff --git a/test/jdk/javax/swing/plaf/basic/BasicMenuUI/4983388/bug4983388.java b/test/jdk/javax/swing/plaf/basic/BasicMenuUI/4983388/bug4983388.java index 957f0e2cfe8..18f78d88f52 100644 --- a/test/jdk/javax/swing/plaf/basic/BasicMenuUI/4983388/bug4983388.java +++ b/test/jdk/javax/swing/plaf/basic/BasicMenuUI/4983388/bug4983388.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2024, Oracle and/or its affiliates. All rights reserved. * 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,7 @@ public class bug4983388 { static volatile boolean bMenuSelected = false; + static JFrame frame; private static class TestMenuListener implements MenuListener { public void menuCanceled(MenuEvent e) {} @@ -55,8 +56,9 @@ private static void createAndShowGUI() { JMenu menu = new JMenu("File"); menu.setMnemonic('F'); menuBar.add(menu); - JFrame frame = new JFrame(); + frame = new JFrame(); frame.setJMenuBar(menuBar); + frame.setLocationRelativeTo(null); frame.pack(); frame.setVisible(true); MenuListener listener = new TestMenuListener(); @@ -80,9 +82,13 @@ public void run() { Robot robot = new Robot(); robot.setAutoDelay(50); robot.waitForIdle(); + robot.delay(500); + Util.hitMnemonics(robot, KeyEvent.VK_F); robot.waitForIdle(); - robot.delay(200); + robot.delay(500); + + SwingUtilities.invokeAndWait(() -> frame.dispose()); if (!bMenuSelected) { throw new RuntimeException("shortcuts on menus do not work"); diff --git a/test/jdk/javax/swing/text/JTextComponent/5074573/bug5074573.java b/test/jdk/javax/swing/text/JTextComponent/5074573/bug5074573.java index 2c83bf2f3a9..5d66a477473 100644 --- a/test/jdk/javax/swing/text/JTextComponent/5074573/bug5074573.java +++ b/test/jdk/javax/swing/text/JTextComponent/5074573/bug5074573.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 2024, Oracle and/or its affiliates. All rights reserved. * 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,7 +25,7 @@ * @test * @key headful * @bug 5074573 8196100 - * @summary tests delte-next-word and delete-prev-word actions for all text compnents and all look&feels + * @summary tests delete-next-word and delete-prev-word actions for all text components and all look&feels * @run main bug5074573 */ @@ -49,6 +49,8 @@ public class bug5074573 { private static JTextComponent textComponent; + private static JFrame frame; + private static Robot robot; final static String testString = "123 456 789"; final static String resultString = "456 "; final static List> textClasses = Arrays.asList( @@ -56,24 +58,32 @@ public class bug5074573 { JTextField.class, JFormattedTextField.class, JPasswordField.class); public static void main(String[] args) throws Exception { + robot = new Robot(); + robot.setAutoWaitForIdle(true); + robot.setAutoDelay(50); + for (UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) { UIManager.setLookAndFeel(info.getClassName()); System.out.println(info); for (Class clazz : textClasses) { - boolean res = test(clazz); - if (!res && clazz != JPasswordField.class) { - throw new RuntimeException("failed"); + try { + boolean res = test(clazz); + if (!res && clazz != JPasswordField.class) { + throw new RuntimeException("failed"); + } + } finally { + SwingUtilities.invokeAndWait(() -> { + if (frame != null) { + frame.dispose(); + frame = null; + } + }); } } } } static boolean test(final Class textComponentClass) throws Exception { - Robot robot = new Robot(); - robot.setAutoWaitForIdle(true); - robot.setAutoDelay(50); - - SwingUtilities.invokeAndWait(new Runnable() { @Override @@ -83,6 +93,7 @@ public void run() { }); robot.waitForIdle(); + robot.delay(500); // Remove selection from JTextField components for the Aqua Look & Feel if (textComponent instanceof JTextField && "Aqua".equals(UIManager.getLookAndFeel().getID())) { @@ -120,6 +131,7 @@ public void run() { robot.keyRelease(KeyEvent.VK_DELETE); robot.keyRelease(getCtrlKey()); robot.waitForIdle(); + robot.delay(250); return resultString.equals(getText()); } @@ -152,7 +164,7 @@ public static int getCtrlKey() { private static void initialize(Class textComponentClass) { try { - JFrame frame = new JFrame(); + frame = new JFrame(); textComponent = textComponentClass.newInstance(); textComponent.setText(testString); frame.add(textComponent); diff --git a/test/jdk/javax/swing/text/html/CSS/bug8234913.java b/test/jdk/javax/swing/text/html/CSS/bug8234913.java index cf4c43d7531..bd74fbaeb93 100644 --- a/test/jdk/javax/swing/text/html/CSS/bug8234913.java +++ b/test/jdk/javax/swing/text/html/CSS/bug8234913.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 2023, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2019 SAP SE. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -52,7 +52,7 @@ static ProcessBuilder exec(String... args) throws Exception { Collections.addAll(argsList, "-Xmn8m"); Collections.addAll(argsList, "-Dtest.class.path=" + System.getProperty("test.class.path", ".")); Collections.addAll(argsList, FontSizePercentTest.class.getName()); - return ProcessTools.createJavaProcessBuilder(argsList.toArray(new String[argsList.size()])); + return ProcessTools.createLimitedTestJavaProcessBuilder(argsList.toArray(new String[argsList.size()])); } static void checkFor(String... outputStrings) throws Exception { diff --git a/test/jdk/jdk/incubator/vector/LoadJsvmlTest.java b/test/jdk/jdk/incubator/vector/LoadJsvmlTest.java index 355201bfbf3..e6e613bbc90 100644 --- a/test/jdk/jdk/incubator/vector/LoadJsvmlTest.java +++ b/test/jdk/jdk/incubator/vector/LoadJsvmlTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2021, 2023, Oracle and/or its affiliates. All rights reserved. * 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,7 +60,7 @@ public static void main(String[] args) throws Exception { } public static void main(String... args) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-Xmn8m", "-Xlog:library=info", "--add-modules=jdk.incubator.vector", VectorTest.class.getName()); diff --git a/test/jdk/jdk/internal/misc/VM/RuntimeArguments.java b/test/jdk/jdk/internal/misc/VM/RuntimeArguments.java index bcf3eda476d..c48de900ec3 100644 --- a/test/jdk/jdk/internal/misc/VM/RuntimeArguments.java +++ b/test/jdk/jdk/internal/misc/VM/RuntimeArguments.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -30,6 +30,12 @@ * @run testng RuntimeArguments */ +import java.io.IOException; +import java.io.InputStream; +import java.io.UncheckedIOException; +import java.lang.module.ModuleFinder; +import java.lang.module.ModuleReader; +import java.lang.module.ModuleReference; import java.util.Arrays; import java.util.List; import java.util.stream.Stream; @@ -41,6 +47,30 @@ public class RuntimeArguments { static final String TEST_CLASSES = System.getProperty("test.classes"); + static final List VM_OPTIONS = getInitialOptions(); + + /* + * Read jdk/internal/vm/options resource from the runtime image. + * If present, the runtime image was created with jlink --add-options and + * the java launcher launches the application as if + * $ java @options + * The VM options listed in the jdk/internal/vm/options resource file + * are passed to the VM. + */ + static List getInitialOptions() { + ModuleReference mref = ModuleFinder.ofSystem().find("java.base").orElseThrow(); + try (ModuleReader reader = mref.open()) { + InputStream in = reader.open("jdk/internal/vm/options").orElse(null); + if (in != null) { + // support the simplest form for now: whitespace-separated + return List.of(new String(in.readAllBytes()).split("\s")); + } else { + return List.of(); + } + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } @DataProvider(name = "options") public Object[][] options() { @@ -83,13 +113,15 @@ public static void main(String... expected) { @Test(dataProvider = "options") public void test(List args, List expected) throws Exception { // launch a test program - // $ java -classpath RuntimeArguments - + // $ java -classpath RuntimeArguments Stream options = Stream.concat(args.stream(), Stream.of("-classpath", TEST_CLASSES, "RuntimeArguments")); - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( - Stream.concat(options, expected.stream()) + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( + // The runtime image may be created with jlink --add-options + // The initial VM options will be included in the result + // returned by VM.getRuntimeArguments() + Stream.concat(options, Stream.concat(VM_OPTIONS.stream(), expected.stream())) .toArray(String[]::new) ); ProcessTools.executeProcess(pb).shouldHaveExitValue(0); diff --git a/test/jdk/jdk/jfr/api/consumer/streaming/Application.java b/test/jdk/jdk/jfr/api/consumer/streaming/Application.java index 6cc7876a7cb..fea8347ceaf 100644 --- a/test/jdk/jdk/jfr/api/consumer/streaming/Application.java +++ b/test/jdk/jdk/jfr/api/consumer/streaming/Application.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2021, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -102,7 +102,7 @@ public void start() throws IOException { args[2] = Application.class.getName(); args[3] = lockFile.toString(); args[4] = message; - ProcessBuilder pb = ProcessTools.createTestJvm(args); + ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder(args); touch(lockFile); process = pb.start(); // For debugging diff --git a/test/jdk/jdk/jfr/api/consumer/streaming/TestCrossProcessStreaming.java b/test/jdk/jdk/jfr/api/consumer/streaming/TestCrossProcessStreaming.java index 75885d50876..313b5f026e1 100644 --- a/test/jdk/jdk/jfr/api/consumer/streaming/TestCrossProcessStreaming.java +++ b/test/jdk/jdk/jfr/api/consumer/streaming/TestCrossProcessStreaming.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -127,7 +127,7 @@ static class EventProducer { static Process start() throws Exception { String[] args = {"-XX:StartFlightRecording", EventProducer.class.getName()}; - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(args); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(args); return ProcessTools.startProcess("Event-Producer", pb, line -> line.contains(MAIN_STARTED), 0, TimeUnit.SECONDS); diff --git a/test/jdk/jdk/jfr/api/consumer/streaming/TestProcess.java b/test/jdk/jdk/jfr/api/consumer/streaming/TestProcess.java index 8643ec35bc2..dbbdbe9c67d 100644 --- a/test/jdk/jdk/jfr/api/consumer/streaming/TestProcess.java +++ b/test/jdk/jdk/jfr/api/consumer/streaming/TestProcess.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 2023, Oracle and/or its affiliates. All rights reserved. * 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,7 +66,7 @@ public TestProcess(String name, boolean createCore) throws IOException { "-XX:" + (createCore ? "+" : "-") + "CreateCoredumpOnCrash", TestProcess.class.getName(), path.toString() }; - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(args); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(args); process = ProcessTools.startProcess(name, pb); } diff --git a/test/jdk/jdk/jfr/event/gc/configuration/TestGCYoungGenerationConfigurationEventWithMinAndMaxSize.java b/test/jdk/jdk/jfr/event/gc/configuration/TestGCYoungGenerationConfigurationEventWithMinAndMaxSize.java index 67962399569..d347378b606 100644 --- a/test/jdk/jdk/jfr/event/gc/configuration/TestGCYoungGenerationConfigurationEventWithMinAndMaxSize.java +++ b/test/jdk/jdk/jfr/event/gc/configuration/TestGCYoungGenerationConfigurationEventWithMinAndMaxSize.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2023, Oracle and/or its affiliates. All rights reserved. * 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 static void main(String[] args) throws Exception { "-Xms32m", "-Xmx64m", Tester.class.getName()}; - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(jvm_args); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(jvm_args); OutputAnalyzer analyzer = ProcessTools.executeProcess(pb); analyzer.shouldHaveExitValue(0); } diff --git a/test/jdk/jdk/jfr/event/os/TestInitialEnvironmentVariable.java b/test/jdk/jdk/jfr/event/os/TestInitialEnvironmentVariable.java index aa8cdbbf662..d8fd9a6e673 100644 --- a/test/jdk/jdk/jfr/event/os/TestInitialEnvironmentVariable.java +++ b/test/jdk/jdk/jfr/event/os/TestInitialEnvironmentVariable.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2023, Oracle and/or its affiliates. All rights reserved. * 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,7 +48,7 @@ public class TestInitialEnvironmentVariable { private final static String EVENT_NAME = EventNames.InitialEnvironmentVariable; public static void main(String[] args) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(Test.class.getName()); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(Test.class.getName()); setEnv(pb.environment()); (new OutputAnalyzer(pb.start())).shouldHaveExitValue(0); } diff --git a/test/jdk/jdk/jfr/event/runtime/TestDumpReason.java b/test/jdk/jdk/jfr/event/runtime/TestDumpReason.java index 4282c1afffb..83af0de239d 100644 --- a/test/jdk/jdk/jfr/event/runtime/TestDumpReason.java +++ b/test/jdk/jdk/jfr/event/runtime/TestDumpReason.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2020, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -89,7 +89,7 @@ private static void test(Class crasher, String reason) throws Exception { private static long runProcess(Class crasher) throws Exception { System.out.println("Test case for " + crasher.getName()); - Process p = ProcessTools.createTestJvm( + Process p = ProcessTools.createTestJavaProcessBuilder( "-Xmx64m", "-XX:-CreateCoredumpOnCrash", "--add-exports=java.base/jdk.internal.misc=ALL-UNNAMED", diff --git a/test/jdk/jdk/jfr/event/runtime/TestShutdownEvent.java b/test/jdk/jdk/jfr/event/runtime/TestShutdownEvent.java index 71b617ecd79..5eedbd24354 100644 --- a/test/jdk/jdk/jfr/event/runtime/TestShutdownEvent.java +++ b/test/jdk/jdk/jfr/event/runtime/TestShutdownEvent.java @@ -89,7 +89,7 @@ public static void main(String[] args) throws Throwable { } private static void runSubtest(int subTestIndex) throws Exception { - ProcessBuilder pb = ProcessTools.createTestJvm( + ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder( "-Xlog:jfr=debug", "-XX:-CreateCoredumpOnCrash", "-XX:-TieredCompilation", diff --git a/test/jdk/jdk/jfr/jvm/TestDumpOnCrash.java b/test/jdk/jdk/jfr/jvm/TestDumpOnCrash.java index 926f918f476..4f44cac0260 100644 --- a/test/jdk/jdk/jfr/jvm/TestDumpOnCrash.java +++ b/test/jdk/jdk/jfr/jvm/TestDumpOnCrash.java @@ -110,7 +110,7 @@ private static void test(Class crasher, String signal, boolean disk, String d private static long runProcess(Class crasher, String signal, boolean disk) throws Exception { System.out.println("Test case for crasher " + crasher.getName()); final String flightRecordingOptions = "dumponexit=true,disk=" + Boolean.toString(disk); - Process p = ProcessTools.createTestJvm( + Process p = ProcessTools.createTestJavaProcessBuilder( "-Xmx64m", "-XX:-CreateCoredumpOnCrash", "-XX:-TieredCompilation", // Avoid secondary crashes (see JDK-8293166) diff --git a/test/jdk/jdk/jfr/jvm/TestEventWriterLog.java b/test/jdk/jdk/jfr/jvm/TestEventWriterLog.java index a57f8231e7e..2a33e7892c9 100644 --- a/test/jdk/jdk/jfr/jvm/TestEventWriterLog.java +++ b/test/jdk/jdk/jfr/jvm/TestEventWriterLog.java @@ -35,7 +35,7 @@ public class TestEventWriterLog { public static void main(String[] args) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-Xlog:jfr+system+bytecode=trace", "-XX:StartFlightRecording", "-version"); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("-Xlog:jfr+system+bytecode=trace", "-XX:StartFlightRecording", "-version"); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldContain("extends jdk/jfr/internal/handlers/EventHandler"); } diff --git a/test/jdk/jdk/jfr/jvm/TestJfrJavaBase.java b/test/jdk/jdk/jfr/jvm/TestJfrJavaBase.java deleted file mode 100644 index e6a3b2662ac..00000000000 --- a/test/jdk/jdk/jfr/jvm/TestJfrJavaBase.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute 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 8157032 - * @key jfr - * @summary verify that jfr can not be used when JVM is executed only with java.base - * @requires vm.hasJFR & !vm.graal.enabled - * @library /test/lib - * @modules java.base/jdk.internal.misc - * @run driver jdk.jfr.jvm.TestJfrJavaBase - */ - -package jdk.jfr.jvm; - - -import jdk.test.lib.dcmd.PidJcmdExecutor; -import jdk.test.lib.process.OutputAnalyzer; -import jdk.test.lib.process.ProcessTools; - -public class TestJfrJavaBase { - - private static void checkOutput(OutputAnalyzer output) { - output.shouldContain("Module jdk.jfr not found."); - output.shouldContain("Flight Recorder can not be enabled."); - } - - public static void main(String[] args) throws Exception { - OutputAnalyzer output; - if (args.length == 0) { - output = ProcessTools.executeProcess(ProcessTools.createJavaProcessBuilder( - "-Dtest.jdk=" + System.getProperty("test.jdk"), - "--limit-modules", "java.base", "-cp", System.getProperty("java.class.path"), - TestJfrJavaBase.class.getName(), "runtest")); - output.shouldHaveExitValue(0); - } else { - output = ProcessTools.executeTestJava("-XX:StartFlightRecording:dumponexit=true", - "--limit-modules", "java.base", "-version"); - checkOutput(output); - output.shouldHaveExitValue(1); - - // Verify that JFR.start jcmd command reports an error when jdk.jfr module is not available - output = new PidJcmdExecutor().execute("JFR.start"); - checkOutput(output); - output.shouldHaveExitValue(0); - } - } -} diff --git a/test/jdk/jdk/jfr/jvm/TestModularImage.java b/test/jdk/jdk/jfr/jvm/TestModularImage.java new file mode 100644 index 00000000000..0f10150af60 --- /dev/null +++ b/test/jdk/jdk/jfr/jvm/TestModularImage.java @@ -0,0 +1,184 @@ +/* + * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package jdk.jfr.jvm; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.spi.ToolProvider; + +import jdk.test.lib.JDKToolFinder; +import jdk.test.lib.Platform; +import jdk.test.lib.process.OutputAnalyzer; +import jdk.test.lib.process.ProcessTools; + +/** + * @test + * @key jfr + * @summary Checks that a JDK image with and without the jdk.jfr module behaves + * as expected + * @requires vm.hasJFR + * @library /test/lib + * @run driver jdk.jfr.jvm.TestModularImage + */ +public class TestModularImage { + private static final String STARTED_RECORDING = "Started recording"; + private static final String HELLO_WORLD = "hello, world"; + private static final String ERROR_LINE1 = "Error occurred during initialization of boot layer"; + private static final String ERROR_LINE2 = "java.lang.module.FindException: Module jdk.jfr not found"; + + private static final ToolProvider javac = find("javac"); + private static final ToolProvider jlink = find("jlink"); + + private static final Path out = Path.of("out"); + private static final Path src = out.resolve("src"); + private static final Path classes = out.resolve("classes"); + + private static final Path testJDK = Path.of(System.getProperty("test.jdk")); + private static final Path jmods = testJDK.resolve("jmods"); + + private static final String modulePath = jmods.toString() + File.pathSeparator + classes.toString(); + + public static void main(String[] args) throws Exception { + preparseSourceTree(); + compileSourceCode(); + + // Jcmd for the current JVM where jdk.attach module is available + String currentJcmd = JDKToolFinder.getJDKTool("jcmd"); + currentJcmd = Path.of(currentJcmd).normalize().toAbsolutePath().toString(); + + // Image 1: Should be able to start JFR if jdk.jfr module is present + Path javaBin1 = jlink("hello.world,jdk.jfr", "with-jfr"); + testCommandLineWithJFR(javaBin1); + testJcmdWithJFR(javaBin1, currentJcmd); + + // Image 2: Should fail if jdk.jfr module is not present + Path javaBin2 = jlink("hello.world", "without-jfr"); + testCommandLineWithoutJFR(javaBin2); + testJcmdWithoutJFR(javaBin2, currentJcmd); + } + + private static void testCommandLineWithJFR(Path binPath) throws Exception { + var result = java(binPath, "-XX:StartFlightRecording", "--module", "hello.world/hello.Main"); + result.shouldNotContain(ERROR_LINE1); + result.shouldNotContain(ERROR_LINE2); + result.shouldContain(HELLO_WORLD); + result.shouldContain(STARTED_RECORDING); + result.shouldHaveExitValue(0); + } + + private static void testJcmdWithJFR(Path binPath, String jcmd) throws Exception { + var result = java(binPath, "--module", "hello.world/hello.Main", jcmd); + result.shouldContain(HELLO_WORLD); + result.shouldNotContain(ERROR_LINE1); + result.shouldNotContain(ERROR_LINE2); + result.shouldContain(STARTED_RECORDING); + result.shouldHaveExitValue(0); + } + + private static void testCommandLineWithoutJFR(Path binPath) throws Exception { + var result = java(binPath, "-XX:StartFlightRecording", "--module", "hello.world/hello.Main"); + result.shouldContain(ERROR_LINE1); + result.shouldContain(ERROR_LINE2); + result.shouldNotContain(HELLO_WORLD); + result.shouldNotContain(STARTED_RECORDING); + result.shouldHaveExitValue(1); + } + + private static void testJcmdWithoutJFR(Path binPath, String jcmd) throws Exception { + OutputAnalyzer result = java(binPath, "--module", "hello.world/hello.Main", jcmd); + result.shouldContain(HELLO_WORLD); + result.shouldContain("Module jdk.jfr not found."); + result.shouldContain("Flight Recorder can not be enabled."); + result.shouldNotContain(STARTED_RECORDING); + result.shouldHaveExitValue(0); + } + + private static ToolProvider find(String tool) { + return ToolProvider.findFirst(tool).orElseThrow(() -> new RuntimeException("No " + tool)); + } + + private static void preparseSourceTree() throws IOException { + String main = + """ + package hello; + import java.io.ByteArrayOutputStream; + public class Main { + public static void main(String... args) throws Exception { + System.out.println("hello, world!"); + if (args.length > 0) { + long pid = ProcessHandle.current().pid(); + String jcmd = args[0]; + String[] cmds = { jcmd, Long.toString(pid), "JFR.start" }; + Process process = new ProcessBuilder(cmds).redirectErrorStream(true).start(); + process.waitFor(); + var baos = new ByteArrayOutputStream(); + process.getInputStream().transferTo(baos); + System.out.println(baos.toString()); + System.exit(process.exitValue()); + } + } + } + """; + String moduleInfo = "module hello.world {}"; + Path helloWorld = src.resolve("hello.world"); + Files.createDirectories(helloWorld.resolve("hello")); + Files.write(helloWorld.resolve("module-info.java"), moduleInfo.getBytes()); + Files.write(helloWorld.resolve("hello").resolve("Main.java"), main.getBytes()); + } + + private static void compileSourceCode() { + javac.run(System.out, System.err, + "--module-source-path", src.toString(), + "--module", "hello.world", + "-d", classes.toString()); + } + + private static Path jlink(String modules, String output) { + jlink.run(System.out, System.err, + "--add-modules", modules, + "--module-path", modulePath, + "--output", output); + return Path.of(output).resolve("bin").toAbsolutePath(); + } + + private static OutputAnalyzer java(Path jvm, String... args) throws Exception { + ProcessBuilder pb = new ProcessBuilder(); + String java = Platform.isWindows() ? "java.exe" : "java"; + List arguments = new ArrayList<>(); + arguments.add(jvm.resolve(java).toString()); + arguments.addAll(Arrays.asList(args)); + pb.command(arguments); + pb.directory(jvm.toFile()); + System.out.println("Executing: java " + String.join(" ", args)); + OutputAnalyzer result = ProcessTools.executeProcess(pb); + System.out.println("--- Output ----" + "-".repeat(65)); + System.out.println(result.getOutput()); + System.out.println("-".repeat(80)); + return result; + } +} diff --git a/test/jdk/jdk/jfr/startupargs/TestBadOptionValues.java b/test/jdk/jdk/jfr/startupargs/TestBadOptionValues.java index 9156ffb6b66..50514e02024 100644 --- a/test/jdk/jdk/jfr/startupargs/TestBadOptionValues.java +++ b/test/jdk/jdk/jfr/startupargs/TestBadOptionValues.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -54,7 +54,7 @@ private static void test(String prepend, String expectedOutput, String... option Asserts.assertGreaterThan(options.length, 0); for (String option : options) { - pb = ProcessTools.createJavaProcessBuilder(prepend + option, "-version"); + pb = ProcessTools.createLimitedTestJavaProcessBuilder(prepend + option, "-version"); output = new OutputAnalyzer(pb.start()); output.shouldContain(expectedOutput); } diff --git a/test/jdk/jdk/jfr/startupargs/TestDumpOnExit.java b/test/jdk/jdk/jfr/startupargs/TestDumpOnExit.java index 454bbb631ad..eaf325a779d 100644 --- a/test/jdk/jdk/jfr/startupargs/TestDumpOnExit.java +++ b/test/jdk/jdk/jfr/startupargs/TestDumpOnExit.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -92,7 +92,7 @@ private static Path findJFRFileInCurrentDirectory() { } private static void testDumponExit(Supplier p,String... args) throws Exception, IOException { - ProcessBuilder pb = ProcessTools.createTestJvm(args); + ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder(args); OutputAnalyzer output = ProcessTools.executeProcess(pb); System.out.println(output.getOutput()); output.shouldHaveExitValue(0); diff --git a/test/jdk/jdk/jfr/startupargs/TestJFCWarnings.java b/test/jdk/jdk/jfr/startupargs/TestJFCWarnings.java index 139ab8385d7..cf0cb021216 100644 --- a/test/jdk/jdk/jfr/startupargs/TestJFCWarnings.java +++ b/test/jdk/jdk/jfr/startupargs/TestJFCWarnings.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2021, 2023, Oracle and/or its affiliates. All rights reserved. * 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 @@ private static void testUnknownOption() throws Exception { } private static void launch(String commandLine, String expectedOutput) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(commandLine, "-version"); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(commandLine, "-version"); OutputAnalyzer output = new OutputAnalyzer(pb.start()); output.shouldContain(expectedOutput); } diff --git a/test/jdk/jdk/jfr/startupargs/TestMemoryOptions.java b/test/jdk/jdk/jfr/startupargs/TestMemoryOptions.java index baa56bbddc9..9c90d04691a 100644 --- a/test/jdk/jdk/jfr/startupargs/TestMemoryOptions.java +++ b/test/jdk/jdk/jfr/startupargs/TestMemoryOptions.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -483,19 +483,19 @@ private static void launchTestVM(TestCase tc) throws Exception { final String flightRecorderOptions = tc.getTestString(); ProcessBuilder pb; if (flightRecorderOptions != null) { - pb = ProcessTools.createTestJvm("--add-exports=jdk.jfr/jdk.jfr.internal=ALL-UNNAMED", - "--add-exports=java.base/jdk.internal.misc=ALL-UNNAMED", - flightRecorderOptions, - "-XX:StartFlightRecording", - SUT.class.getName(), - tc.getTestName()); + pb = ProcessTools.createTestJavaProcessBuilder("--add-exports=jdk.jfr/jdk.jfr.internal=ALL-UNNAMED", + "--add-exports=java.base/jdk.internal.misc=ALL-UNNAMED", + flightRecorderOptions, + "-XX:StartFlightRecording", + SUT.class.getName(), + tc.getTestName()); } else { // default, no FlightRecorderOptions passed - pb = ProcessTools.createTestJvm("--add-exports=jdk.jfr/jdk.jfr.internal=ALL-UNNAMED", - "--add-exports=java.base/jdk.internal.misc=ALL-UNNAMED", - "-XX:StartFlightRecording", - SUT.class.getName(), - tc.getTestName()); + pb = ProcessTools.createTestJavaProcessBuilder("--add-exports=jdk.jfr/jdk.jfr.internal=ALL-UNNAMED", + "--add-exports=java.base/jdk.internal.misc=ALL-UNNAMED", + "-XX:StartFlightRecording", + SUT.class.getName(), + tc.getTestName()); } System.out.println("Driver launching SUT with string: " + flightRecorderOptions != null ? flightRecorderOptions : "default"); diff --git a/test/jdk/jdk/jfr/startupargs/TestMultipleStartupRecordings.java b/test/jdk/jdk/jfr/startupargs/TestMultipleStartupRecordings.java index e8cbff2dfd3..24be874a87f 100644 --- a/test/jdk/jdk/jfr/startupargs/TestMultipleStartupRecordings.java +++ b/test/jdk/jdk/jfr/startupargs/TestMultipleStartupRecordings.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2023, Oracle and/or its affiliates. All rights reserved. * 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,14 +55,14 @@ private static void test(ProcessBuilder pb, String... expectedOutputs) throws Ex private static void launchUnary(String options) throws Exception { String recording1 = START_FLIGHT_RECORDING + (options != null ? options : ""); - ProcessBuilder pb = ProcessTools.createTestJvm(recording1, MainClass.class.getName()); + ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder(recording1, MainClass.class.getName()); test(pb, "Started recording 1"); } private static void launchBinary(String options1, String options2) throws Exception { String recording1 = START_FLIGHT_RECORDING + (options1 != null ? options1 : ""); String recording2 = START_FLIGHT_RECORDING + (options2 != null ? options2 : ""); - ProcessBuilder pb = ProcessTools.createTestJvm(recording1, recording2, MainClass.class.getName()); + ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder(recording1, recording2, MainClass.class.getName()); test(pb, "Started recording 1", "Started recording 2"); } @@ -70,7 +70,7 @@ private static void launchTernary(String options1, String options2, String optio String recording1 = START_FLIGHT_RECORDING + (options1 != null ? options1 : ""); String recording2 = START_FLIGHT_RECORDING + (options2 != null ? options2 : ""); String recording3 = START_FLIGHT_RECORDING + (options3 != null ? options3 : ""); - ProcessBuilder pb = ProcessTools.createTestJvm(recording1, recording2, recording3, MainClass.class.getName()); + ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder(recording1, recording2, recording3, MainClass.class.getName()); test(pb, "Started recording 1", "Started recording 2", "Started recording 3"); } @@ -94,7 +94,7 @@ private static void testWithFlightRecorderOptions() throws Exception { String flightRecorderOptions = FLIGHT_RECORDER_OPTIONS + "=maxchunksize=8m"; String recording1 = START_FLIGHT_RECORDING + "=filename=recording1.jfr"; String recording2 = START_FLIGHT_RECORDING + "=name=myrecording,filename=recording2.jfr"; - ProcessBuilder pb = ProcessTools.createTestJvm(flightRecorderOptions, recording1, recording2, MainClass.class.getName()); + ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder(flightRecorderOptions, recording1, recording2, MainClass.class.getName()); test(pb, "Started recording 1", "Started recording 2"); } diff --git a/test/jdk/jdk/jfr/startupargs/TestOptionsWithLocale.java b/test/jdk/jdk/jfr/startupargs/TestOptionsWithLocale.java index 1942b3d3f63..3a4d3f20732 100644 --- a/test/jdk/jdk/jfr/startupargs/TestOptionsWithLocale.java +++ b/test/jdk/jdk/jfr/startupargs/TestOptionsWithLocale.java @@ -36,7 +36,7 @@ public static void main(String... args) throws IOException { return; } - ProcessBuilder pb = ProcessTools.createTestJvm( + ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder( "-Duser.country=DE", "-Duser.language=de", "-XX:FlightRecorderOptions:stackdepth=128", diff --git a/test/jdk/jdk/jfr/startupargs/TestRetransformUsingLog.java b/test/jdk/jdk/jfr/startupargs/TestRetransformUsingLog.java index a427cfc1af4..8c8703dc9e6 100644 --- a/test/jdk/jdk/jfr/startupargs/TestRetransformUsingLog.java +++ b/test/jdk/jdk/jfr/startupargs/TestRetransformUsingLog.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -104,7 +104,7 @@ private static void startApp(boolean recording, boolean retransform, Consumer addrs) { System.out.println("DEBUG: Running tests with plain sockets."); @@ -198,8 +197,6 @@ private Process createTestProcess() { " == (%s,%d,%d)", address, jmxPort, rmiPort); System.out.println(msg); List args = new ArrayList<>(); - args.add("-classpath"); - args.add(TEST_CLASSPATH); args.add("-Dcom.sun.management.jmxremote.host=" + address); args.add("-Dcom.sun.management.jmxremote.port=" + jmxPort); args.add("-Dcom.sun.management.jmxremote.rmi.port=" + rmiPort); @@ -221,7 +218,7 @@ private Process createTestProcess() { args.add(Boolean.toString(useSSL)); try { - ProcessBuilder builder = ProcessTools.createJavaProcessBuilder(args.toArray(new String[]{})); + ProcessBuilder builder = ProcessTools.createTestJavaProcessBuilder(args.toArray(new String[]{})); System.out.println(ProcessTools.getCommandLine(builder)); Process process = builder.start(); output = new OutputAnalyzer(process); diff --git a/test/jdk/sun/management/jmxremote/bootstrap/LocalManagementTest.java b/test/jdk/sun/management/jmxremote/bootstrap/LocalManagementTest.java index 571aa93f23b..0a7c735e2e0 100644 --- a/test/jdk/sun/management/jmxremote/bootstrap/LocalManagementTest.java +++ b/test/jdk/sun/management/jmxremote/bootstrap/LocalManagementTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2023, Oracle and/or its affiliates. All rights reserved. * 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,7 +107,7 @@ private static boolean doTest(String testId, String arg) throws Exception { args.add(arg); } args.add("TestApplication"); - ProcessBuilder server = ProcessTools.createJavaProcessBuilder( + ProcessBuilder server = ProcessTools.createTestJavaProcessBuilder( args.toArray(new String[args.size()]) ); @@ -133,7 +133,7 @@ private static boolean doTest(String testId, String arg) throws Exception { System.out.println(" PID : " + serverPrc.pid()); System.out.println(" shutdown port : " + port.get()); - ProcessBuilder client = ProcessTools.createJavaProcessBuilder( + ProcessBuilder client = ProcessTools.createTestJavaProcessBuilder( "-cp", TEST_CLASSPATH, "--add-exports", "jdk.management.agent/jdk.internal.agent=ALL-UNNAMED", diff --git a/test/jdk/sun/management/jmxremote/bootstrap/RmiRegistrySslTest.java b/test/jdk/sun/management/jmxremote/bootstrap/RmiRegistrySslTest.java index 59f3f8e182a..6cc5708b385 100644 --- a/test/jdk/sun/management/jmxremote/bootstrap/RmiRegistrySslTest.java +++ b/test/jdk/sun/management/jmxremote/bootstrap/RmiRegistrySslTest.java @@ -188,7 +188,7 @@ private int doTest(String... args) throws Exception { command.add(TEST_CLASS_PATH); command.add(className); - ProcessBuilder processBuilder = ProcessTools.createJavaProcessBuilder(command.toArray(new String[command.size()])); + ProcessBuilder processBuilder = ProcessTools.createTestJavaProcessBuilder(command); OutputAnalyzer output = ProcessTools.executeProcess(processBuilder); diff --git a/test/jdk/sun/management/jmxremote/startstop/JMXStartStopTest.java b/test/jdk/sun/management/jmxremote/startstop/JMXStartStopTest.java index 283cccd8397..13a4f7bea73 100644 --- a/test/jdk/sun/management/jmxremote/startstop/JMXStartStopTest.java +++ b/test/jdk/sun/management/jmxremote/startstop/JMXStartStopTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -391,16 +391,14 @@ public synchronized void stop() private static TestAppRun doTest(String name, String ... args) throws Exception { List pbArgs = new ArrayList<>(Arrays.asList( - "-cp", - System.getProperty("test.class.path"), + "-Duser.language=en", + "-Duser.country=US", "-XX:+UsePerfData" )); pbArgs.addAll(Arrays.asList(args)); pbArgs.add(TEST_APP_NAME); - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( - pbArgs.toArray(new String[pbArgs.size()]) - ); + ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder(pbArgs); TestAppRun s = new TestAppRun(pb, name); s.start(); return s; diff --git a/test/jdk/sun/management/jmxremote/startstop/JMXStatusPerfCountersTest.java b/test/jdk/sun/management/jmxremote/startstop/JMXStatusPerfCountersTest.java index 9a12db38a2f..fc7a0de2d06 100644 --- a/test/jdk/sun/management/jmxremote/startstop/JMXStatusPerfCountersTest.java +++ b/test/jdk/sun/management/jmxremote/startstop/JMXStatusPerfCountersTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2023, Oracle and/or its affiliates. All rights reserved. * 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,9 +59,8 @@ public class JMXStatusPerfCountersTest { @BeforeClass public static void setupClass() throws Exception { - testAppPb = ProcessTools.createJavaProcessBuilder( + testAppPb = ProcessTools.createTestJavaProcessBuilder( "-XX:+UsePerfData", - "-cp", System.getProperty("test.class.path"), TEST_APP_NAME ); } diff --git a/test/jdk/sun/management/jmxremote/startstop/JMXStatusTest.java b/test/jdk/sun/management/jmxremote/startstop/JMXStatusTest.java index 0813be10bff..1e6259ef0d7 100644 --- a/test/jdk/sun/management/jmxremote/startstop/JMXStatusTest.java +++ b/test/jdk/sun/management/jmxremote/startstop/JMXStatusTest.java @@ -84,12 +84,10 @@ abstract public class JMXStatusTest { @BeforeTest public final void setup() throws Exception { List args = new ArrayList<>(); - args.add("-cp"); - args.add(System.getProperty("test.class.path")); args.add("-XX:+UsePerfData"); args.addAll(getCustomVmArgs()); args.add(TEST_APP_NAME); - testAppPb = ProcessTools.createJavaProcessBuilder(args.toArray(new String[args.size()])); + testAppPb = ProcessTools.createTestJavaProcessBuilder(args); jcmd = new ManagementAgentJcmd(TEST_APP_NAME, false); } diff --git a/test/jdk/sun/net/www/B8185898.java b/test/jdk/sun/net/www/B8185898.java index cfa54e15a52..c78df56f723 100644 --- a/test/jdk/sun/net/www/B8185898.java +++ b/test/jdk/sun/net/www/B8185898.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,7 +23,7 @@ /** * @test - * @bug 8185898 8163921 + * @bug 8185898 8163921 8339470 * @modules java.base/sun.net.www * @library /test/lib * @run main/othervm B8185898 @@ -143,32 +143,32 @@ static void testMessageHeaderMethods() throws IOException { // {{inputString1, expectedToString1, expectedPrint1}, {...}} String[][] strings = { {"HTTP/1.1 200 OK\r\n" - + "Accept: */*\r\n" + + "Accept: text/html, image/gif, image/jpeg, */*; q=0.2\r\n" + "Connection: keep-alive\r\n" + "Host: 127.0.0.1:12345\r\n" + "User-agent: Java/12\r\n\r\nfoooo", "pairs: {null: HTTP/1.1 200 OK}" - + "{Accept: */*}" + + "{Accept: text/html, image/gif, image/jpeg, */*; q=0.2}" + "{Connection: keep-alive}" + "{Host: 127.0.0.1:12345}" + "{User-agent: Java/12}", - "Accept: */*\r\n" + "Accept: text/html, image/gif, image/jpeg, */*; q=0.2\r\n" + "Connection: keep-alive\r\n" + "Host: 127.0.0.1:12345\r\n" + "User-agent: Java/12\r\n\r\n"}, {"HTTP/1.1 200 OK\r\n" - + "Accept: */*\r\n" + + "Accept: text/html, image/gif, image/jpeg, */*; q=0.2\r\n" + "Connection: keep-alive\r\n" + "Host: 127.0.0.1:12345\r\n" + "User-agent: Java/12\r\n" + "X-Header:\r\n\r\n", "pairs: {null: HTTP/1.1 200 OK}" - + "{Accept: */*}" + + "{Accept: text/html, image/gif, image/jpeg, */*; q=0.2}" + "{Connection: keep-alive}" + "{Host: 127.0.0.1:12345}" + "{User-agent: Java/12}" + "{X-Header: }", - "Accept: */*\r\n" + "Accept: text/html, image/gif, image/jpeg, */*; q=0.2\r\n" + "Connection: keep-alive\r\n" + "Host: 127.0.0.1:12345\r\n" + "User-agent: Java/12\r\n" diff --git a/test/jdk/sun/net/www/http/KeepAliveCache/B5045306.java b/test/jdk/sun/net/www/http/KeepAliveCache/B5045306.java index 151e2ab6b23..0f48b060a31 100644 --- a/test/jdk/sun/net/www/http/KeepAliveCache/B5045306.java +++ b/test/jdk/sun/net/www/http/KeepAliveCache/B5045306.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -24,9 +24,9 @@ /* * @test * @bug 5045306 6356004 6993490 8255124 + * @summary Http keep-alive implementation is not efficient * @library /test/lib * @run main/othervm B5045306 - * @summary Http keep-alive implementation is not efficient */ import java.io.IOException; @@ -42,14 +42,17 @@ import java.net.URL; import java.util.ArrayList; import java.util.List; +import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpHandler; import com.sun.net.httpserver.HttpServer; +import jdk.test.lib.net.URIBuilder; + /* Part 1: - * The http client makes a connection to a URL whos content contains a lot of + * The http client makes a connection to a URL whose content contains a lot of * data, more than can fit in the socket buffer. The client only reads * 1 byte of the data from the InputStream leaving behind more data than can * fit in the socket buffer. The client then makes a second call to the http @@ -63,151 +66,167 @@ public class B5045306 { static HttpServer server; - - public static void main(String[] args) { - startHttpServer(); - clientHttpCalls(); - } + static ExecutorService executor = Executors.newSingleThreadExecutor(); public static void startHttpServer() { try { - server = HttpServer.create(new InetSocketAddress(InetAddress.getLocalHost(), 0), 10); + server = HttpServer.create(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 10); server.createContext("/", new SimpleHttpTransactionHandler()); - server.setExecutor(Executors.newSingleThreadExecutor()); - server.start(); } catch (IOException e) { - e.printStackTrace(); + throw new RuntimeException(e); } + server.setExecutor(executor); + server.start(); + System.out.println("http server listens on: " + server.getAddress()); } - public static void clientHttpCalls() { + public static void stopHttpServer() { + server.stop(1); + executor.shutdown(); + } + + public static void clientHttpCalls() throws Exception { List uncaught = new ArrayList<>(); Thread.setDefaultUncaughtExceptionHandler((t, ex) -> { uncaught.add(ex); }); - try { - System.out.println("http server listen on: " + server.getAddress().getPort()); - String hostAddr = InetAddress.getLocalHost().getHostAddress(); - if (hostAddr.indexOf(':') > -1) hostAddr = "[" + hostAddr + "]"; - String baseURLStr = "http://" + hostAddr + ":" + server.getAddress().getPort() + "/"; - URL bigDataURL = new URL (baseURLStr + "firstCall"); - URL smallDataURL = new URL (baseURLStr + "secondCall"); + URL bigDataURL = URIBuilder.newBuilder() + .scheme("http") + .loopback() + .port(server.getAddress().getPort()) + .path("/firstCall") + .toURL(); + + URL smallDataURL = URIBuilder.newBuilder() + .scheme("http") + .loopback() + .port(server.getAddress().getPort()) + .path("/secondCall") + .toURL(); - HttpURLConnection uc = (HttpURLConnection)bigDataURL.openConnection(Proxy.NO_PROXY); + HttpURLConnection uc = (HttpURLConnection)bigDataURL.openConnection(Proxy.NO_PROXY); - //Only read 1 byte of response data and close the stream - InputStream is = uc.getInputStream(); + // Only read 1 byte of response data and close the stream + try (InputStream is = uc.getInputStream()) { byte[] ba = new byte[1]; is.read(ba); - is.close(); - - // Allow the KeepAliveStreamCleaner thread to read the data left behind and cache the connection. - try { Thread.sleep(2000); } catch (Exception e) {} - - uc = (HttpURLConnection)smallDataURL.openConnection(Proxy.NO_PROXY); - uc.getResponseCode(); - - if (SimpleHttpTransactionHandler.failed) - throw new RuntimeException("Failed: Initial Keep Alive Connection is not being reused"); - - // Part 2 - URL part2Url = new URL (baseURLStr + "part2"); - uc = (HttpURLConnection)part2Url.openConnection(Proxy.NO_PROXY); - is = uc.getInputStream(); - is.close(); - - // Allow the KeepAliveStreamCleaner thread to try and read the data left behind and cache the connection. - try { Thread.sleep(2000); } catch (Exception e) {} - - ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean(); - if (threadMXBean.isThreadCpuTimeSupported()) { - long[] threads = threadMXBean.getAllThreadIds(); - ThreadInfo[] threadInfo = threadMXBean.getThreadInfo(threads); - for (int i=0; i= 1000000000) // 1 second, or 1 billion nanoseconds - throw new RuntimeException("Failed: possible recursive loop in Keep-Alive-SocketCleaner"); - } + } + + // Allow the KeepAliveStreamCleaner thread to read the data left behind and cache the connection. + try { Thread.sleep(2000); } catch (Exception e) {} + + uc = (HttpURLConnection)smallDataURL.openConnection(Proxy.NO_PROXY); + uc.getResponseCode(); + + if (SimpleHttpTransactionHandler.failed) + throw new RuntimeException("Failed: Initial Keep Alive Connection is not being reused"); + + // Part 2 + URL part2Url = URIBuilder.newBuilder() + .scheme("http") + .loopback() + .port(server.getAddress().getPort()) + .path("/part2") + .toURL(); + + uc = (HttpURLConnection)part2Url.openConnection(Proxy.NO_PROXY); + try (InputStream is = uc.getInputStream()) {} + + // Allow the KeepAliveStreamCleaner thread to try and read the data left behind and cache the connection. + try { Thread.sleep(2000); } catch (Exception e) {} + + ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean(); + if (threadMXBean.isThreadCpuTimeSupported()) { + long[] threads = threadMXBean.getAllThreadIds(); + ThreadInfo[] threadInfo = threadMXBean.getThreadInfo(threads); + for (int i = 0; i < threadInfo.length; i++) { + if (threadInfo[i].getThreadName().equals("Keep-Alive-SocketCleaner")) { + System.out.println("Found Keep-Alive-SocketCleaner thread"); + long threadID = threadInfo[i].getThreadId(); + long before = threadMXBean.getThreadCpuTime(threadID); + try { Thread.sleep(2000); } catch (Exception e) {} + long after = threadMXBean.getThreadCpuTime(threadID); + + if (before ==-1 || after == -1) + break; // thread has died, OK + + // if Keep-Alive-SocketCleaner consumes more than 50% of cpu then we + // can assume a recursive loop. + long total = after - before; + if (total >= 1000000000) // 1 second, or 1 billion nanoseconds + throw new RuntimeException("Failed: possible recursive loop in Keep-Alive-SocketCleaner"); } } - - } catch (IOException e) { - e.printStackTrace(); - } finally { - server.stop(1); } if (!uncaught.isEmpty()) { throw new RuntimeException("Unhandled exception:", uncaught.get(0)); } } -} -class SimpleHttpTransactionHandler implements HttpHandler -{ - static volatile boolean failed = false; + static class SimpleHttpTransactionHandler implements HttpHandler { + static volatile boolean failed = false; - // Need to have enough data here that is too large for the socket buffer to hold. - // Also http.KeepAlive.remainingData must be greater than this value, default is 256K. - static final int RESPONSE_DATA_LENGTH = 128 * 1024; + // Need to have enough data here that is too large for the socket buffer to hold. + // Also http.KeepAlive.remainingData must be greater than this value, default is 256K. + static final int RESPONSE_DATA_LENGTH = 128 * 1024; - int port1; + int port1; - public void handle(HttpExchange trans) { - try { - String path = trans.getRequestURI().getPath(); - if (path.equals("/firstCall")) { - port1 = trans.getRemoteAddress().getPort(); - System.out.println("First connection on client port = " + port1); - - byte[] responseBody = new byte[RESPONSE_DATA_LENGTH]; - for (int i=0; i passed = new CompletableFuture<>(); - static class Server extends Thread { - final ServerSocket serverSocket; - final int port; + static class Server extends Thread implements AutoCloseable { final String param; // the parameter to test "max" or "timeout" + final ServerSocket serverSocket = new ServerSocket(0); + final int port; volatile Socket s; public Server(String param) throws IOException { - serverSocket = new ServerSocket(0); + this.param = param; port = serverSocket.getLocalPort(); setDaemon(true); - this.param = param; } public int getPort() { return port; } - public void close() { - try { - serverSocket.close(); - if (s != null) - s.close(); - } catch (IOException e) {} + public void close() throws IOException { + serverSocket.close(); + if (s != null) + s.close(); } static void readRequest(Socket s) throws IOException { @@ -112,28 +114,29 @@ public void run() { } } - public static void main(String[] args) throws Exception { - Server server = new Server(args[0]); - int port = server.getPort(); - server.start(); - URL url = new URL("http://127.0.0.1:" + Integer.toString(port) + "/"); - HttpURLConnection urlc = (HttpURLConnection) url.openConnection(); - InputStream i = urlc.getInputStream(); - int c,count=0; - byte[] buf = new byte[256]; - while ((c=i.read(buf)) != -1) { - count+=c; - } - i.close(); - System.out.println("Read " + count ); - try { + public static void runTest(String param) throws Exception { + try (Server server = new Server(param)) { + server.start(); + URL url = URIBuilder.newBuilder() + .scheme("http") + .loopback() + .port(server.getPort()) + .path("/") + .toURL(); + HttpURLConnection urlc = (HttpURLConnection) url.openConnection(); + try (InputStream i = urlc.getInputStream()) { + System.out.println("Read " + i.readAllBytes().length); + } if (!passed.get()) { throw new RuntimeException("Test failed"); } else { System.out.println("Test passed"); } - } finally { - server.close(); } } + + public static void main(String[] args) throws Exception { + runTest("timeout"); + runTest("max"); + } } diff --git a/test/jdk/sun/net/www/http/KeepAliveCache/B8293562.java b/test/jdk/sun/net/www/http/KeepAliveCache/B8293562.java index 2e6dbb84e2d..e17d0586256 100644 --- a/test/jdk/sun/net/www/http/KeepAliveCache/B8293562.java +++ b/test/jdk/sun/net/www/http/KeepAliveCache/B8293562.java @@ -24,20 +24,11 @@ /* * @test * @bug 8293562 + * @summary Http keep-alive thread should close sockets without holding a lock * @library /test/lib * @run main/othervm -Dhttp.keepAlive.time.server=1 B8293562 - * @summary Http keep-alive thread should close sockets without holding a lock */ -import com.sun.net.httpserver.HttpExchange; -import com.sun.net.httpserver.HttpHandler; -import com.sun.net.httpserver.HttpServer; - -import javax.net.ssl.HandshakeCompletedListener; -import javax.net.ssl.HttpsURLConnection; -import javax.net.ssl.SSLSession; -import javax.net.ssl.SSLSocket; -import javax.net.ssl.SSLSocketFactory; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; @@ -53,6 +44,18 @@ import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; +import javax.net.ssl.HandshakeCompletedListener; +import javax.net.ssl.HttpsURLConnection; +import javax.net.ssl.SSLSession; +import javax.net.ssl.SSLSocket; +import javax.net.ssl.SSLSocketFactory; + +import com.sun.net.httpserver.HttpExchange; +import com.sun.net.httpserver.HttpHandler; +import com.sun.net.httpserver.HttpServer; + +import jdk.test.lib.net.URIBuilder; + public class B8293562 { static HttpServer server; static CountDownLatch closing = new CountDownLatch(1); @@ -73,12 +76,13 @@ public static void startHttpServer() throws Exception { public static void clientHttpCalls() throws Exception { try { - System.out.println("http server listen on: " + server.getAddress().getPort()); - String hostAddr = InetAddress.getLoopbackAddress().getHostAddress(); - if (hostAddr.indexOf(':') > -1) hostAddr = "[" + hostAddr + "]"; - String baseURLStr = "https://" + hostAddr + ":" + server.getAddress().getPort() + "/"; + System.out.println("http server listens on: " + server.getAddress().getPort()); - URL testUrl = new URL (baseURLStr); + URL testUrl = URIBuilder.newBuilder() + .scheme("https") + .loopback() + .port(server.getAddress().getPort()) + .toURL(); // SlowCloseSocketFactory is not a real SSLSocketFactory; // it produces regular non-SSL sockets. Effectively, the request diff --git a/test/jdk/sun/net/www/http/KeepAliveCache/KeepAliveProperty.java b/test/jdk/sun/net/www/http/KeepAliveCache/KeepAliveProperty.java index 83491ad4e38..0e065b1224c 100644 --- a/test/jdk/sun/net/www/http/KeepAliveCache/KeepAliveProperty.java +++ b/test/jdk/sun/net/www/http/KeepAliveCache/KeepAliveProperty.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,18 +23,29 @@ /* * @test - * @library /test/lib * @bug 8278067 + * @library /test/lib * @run main/othervm -Dhttp.keepAlive.time.server=30 KeepAliveProperty long * @run main/othervm -Dhttp.keepAlive.time.server=1 KeepAliveProperty short * @run main/othervm -ea -Dhttp.keepAlive.time.server=0 KeepAliveProperty short */ -import java.net.*; -import java.io.*; -import java.nio.charset.*; -import java.util.logging.*; +import java.io.BufferedOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.PrintStream; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.ServerSocket; +import java.net.Socket; +import java.net.URL; +import java.nio.charset.StandardCharsets; +import java.util.logging.ConsoleHandler; +import java.util.logging.Level; +import java.util.logging.Logger; + import jdk.test.lib.net.URIBuilder; + import static java.net.Proxy.NO_PROXY; public class KeepAliveProperty { diff --git a/test/jdk/sun/net/www/http/KeepAliveCache/KeepAliveTimerThread.java b/test/jdk/sun/net/www/http/KeepAliveCache/KeepAliveTimerThread.java index 5568f0c54a9..44130b2a820 100644 --- a/test/jdk/sun/net/www/http/KeepAliveCache/KeepAliveTimerThread.java +++ b/test/jdk/sun/net/www/http/KeepAliveCache/KeepAliveTimerThread.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,16 +23,26 @@ /* * @test - * @library /test/lib * @bug 4701299 * @summary Keep-Alive-Timer thread management in KeepAliveCache causes memory leak + * @library /test/lib * @run main KeepAliveTimerThread * @run main/othervm -Djava.net.preferIPv6Addresses=true KeepAliveTimerThread */ -import java.net.*; -import java.io.*; +import java.io.BufferedOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.PrintStream; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.ServerSocket; +import java.net.Socket; +import java.net.SocketTimeoutException; +import java.net.URL; + import jdk.test.lib.net.URIBuilder; + import static java.net.Proxy.NO_PROXY; public class KeepAliveTimerThread { @@ -131,8 +141,5 @@ public static void main(String args[]) throws Exception { if (grp.activeCount() > 0) { throw new RuntimeException("Keep-alive thread started in wrong thread group"); } - - grp.destroy(); } - } diff --git a/test/jdk/sun/net/www/protocol/jar/GetContentTypeTest.java b/test/jdk/sun/net/www/protocol/jar/GetContentTypeTest.java index 16a59d65dc2..c730b693910 100644 --- a/test/jdk/sun/net/www/protocol/jar/GetContentTypeTest.java +++ b/test/jdk/sun/net/www/protocol/jar/GetContentTypeTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -34,10 +34,10 @@ * GetContentType GetContentTypeTest * @run main/othervm GetContentTypeTest * @summary Test JarURLConnection.getContentType would - * would return default "content/unknown" + * return default "content/unknown" */ -import jdk.test.lib.JDKToolFinder; +import jdk.test.lib.process.OutputAnalyzer; import jdk.test.lib.process.ProcessTools; import java.io.File; @@ -49,9 +49,9 @@ public static void main(String[] args) throws Throwable { Path resJar = Paths.get(System.getProperty("test.src"), "resource.jar"); Path classes = Paths.get(System.getProperty("test.classes")); - ProcessTools.executeCommand( - JDKToolFinder.getTestJDKTool("java"), - "-cp", resJar + File.pathSeparator + classes, "GetContentType") + ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder( + "-cp", resJar + File.pathSeparator + classes, "GetContentType"); + new OutputAnalyzer(pb.start()) .outputTo(System.out) .errorTo(System.out) .shouldHaveExitValue(0); diff --git a/test/jdk/sun/net/www/protocol/jar/jarbug/TestDriver.java b/test/jdk/sun/net/www/protocol/jar/jarbug/TestDriver.java index cb27c554686..19ab2a668d4 100644 --- a/test/jdk/sun/net/www/protocol/jar/jarbug/TestDriver.java +++ b/test/jdk/sun/net/www/protocol/jar/jarbug/TestDriver.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2024, Oracle and/or its affiliates. All rights reserved. * 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,6 +47,7 @@ import static java.nio.file.StandardCopyOption.REPLACE_EXISTING; import jdk.test.lib.JDKToolFinder; import jdk.test.lib.compiler.CompilerUtils; +import jdk.test.lib.process.OutputAnalyzer; import jdk.test.lib.process.ProcessTools; import jdk.test.lib.util.JarUtils; @@ -81,14 +82,14 @@ public static void main(String[] args) throws Throwable { CompilerUtils.compile(srcDir.resolve("src").resolve("test"), targetDir); // Run tests - String java = JDKToolFinder.getTestJDKTool("java"); String cp = targetDir.toString() + File.pathSeparator + jarFile; String[] tests = new String[]{"TestBug4361044", "TestBug4523159"}; for (String test : tests) { - ProcessTools.executeCommand(java, "-cp", cp, test) - .outputTo(System.out) - .errorTo(System.out) - .shouldHaveExitValue(0); + ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder("-cp", cp, test); + new OutputAnalyzer(pb.start()) + .outputTo(System.out) + .errorTo(System.out) + .shouldHaveExitValue(0); } } } diff --git a/test/jdk/sun/net/www/protocol/jrt/OtherResourcesTest.java b/test/jdk/sun/net/www/protocol/jrt/OtherResourcesTest.java index 00ec82282e0..0c901f95cc7 100644 --- a/test/jdk/sun/net/www/protocol/jrt/OtherResourcesTest.java +++ b/test/jdk/sun/net/www/protocol/jrt/OtherResourcesTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,8 +21,8 @@ * questions. */ -import jdk.test.lib.JDKToolFinder; -import static jdk.test.lib.process.ProcessTools.executeCommand; +import jdk.test.lib.process.OutputAnalyzer; +import jdk.test.lib.process.ProcessTools; /** * @test @@ -39,12 +39,13 @@ public class OtherResourcesTest { public static void main(String[] args) throws Throwable { String classes = System.getProperty("test.classes"); - executeCommand(JDKToolFinder.getTestJDKTool("java"), - "--limit-modules", "java.base", - "-cp", classes, "OtherResources") - .outputTo(System.out) - .errorTo(System.out) - .shouldHaveExitValue(0); + ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder( + "--limit-modules", "java.base", + "-cp", classes, "OtherResources"); + new OutputAnalyzer(pb.start()) + .outputTo(System.out) + .errorTo(System.out) + .shouldHaveExitValue(0); } } diff --git a/test/jdk/sun/security/krb5/auto/ModuleName.java b/test/jdk/sun/security/krb5/auto/ModuleName.java index 02b712f26fa..8058326bc61 100644 --- a/test/jdk/sun/security/krb5/auto/ModuleName.java +++ b/test/jdk/sun/security/krb5/auto/ModuleName.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -53,7 +53,7 @@ public static void main(String[] args) throws Throwable { test("jdk.security.jgss"); // With limited modules - List cmd = ProcessTools.createJavaProcessBuilder().command(); + List cmd = ProcessTools.createLimitedTestJavaProcessBuilder().command(); Stream.of(jdk.internal.misc.VM.getRuntimeArguments()) .filter(arg -> arg.startsWith("--add-exports=") || arg.startsWith("--add-opens=")) diff --git a/test/jdk/sun/security/pkcs11/PKCS11Test.java b/test/jdk/sun/security/pkcs11/PKCS11Test.java index becbc9695a1..ca4a74e1825 100644 --- a/test/jdk/sun/security/pkcs11/PKCS11Test.java +++ b/test/jdk/sun/security/pkcs11/PKCS11Test.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -53,9 +53,7 @@ import java.util.ServiceConfigurationError; import java.util.ServiceLoader; import java.util.Set; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import java.util.stream.Collectors; +import java.util.stream.Stream; import jdk.test.lib.Platform; import jdk.test.lib.artifacts.Artifact; @@ -79,7 +77,7 @@ public abstract class PKCS11Test { // Version of the NSS artifact. This coincides with the version of // the NSS version - private static final String NSS_BUNDLE_VERSION = "3.91"; + private static final String NSS_BUNDLE_VERSION = "3.96"; private static final String NSSLIB = "jpg.tests.jdk.nsslib"; static double nss_version = -1; @@ -256,19 +254,13 @@ private static Path getNSSLibPath() throws Exception { static Path getNSSLibPath(String library) throws Exception { String osid = getOsId(); - String nssLibDir = fetchNssLib(osid); - if (nssLibDir == null) { + Path libraryName = Path.of(System.mapLibraryName(library)); + Path nssLibPath = fetchNssLib(osid, libraryName); + if (nssLibPath == null) { throw new SkippedException("Warning: unsupported OS: " + osid + ", please initialize NSS library location, skipping test"); } - - String libraryName = System.mapLibraryName(library); - Path libPath = Paths.get(nssLibDir).resolve(libraryName); - if (!Files.exists(libPath)) { - throw new SkippedException("NSS library \"" + libraryName + "\" was not found in " + nssLibDir); - } - - return libPath; + return nssLibPath; } private static String getOsId() { @@ -674,42 +666,42 @@ static byte[] generateData(int length) { return data; } - private static String fetchNssLib(String osId) { + private static Path fetchNssLib(String osId, Path libraryName) { switch (osId) { case "Windows-amd64-64": - return fetchNssLib(WINDOWS_X64.class); + return fetchNssLib(WINDOWS_X64.class, libraryName); case "MacOSX-x86_64-64": - return fetchNssLib(MACOSX_X64.class); + return fetchNssLib(MACOSX_X64.class, libraryName); case "MacOSX-aarch64-64": - return fetchNssLib(MACOSX_AARCH64.class); + return fetchNssLib(MACOSX_AARCH64.class, libraryName); case "Linux-amd64-64": if (Platform.isOracleLinux7()) { throw new SkippedException("Skipping Oracle Linux prior to v8"); } else { - return fetchNssLib(LINUX_X64.class); + return fetchNssLib(LINUX_X64.class, libraryName); } case "Linux-aarch64-64": if (Platform.isOracleLinux7()) { throw new SkippedException("Skipping Oracle Linux prior to v8"); } else { - return fetchNssLib(LINUX_AARCH64.class); + return fetchNssLib(LINUX_AARCH64.class, libraryName); } default: return null; } } - private static String fetchNssLib(Class clazz) { - String path = null; + private static Path fetchNssLib(Class clazz, Path libraryName) { + Path path = null; try { - path = ArtifactResolver.resolve(clazz).entrySet().stream() - .findAny().get().getValue() + File.separator + "nss" - + File.separator + "lib" + File.separator; - } catch (ArtifactResolverException e) { + Path p = ArtifactResolver.resolve(clazz).entrySet().stream() + .findAny().get().getValue(); + path = findNSSLibrary(p, libraryName); + } catch (ArtifactResolverException | IOException e) { Throwable cause = e.getCause(); if (cause == null) { System.out.println("Cannot resolve artifact, " @@ -723,6 +715,16 @@ private static String fetchNssLib(Class clazz) { return path; } + private static Path findNSSLibrary(Path path, Path libraryName) throws IOException { + try(Stream files = Files.find(path, 10, + (tp, attr) -> tp.getFileName().equals(libraryName))) { + + return files.findAny() + .orElseThrow(() -> + new RuntimeException("NSS library \"" + libraryName + "\" was not found in " + path)); + } + } + public abstract void main(Provider p) throws Exception; protected boolean skipTest(Provider p) { diff --git a/test/jdk/sun/security/provider/KeyStore/DKSTest.java b/test/jdk/sun/security/provider/KeyStore/DKSTest.java index 76c66f492d1..1d1943ec729 100644 --- a/test/jdk/sun/security/provider/KeyStore/DKSTest.java +++ b/test/jdk/sun/security/provider/KeyStore/DKSTest.java @@ -80,7 +80,7 @@ public class DKSTest { public static void main(String[] args) throws Exception { if (args.length == 0) { // Environment variable and system properties referred in domains.cfg used by this Test. - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(List.of( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(List.of( "-Dtest.src=" + TEST_SRC , "-Duser.dir=" + USER_DIR, "DKSTest", "run")); pb.environment().putAll(System.getenv()); pb.environment().put("KEYSTORE_PWD", "test12"); diff --git a/test/jdk/sun/security/ssl/ClientHandshaker/LengthCheckTest.java b/test/jdk/sun/security/ssl/ClientHandshaker/LengthCheckTest.java index 6abcab4c555..6c9dd847ee9 100644 --- a/test/jdk/sun/security/ssl/ClientHandshaker/LengthCheckTest.java +++ b/test/jdk/sun/security/ssl/ClientHandshaker/LengthCheckTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2023, Oracle and/or its affiliates. All rights reserved. * 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 @@ * @bug 8044860 * @summary Vectors and fixed length fields should be verified * for allowed sizes. - * @library /test/lib + * @library /test/lib /javax/net/ssl/templates * @modules java.base/sun.security.ssl * @run main/othervm LengthCheckTest * @key randomness @@ -70,7 +70,6 @@ import javax.net.ssl.*; import javax.net.ssl.SSLEngineResult.*; -import java.io.*; import java.security.*; import java.nio.*; import java.util.List; @@ -79,7 +78,7 @@ import jdk.test.lib.security.SecurityUtils; -public class LengthCheckTest { +public class LengthCheckTest extends SSLEngineTemplate { /* * Enables logging of the SSLEngine operations. @@ -98,41 +97,9 @@ public class LengthCheckTest { private static final boolean debug = false; private static final boolean dumpBufs = true; - private final SSLContext sslc; - - private SSLEngine clientEngine; // client Engine - private ByteBuffer clientOut; // write side of clientEngine - private ByteBuffer clientIn; // read side of clientEngine - - private SSLEngine serverEngine; // server Engine - private ByteBuffer serverOut; // write side of serverEngine - private ByteBuffer serverIn; // read side of serverEngine private HandshakeTest handshakeTest; - /* - * For data transport, this example uses local ByteBuffers. This - * isn't really useful, but the purpose of this example is to show - * SSLEngine concepts, not how to do network transport. - */ - private ByteBuffer cTOs; // "reliable" transport client->server - private ByteBuffer sTOc; // "reliable" transport server->client - - /* - * The following is to set up the keystores. - */ - private static final String pathToStores = "../../../../javax/net/ssl/etc"; - private static final String keyStoreFile = "keystore"; - private static final String trustStoreFile = "truststore"; - private static final String passwd = "passphrase"; - - private static final String keyFilename = - System.getProperty("test.src", ".") + "/" + pathToStores + - "/" + keyStoreFile; - private static final String trustFilename = - System.getProperty("test.src", ".") + "/" + pathToStores + - "/" + trustStoreFile; - // Define a few basic TLS record and message types we might need private static final int TLS_RECTYPE_CCS = 0x14; private static final int TLS_RECTYPE_ALERT = 0x15; @@ -176,20 +143,20 @@ public void execTest() throws Exception { // Send Client Hello clientResult = clientEngine.wrap(clientOut, cTOs); log("client wrap: ", clientResult); - runDelegatedTasks(clientResult, clientEngine); + runDelegatedTasks(clientEngine); cTOs.flip(); dumpByteBuffer("CLIENT-TO-SERVER", cTOs); // Server consumes Client Hello serverResult = serverEngine.unwrap(cTOs, serverIn); log("server unwrap: ", serverResult); - runDelegatedTasks(serverResult, serverEngine); + runDelegatedTasks(serverEngine); cTOs.compact(); // Server generates ServerHello/Cert/Done record serverResult = serverEngine.wrap(serverOut, sTOc); log("server wrap: ", serverResult); - runDelegatedTasks(serverResult, serverEngine); + runDelegatedTasks(serverEngine); sTOc.flip(); // Intercept the ServerHello messages and instead send @@ -220,19 +187,19 @@ public void execTest() throws Exception { gotException = true; } log("client unwrap: ", clientResult); - runDelegatedTasks(clientResult, clientEngine); + runDelegatedTasks(clientEngine); } } else { dumpByteBuffer("SERVER-TO-CLIENT", sTOc); log("client unwrap: ", clientResult); - runDelegatedTasks(clientResult, clientEngine); + runDelegatedTasks(clientEngine); } sTOc.compact(); // The Client should now send a TLS Alert clientResult = clientEngine.wrap(clientOut, cTOs); log("client wrap: ", clientResult); - runDelegatedTasks(clientResult, clientEngine); + runDelegatedTasks(clientEngine); cTOs.flip(); dumpByteBuffer("CLIENT-TO-SERVER", cTOs); @@ -264,7 +231,7 @@ public void execTest() throws Exception { // Server consumes Client Hello serverResult = serverEngine.unwrap(evilClientHello, serverIn); log("server unwrap: ", serverResult); - runDelegatedTasks(serverResult, serverEngine); + runDelegatedTasks(serverEngine); evilClientHello.compact(); // Under normal circumstances this should be a ServerHello @@ -273,7 +240,7 @@ public void execTest() throws Exception { try { serverResult = serverEngine.wrap(serverOut, sTOc); log("server wrap: ", serverResult); - runDelegatedTasks(serverResult, serverEngine); + runDelegatedTasks(serverEngine); } catch (SSLProtocolException ssle) { log("Received expected SSLProtocolException: " + ssle); gotException = true; @@ -282,7 +249,7 @@ public void execTest() throws Exception { // We expect to see the server generate an alert here serverResult = serverEngine.wrap(serverOut, sTOc); log("server wrap: ", serverResult); - runDelegatedTasks(serverResult, serverEngine); + runDelegatedTasks(serverEngine); sTOc.flip(); dumpByteBuffer("SERVER-TO-CLIENT", sTOc); @@ -326,26 +293,7 @@ public static void main(String args[]) throws Exception { * Create an initialized SSLContext to use for these tests. */ public LengthCheckTest(String testName) throws Exception { - - KeyStore ks = KeyStore.getInstance("JKS"); - KeyStore ts = KeyStore.getInstance("JKS"); - - char[] passphrase = "passphrase".toCharArray(); - - ks.load(new FileInputStream(keyFilename), passphrase); - ts.load(new FileInputStream(trustFilename), passphrase); - - KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); - kmf.init(ks, passphrase); - - TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); - tmf.init(ts); - - SSLContext sslCtx = SSLContext.getInstance("TLS"); - - sslCtx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); - - sslc = sslCtx; + super(); switch (testName) { case "ServSendLongID": @@ -378,10 +326,8 @@ public LengthCheckTest(String testName) throws Exception { * sections of code. */ private void runTest() throws Exception { - boolean dataDone = false; - - createSSLEngines(); - createBuffers(); + configureSSLEngine(); +// createBuffers(); handshakeTest.execTest(); } @@ -390,19 +336,17 @@ private void runTest() throws Exception { * Using the SSLContext created during object creation, * create/configure the SSLEngines we'll use for this test. */ - private void createSSLEngines() throws Exception { + private void configureSSLEngine() throws Exception { /* * Configure the serverEngine to act as a server in the SSL/TLS * handshake. Also, require SSL client authentication. */ - serverEngine = sslc.createSSLEngine(); serverEngine.setUseClientMode(false); serverEngine.setNeedClientAuth(false); /* * Similar to above, but using client mode instead. */ - clientEngine = sslc.createSSLEngine("client", 80); clientEngine.setUseClientMode(true); // In order to make a test that will be backwards compatible @@ -413,84 +357,6 @@ private void createSSLEngines() throws Exception { new String[]{"TLS_RSA_WITH_AES_128_CBC_SHA"}); } - /* - * Create and size the buffers appropriately. - */ - private void createBuffers() { - - /* - * We'll assume the buffer sizes are the same - * between client and server. - */ - SSLSession session = clientEngine.getSession(); - int appBufferMax = session.getApplicationBufferSize(); - int netBufferMax = session.getPacketBufferSize(); - - /* - * We'll make the input buffers a bit bigger than the max needed - * size, so that unwrap()s following a successful data transfer - * won't generate BUFFER_OVERFLOWS. - * - * We'll use a mix of direct and indirect ByteBuffers for - * tutorial purposes only. In reality, only use direct - * ByteBuffers when they give a clear performance enhancement. - */ - clientIn = ByteBuffer.allocate(appBufferMax + 50); - serverIn = ByteBuffer.allocate(appBufferMax + 50); - - cTOs = ByteBuffer.allocateDirect(netBufferMax); - sTOc = ByteBuffer.allocateDirect(netBufferMax); - - clientOut = ByteBuffer.wrap("Hi Server, I'm Client".getBytes()); - serverOut = ByteBuffer.wrap("Hello Client, I'm Server".getBytes()); - } - - /* - * If the result indicates that we have outstanding tasks to do, - * go ahead and run them in this thread. - */ - private static void runDelegatedTasks(SSLEngineResult result, - SSLEngine engine) throws Exception { - - if (result.getHandshakeStatus() == HandshakeStatus.NEED_TASK) { - Runnable runnable; - while ((runnable = engine.getDelegatedTask()) != null) { - log("\trunning delegated task..."); - runnable.run(); - } - HandshakeStatus hsStatus = engine.getHandshakeStatus(); - if (hsStatus == HandshakeStatus.NEED_TASK) { - throw new Exception( - "handshake shouldn't need additional tasks"); - } - log("\tnew HandshakeStatus: " + hsStatus); - } - } - - private static boolean isEngineClosed(SSLEngine engine) { - return (engine.isOutboundDone() && engine.isInboundDone()); - } - - /* - * Simple check to make sure everything came across as expected. - */ - private static void checkTransfer(ByteBuffer a, ByteBuffer b) - throws Exception { - a.flip(); - b.flip(); - - if (!a.equals(b)) { - throw new Exception("Data didn't transfer cleanly"); - } else { - log("\tData transferred cleanly"); - } - - a.position(a.limit()); - b.position(b.limit()); - a.limit(a.capacity()); - b.limit(b.capacity()); - } - /* * Logging code */ diff --git a/test/jdk/sun/security/ssl/DHKeyExchange/DHEKeySizing.java b/test/jdk/sun/security/ssl/DHKeyExchange/DHEKeySizing.java index 9618cae88a3..c6c8841f6c7 100644 --- a/test/jdk/sun/security/ssl/DHKeyExchange/DHEKeySizing.java +++ b/test/jdk/sun/security/ssl/DHKeyExchange/DHEKeySizing.java @@ -30,6 +30,7 @@ * @test * @bug 6956398 8301700 * @summary make ephemeral DH key match the length of the certificate key + * @library /javax/net/ssl/templates * @run main/othervm -Djdk.tls.client.enableSessionTicketExtension=false * DHEKeySizing TLS_DHE_RSA_WITH_AES_128_CBC_SHA false 1643 267 * @run main/othervm -Djsse.enableFFDHE=false @@ -122,18 +123,10 @@ import javax.net.ssl.*; import javax.net.ssl.SSLEngineResult.*; -import java.io.*; import java.nio.*; -import java.security.KeyStore; -import java.security.KeyFactory; import java.security.Security; -import java.security.cert.Certificate; -import java.security.cert.CertificateFactory; -import java.security.spec.PKCS8EncodedKeySpec; -import java.security.interfaces.*; -import java.util.Base64; -public class DHEKeySizing { +public class DHEKeySizing extends SSLEngineTemplate { private final static boolean debug = true; @@ -145,89 +138,6 @@ public class DHEKeySizing { // negotiated DH keys. private final static int KEY_LEN_BIAS = 6; - private SSLContext sslc; - private SSLEngine ssle1; // client - private SSLEngine ssle2; // server - - private ByteBuffer appOut1; // write side of ssle1 - private ByteBuffer appIn1; // read side of ssle1 - private ByteBuffer appOut2; // write side of ssle2 - private ByteBuffer appIn2; // read side of ssle2 - - private ByteBuffer oneToTwo; // "reliable" transport ssle1->ssle2 - private ByteBuffer twoToOne; // "reliable" transport ssle2->ssle1 - - /* - * Where do we find the keystores? - */ - // Certificates and key used in the test. - static String trustedCertStr = - "-----BEGIN CERTIFICATE-----\n" + - "MIIC8jCCAdqgAwIBAgIEUjkuRzANBgkqhkiG9w0BAQUFADA7MR0wGwYDVQQLExRT\n" + - "dW5KU1NFIFRlc3QgU2VyaXZjZTENMAsGA1UEChMESmF2YTELMAkGA1UEBhMCVVMw\n" + - "HhcNMTMwOTE4MDQzODMxWhcNMTMxMjE3MDQzODMxWjA7MR0wGwYDVQQLExRTdW5K\n" + - "U1NFIFRlc3QgU2VyaXZjZTENMAsGA1UEChMESmF2YTELMAkGA1UEBhMCVVMwggEi\n" + - "MA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCO+IGeaskJAvEcYc7pCl9neK3E\n" + - "a28fwWLtChufYNaC9hQfZlUdETWYjV7fZJVJKT/oLzdDNMWuVA0LKXArpI3thLNK\n" + - "QLXisdF9hKPlZRDazACL9kWUUtJ0FzpEySK4e8wW/z9FuU6e6iO19FbjxAfInJqk\n" + - "3EDiEhB5g73S2vtvPCxgq2DvWw9TDl/LIqdKG2JCS93koXCCaHmQ7MrIOqHPd+8r\n" + - "RbGpatXT9qyHKppUv9ATxVygO4rA794mgCFxpT+fkhz+NEB0twTkM65T1hnnOv5n\n" + - "ZIxkcjBggt85UlZtnP3b9P7SYxsWIa46Oc38Od2f3YejfVg6B+PqPgWNl3+/AgMB\n" + - "AAEwDQYJKoZIhvcNAQEFBQADggEBAAlrP6DFLRPSy0IgQhcI2i56tR/na8pezSte\n" + - "ZHcCdaCZPDy4UP8mpLJ9QCjEB5VJv8hPm4xdK7ULnKGOGHgYqDpV2ZHvQlhV1woQ\n" + - "TZGb/LM3c6kAs0j4j9KM2fq3iYUYexjIkS1KzsziflxMM6igS9BRMBR2LQyU+cYq\n" + - "YEsFzkF7Aj2ET4v/+tgot9mRr2NioJcaJkdsPDpMU3IKB1cczfu+OuLQ/GCG0Fqu\n" + - "6ijCeCqfnaAbemHbJeVZZ6Qgka3uC2YMntLBmLkhqEo1d9zGYLoh7oWL77y5ibQZ\n" + - "LK5/H/zikcu579TWjlDHcqL3arCwBcrtsjSaPrRSWMrWV/6c0qw=\n" + - "-----END CERTIFICATE-----"; - - // Private key in the format of PKCS#8 - static String targetPrivateKey = - "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCO+IGeaskJAvEc\n" + - "Yc7pCl9neK3Ea28fwWLtChufYNaC9hQfZlUdETWYjV7fZJVJKT/oLzdDNMWuVA0L\n" + - "KXArpI3thLNKQLXisdF9hKPlZRDazACL9kWUUtJ0FzpEySK4e8wW/z9FuU6e6iO1\n" + - "9FbjxAfInJqk3EDiEhB5g73S2vtvPCxgq2DvWw9TDl/LIqdKG2JCS93koXCCaHmQ\n" + - "7MrIOqHPd+8rRbGpatXT9qyHKppUv9ATxVygO4rA794mgCFxpT+fkhz+NEB0twTk\n" + - "M65T1hnnOv5nZIxkcjBggt85UlZtnP3b9P7SYxsWIa46Oc38Od2f3YejfVg6B+Pq\n" + - "PgWNl3+/AgMBAAECggEAPdb5Ycc4m4A9QBSCRcRpzbyiFLKPh0HDg1n65q4hOtYr\n" + - "kAVYTVFTSF/lqGS+Ob3w2YIKujQKSUQrvCc5UHdFuHXMgxKIWbymK0+DAMb9SlYw\n" + - "6lkkcWp9gx9E4dnJ/df2SAAxovvrKMuHlL1SFASHhVtPfH2URvSfUaANLDXxyYOs\n" + - "8BX0Nr6wazhWjLjXo9yIGnKSvFfB8XisYcA78kEgas43zhmIGCDPqaYyyffOfRbx\n" + - "pM1KNwGmlN86iWR1CbwA/wwhcMySWQueS+s7cHbpRqZIYJF9jEeELiwi0vxjealS\n" + - "EMuHYedIRFMWaDIq9XyjrvXamHb0Z25jlXBNZHaM0QKBgQDE9adl+zAezR/n79vw\n" + - "0XiX2Fx1UEo3ApZHuoA2Q/PcBk+rlKqqQ3IwTcy6Wo648wK7v6Nq7w5nEWcsf0dU\n" + - "QA2Ng/AJEev/IfF34x7sKGYxtk1gcE0EuSBA3R+ocEZxnNw1Ryd5nUU24s8d4jCP\n" + - "Mkothnyaim+zE2raDlEtVc0CaQKBgQC509av+02Uq5oMjzbQp5PBJfQFjATOQT15\n" + - "eefYnVYurkQ1kcVfixkrO2ORhg4SjmI2Z5hJDgGtXdwgidpzkad+R2epS5qLMyno\n" + - "lQVpY6bMpEZ7Mos0yQygxnm8uNohEcTExOe+nP5fNJVpzBsGmfeyYOhnPQlf6oqf\n" + - "0cHizedb5wKBgQC/l5LyMil6HOGHlhzmIm3jj7VI7QR0hJC5T6N+phVml8ESUDjA\n" + - "DYHbmSKouISTRtkG14FY+RiSjCxH7bvuKazFV2289PETquogTA/9e8MFYqfcQwG4\n" + - "sXi9gBxWlnj/9a2EKiYtOB5nKLR/BlNkSHA93tAA6N+FXEMZwMmYhxk42QKBgAuY\n" + - "HQgD3PZOsqDf+qKQIhbmAFCsSMx5o5VFtuJ8BpmJA/Z3ruHkMuDQpsi4nX4o5hXQ\n" + - "5t6AAjjH52kcUMXvK40kdWJJtk3DFnVNfvXxYsHX6hHbuHXFqYUKfSP6QJnZmvZP\n" + - "9smcz/4usLfWJUWHK740b6upUkFqx9Vq5/b3s9y3AoGAdM5TW7LkkOFsdMGVAUzR\n" + - "9iXmCWElHTK2Pcp/3yqDBHSfiQx6Yp5ANyPnE9NBM0yauCfOyBB2oxLO4Rdv3Rqk\n" + - "9V9kyR/YAGr7dJaPcQ7pZX0OpkzgueAOJYPrx5VUzPYUtklYV1ycFZTfKlpFCxT+\n" + - "Ei6KUo0NXSdUIcB4yib1J10="; - - static char passphrase[] = "passphrase".toCharArray(); - - /* - * Majority of the test case is here, setup is done below. - */ - - private void createSSLEngines() throws Exception { - ssle1 = sslc.createSSLEngine("client", 1); - ssle1.setUseClientMode(true); - - ssle2 = sslc.createSSLEngine("server", 2); - ssle2.setUseClientMode(false); - } - - private boolean isHandshaking(SSLEngine e) { - return (e.getHandshakeStatus() != HandshakeStatus.NOT_HANDSHAKING); - } - private void checkResult(ByteBuffer bbIn, ByteBuffer bbOut, SSLEngineResult result, Status status, HandshakeStatus hsStatus, @@ -268,130 +178,127 @@ private void checkResult(ByteBuffer bbIn, ByteBuffer bbOut, private void test(String cipherSuite, boolean exportable, int lenServerKeyEx, int lenClientKeyEx) throws Exception { - createSSLEngines(); - createBuffers(); - - SSLEngineResult result1; // ssle1's results from last operation - SSLEngineResult result2; // ssle2's results from last operation + SSLEngineResult result1; // clientEngine's results from last operation + SSLEngineResult result2; // serverEngine's results from last operation String[] suites = new String [] {cipherSuite}; - ssle1.setEnabledCipherSuites(suites); - ssle2.setEnabledCipherSuites(suites); + clientEngine.setEnabledCipherSuites(suites); + serverEngine.setEnabledCipherSuites(suites); log("======================================"); log("==================="); log("client hello"); - result1 = ssle1.wrap(appOut1, oneToTwo); - checkResult(appOut1, oneToTwo, result1, + result1 = clientEngine.wrap(clientOut, cTOs); + checkResult(clientOut, cTOs, result1, Status.OK, HandshakeStatus.NEED_UNWRAP, 0, -1); - oneToTwo.flip(); + cTOs.flip(); - result2 = ssle2.unwrap(oneToTwo, appIn2); - checkResult(oneToTwo, appIn2, result2, + result2 = serverEngine.unwrap(cTOs, serverIn); + checkResult(cTOs, serverIn, result2, Status.OK, HandshakeStatus.NEED_TASK, result1.bytesProduced(), 0); - runDelegatedTasks(ssle2); - oneToTwo.compact(); + runDelegatedTasks(serverEngine); + cTOs.compact(); log("==================="); log("ServerHello"); - result2 = ssle2.wrap(appOut2, twoToOne); - checkResult(appOut2, twoToOne, result2, + result2 = serverEngine.wrap(serverOut, sTOc); + checkResult(serverOut, sTOc, result2, Status.OK, HandshakeStatus.NEED_UNWRAP, 0, -1); - twoToOne.flip(); + sTOc.flip(); - log("Message length of ServerHello series: " + twoToOne.remaining()); - if (twoToOne.remaining() < (lenServerKeyEx - KEY_LEN_BIAS) || - twoToOne.remaining() > lenServerKeyEx) { + log("Message length of ServerHello series: " + sTOc.remaining()); + if (sTOc.remaining() < (lenServerKeyEx - KEY_LEN_BIAS) || + sTOc.remaining() > lenServerKeyEx) { throw new Exception( "Expected to generate ServerHello series messages of " + - lenServerKeyEx + " bytes, but not " + twoToOne.remaining()); + lenServerKeyEx + " bytes, but not " + sTOc.remaining()); } - result1 = ssle1.unwrap(twoToOne, appIn1); - checkResult(twoToOne, appIn1, result1, + result1 = clientEngine.unwrap(sTOc, clientIn); + checkResult(sTOc, clientIn, result1, Status.OK, HandshakeStatus.NEED_TASK, result2.bytesProduced(), 0); - runDelegatedTasks(ssle1); - twoToOne.compact(); + runDelegatedTasks(clientEngine); + sTOc.compact(); log("==================="); log("Key Exchange"); - result1 = ssle1.wrap(appOut1, oneToTwo); - checkResult(appOut1, oneToTwo, result1, + result1 = clientEngine.wrap(clientOut, cTOs); + checkResult(clientOut, cTOs, result1, Status.OK, HandshakeStatus.NEED_WRAP, 0, -1); - oneToTwo.flip(); + cTOs.flip(); - log("Message length of ClientKeyExchange: " + oneToTwo.remaining()); - if (oneToTwo.remaining() < (lenClientKeyEx - KEY_LEN_BIAS) || - oneToTwo.remaining() > lenClientKeyEx) { + log("Message length of ClientKeyExchange: " + cTOs.remaining()); + if (cTOs.remaining() < (lenClientKeyEx - KEY_LEN_BIAS) || + cTOs.remaining() > lenClientKeyEx) { throw new Exception( "Expected to generate ClientKeyExchange message of " + - lenClientKeyEx + " bytes, but not " + oneToTwo.remaining()); + lenClientKeyEx + " bytes, but not " + cTOs.remaining()); } - result2 = ssle2.unwrap(oneToTwo, appIn2); - checkResult(oneToTwo, appIn2, result2, + result2 = serverEngine.unwrap(cTOs, serverIn); + checkResult(cTOs, serverIn, result2, Status.OK, HandshakeStatus.NEED_TASK, result1.bytesProduced(), 0); - runDelegatedTasks(ssle2); - oneToTwo.compact(); + runDelegatedTasks(serverEngine); + cTOs.compact(); log("==================="); log("Client CCS"); - result1 = ssle1.wrap(appOut1, oneToTwo); - checkResult(appOut1, oneToTwo, result1, + result1 = clientEngine.wrap(clientOut, cTOs); + checkResult(clientOut, cTOs, result1, Status.OK, HandshakeStatus.NEED_WRAP, 0, -1); - oneToTwo.flip(); + cTOs.flip(); - result2 = ssle2.unwrap(oneToTwo, appIn2); - checkResult(oneToTwo, appIn2, result2, + result2 = serverEngine.unwrap(cTOs, serverIn); + checkResult(cTOs, serverIn, result2, Status.OK, HandshakeStatus.NEED_UNWRAP, result1.bytesProduced(), 0); - oneToTwo.compact(); + cTOs.compact(); log("==================="); log("Client Finished"); - result1 = ssle1.wrap(appOut1, oneToTwo); - checkResult(appOut1, oneToTwo, result1, + result1 = clientEngine.wrap(clientOut, cTOs); + checkResult(clientOut, cTOs, result1, Status.OK, HandshakeStatus.NEED_UNWRAP, 0, -1); - oneToTwo.flip(); + cTOs.flip(); - result2 = ssle2.unwrap(oneToTwo, appIn2); - checkResult(oneToTwo, appIn2, result2, + result2 = serverEngine.unwrap(cTOs, serverIn); + checkResult(cTOs, serverIn, result2, Status.OK, HandshakeStatus.NEED_WRAP, result1.bytesProduced(), 0); - oneToTwo.compact(); + cTOs.compact(); log("==================="); log("Server CCS"); - result2 = ssle2.wrap(appOut2, twoToOne); - checkResult(appOut2, twoToOne, result2, + result2 = serverEngine.wrap(serverOut, sTOc); + checkResult(serverOut, sTOc, result2, Status.OK, HandshakeStatus.NEED_WRAP, 0, -1); - twoToOne.flip(); + sTOc.flip(); - result1 = ssle1.unwrap(twoToOne, appIn1); - checkResult(twoToOne, appIn1, result1, + result1 = clientEngine.unwrap(sTOc, clientIn); + checkResult(sTOc, clientIn, result1, Status.OK, HandshakeStatus.NEED_UNWRAP, result2.bytesProduced(), 0); - twoToOne.compact(); + sTOc.compact(); log("==================="); log("Server Finished"); - result2 = ssle2.wrap(appOut2, twoToOne); - checkResult(appOut2, twoToOne, result2, + result2 = serverEngine.wrap(serverOut, sTOc); + checkResult(serverOut, sTOc, result2, Status.OK, HandshakeStatus.FINISHED, 0, -1); - twoToOne.flip(); + sTOc.flip(); - result1 = ssle1.unwrap(twoToOne, appIn1); - checkResult(twoToOne, appIn1, result1, + result1 = clientEngine.unwrap(sTOc, clientIn); + checkResult(sTOc, clientIn, result1, Status.OK, HandshakeStatus.FINISHED, result2.bytesProduced(), 0); - twoToOne.compact(); + sTOc.compact(); log("==================="); log("Check Session/Ciphers"); - String cs = ssle1.getSession().getCipherSuite(); + String cs = clientEngine.getSession().getCipherSuite(); if (!cs.equals(suites[0])) { throw new Exception("suites not equal: " + cs + "/" + suites[0]); } - cs = ssle2.getSession().getCipherSuite(); + cs = serverEngine.getSession().getCipherSuite(); if (!cs.equals(suites[0])) { throw new Exception("suites not equal: " + cs + "/" + suites[0]); } @@ -428,84 +335,36 @@ public static void main(String args[]) throws Exception { */ public DHEKeySizing() throws Exception { - sslc = getSSLContext(); + super(); } - /* - * Create an initialized SSLContext to use for this test. - */ - private SSLContext getSSLContext() throws Exception { - - // generate certificate from cert string - CertificateFactory cf = CertificateFactory.getInstance("X.509"); - - // create a key store - KeyStore ts = KeyStore.getInstance("JKS"); - KeyStore ks = KeyStore.getInstance("JKS"); - ts.load(null, null); - ks.load(null, null); - - // import the trused cert - ByteArrayInputStream is = - new ByteArrayInputStream(trustedCertStr.getBytes()); - Certificate trusedCert = cf.generateCertificate(is); - is.close(); - ts.setCertificateEntry("rsa-trusted-2048", trusedCert); - - // generate the private key. - String keySpecStr = targetPrivateKey; - PKCS8EncodedKeySpec priKeySpec = new PKCS8EncodedKeySpec( - Base64.getMimeDecoder().decode(keySpecStr)); - KeyFactory kf = KeyFactory.getInstance("RSA"); - RSAPrivateKey priKey = (RSAPrivateKey)kf.generatePrivate(priKeySpec); - - Certificate[] chain = new Certificate[1]; - chain[0] = trusedCert; - - // import the key entry. - ks.setKeyEntry("rsa-key-2048", priKey, passphrase, chain); - - // create SSL context - KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); - kmf.init(ks, passphrase); - - TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); - tmf.init(ts); - - SSLContext sslCtx = SSLContext.getInstance("TLSv1"); - sslCtx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); - - return sslCtx; + @Override + protected SSLEngine configureServerEngine(SSLEngine engine) { + engine.setNeedClientAuth(false); + engine.setUseClientMode(false); + return engine; } - private void createBuffers() { - // Size the buffers as appropriate. - - SSLSession session = ssle1.getSession(); - int appBufferMax = session.getApplicationBufferSize(); - int netBufferMax = session.getPacketBufferSize(); - - appIn1 = ByteBuffer.allocateDirect(appBufferMax + 50); - appIn2 = ByteBuffer.allocateDirect(appBufferMax + 50); - - oneToTwo = ByteBuffer.allocateDirect(netBufferMax); - twoToOne = ByteBuffer.allocateDirect(netBufferMax); - - appOut1 = ByteBuffer.wrap("Hi Engine2, I'm SSLEngine1".getBytes()); - appOut2 = ByteBuffer.wrap("Hello Engine1, I'm SSLEngine2".getBytes()); + @Override + protected SSLContext createServerSSLContext() throws Exception { + return createSSLContext(null, new Cert[]{Cert.CA_SHA1_RSA_2048}, + getServerContextParameters()); + } - log("AppOut1 = " + appOut1); - log("AppOut2 = " + appOut2); - log(""); + @Override + protected SSLContext createClientSSLContext() throws Exception { + return createSSLContext(new Cert[]{Cert.CA_SHA1_RSA_2048}, null, + getClientContextParameters()); } - private static void runDelegatedTasks(SSLEngine engine) throws Exception { + @Override + protected ContextParameters getClientContextParameters() { + return new ContextParameters("TLSv1", "PKIX", "NewSunX509"); + } - Runnable runnable; - while ((runnable = engine.getDelegatedTask()) != null) { - log("running delegated task..."); - runnable.run(); - } + @Override + protected ContextParameters getServerContextParameters() { + return new ContextParameters("TLSv1", "PKIX", "NewSunX509"); } private static void log(String str) { diff --git a/test/jdk/sun/security/ssl/EngineArgs/DebugReportsOneExtraByte.java b/test/jdk/sun/security/ssl/EngineArgs/DebugReportsOneExtraByte.java index 79405f5e6fa..1ce50662f46 100644 --- a/test/jdk/sun/security/ssl/EngineArgs/DebugReportsOneExtraByte.java +++ b/test/jdk/sun/security/ssl/EngineArgs/DebugReportsOneExtraByte.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2023, Oracle and/or its affiliates. All rights reserved. * 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,7 +25,7 @@ * @test * @bug 7126889 * @summary Incorrect SSLEngine debug output - * @library /test/lib + * @library /test/lib /javax/net/ssl/templates * @run main DebugReportsOneExtraByte */ /* @@ -74,54 +74,19 @@ import javax.net.ssl.*; import javax.net.ssl.SSLEngineResult.*; -import java.io.*; -import java.security.*; import java.nio.*; import jdk.test.lib.process.OutputAnalyzer; import jdk.test.lib.process.ProcessTools; import jdk.test.lib.security.SecurityUtils; -public class DebugReportsOneExtraByte { +public class DebugReportsOneExtraByte extends SSLEngineTemplate { /* * Enables logging of the SSLEngine operations. */ private static boolean logging = true; - private SSLContext sslc; - - private SSLEngine clientEngine; // client Engine - private ByteBuffer clientOut; // write side of clientEngine - private ByteBuffer clientIn; // read side of clientEngine - - private SSLEngine serverEngine; // server Engine - private ByteBuffer serverOut; // write side of serverEngine - private ByteBuffer serverIn; // read side of serverEngine - - /* - * For data transport, this example uses local ByteBuffers. This - * isn't really useful, but the purpose of this example is to show - * SSLEngine concepts, not how to do network transport. - */ - private ByteBuffer cTOs; // "reliable" transport client->server - private ByteBuffer sTOc; // "reliable" transport server->client - - /* - * The following is to set up the keystores. - */ - private static String pathToStores = "../../../../javax/net/ssl/etc"; - private static String keyStoreFile = "keystore"; - private static String trustStoreFile = "truststore"; - private static String passwd = "passphrase"; - - private static String keyFilename = - System.getProperty("test.src", ".") + "/" + pathToStores + - "/" + keyStoreFile; - private static String trustFilename = - System.getProperty("test.src", ".") + "/" + pathToStores + - "/" + trustStoreFile; - /* * Main entry point for this test. */ @@ -147,26 +112,38 @@ public static void main(String args[]) throws Exception { * Create an initialized SSLContext to use for these tests. */ public DebugReportsOneExtraByte() throws Exception { + super(); + } - KeyStore ks = KeyStore.getInstance("JKS"); - KeyStore ts = KeyStore.getInstance("JKS"); - - char[] passphrase = "passphrase".toCharArray(); - - ks.load(new FileInputStream(keyFilename), passphrase); - ts.load(new FileInputStream(trustFilename), passphrase); - - KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); - kmf.init(ks, passphrase); + @Override + protected SSLEngine configureServerEngine(SSLEngine serverEngine) { + serverEngine.setUseClientMode(false); + // Force a block-oriented ciphersuite. + serverEngine.setEnabledCipherSuites( + new String [] {"TLS_RSA_WITH_AES_128_CBC_SHA"}); + return serverEngine; + } - TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); - tmf.init(ts); + @Override + protected ContextParameters getClientContextParameters() { + return new ContextParameters("TLSv1", "PKIX", "NewSunX509"); + } - SSLContext sslCtx = SSLContext.getInstance("TLSv1"); + @Override + protected ContextParameters getServerContextParameters() { + return new ContextParameters("TLSv1", "PKIX", "NewSunX509"); + } - sslCtx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); + @Override + protected ByteBuffer createClientOutputBuffer() { + // No need to write anything on the client side, it will + // just confuse the output. + return ByteBuffer.wrap("".getBytes()); + } - sslc = sslCtx; + @Override + protected ByteBuffer createServerOutputBuffer() { + return ByteBuffer.wrap("Hi Client!".getBytes()); } /* @@ -189,9 +166,6 @@ public DebugReportsOneExtraByte() throws Exception { private void runTest() throws Exception { boolean dataDone = false; - createSSLEngines(); - createBuffers(); - SSLEngineResult clientResult; // results from client's last operation SSLEngineResult serverResult; // results from server's last operation @@ -217,11 +191,11 @@ private void runTest() throws Exception { clientResult = clientEngine.wrap(clientOut, cTOs); log("client wrap: ", clientResult); - runDelegatedTasks(clientResult, clientEngine); + runDelegatedTasks(clientEngine); serverResult = serverEngine.wrap(serverOut, sTOc); log("server wrap: ", serverResult); - runDelegatedTasks(serverResult, serverEngine); + runDelegatedTasks(serverEngine); // Next wrap will split. if (serverOut.position() == 1) { @@ -235,11 +209,11 @@ private void runTest() throws Exception { clientResult = clientEngine.unwrap(sTOc, clientIn); log("client unwrap: ", clientResult); - runDelegatedTasks(clientResult, clientEngine); + runDelegatedTasks(clientEngine); serverResult = serverEngine.unwrap(cTOs, serverIn); log("server unwrap: ", serverResult); - runDelegatedTasks(serverResult, serverEngine); + runDelegatedTasks(serverEngine); cTOs.compact(); sTOc.compact(); @@ -266,111 +240,10 @@ private void runTest() throws Exception { } } - /* - * Using the SSLContext created during object creation, - * create/configure the SSLEngines we'll use for this test. - */ - private void createSSLEngines() throws Exception { - /* - * Configure the serverEngine to act as a server in the SSL/TLS - * handshake. Also, require SSL client authentication. - */ - serverEngine = sslc.createSSLEngine(); - serverEngine.setUseClientMode(false); - serverEngine.setNeedClientAuth(true); - - // Force a block-oriented ciphersuite. - serverEngine.setEnabledCipherSuites( - new String [] {"TLS_RSA_WITH_AES_128_CBC_SHA"}); - - /* - * Similar to above, but using client mode instead. - */ - clientEngine = sslc.createSSLEngine("client", 80); - clientEngine.setUseClientMode(true); - } - - /* - * Create and size the buffers appropriately. - */ - private void createBuffers() { - - /* - * We'll assume the buffer sizes are the same - * between client and server. - */ - SSLSession session = clientEngine.getSession(); - int appBufferMax = session.getApplicationBufferSize(); - int netBufferMax = session.getPacketBufferSize(); - - /* - * We'll make the input buffers a bit bigger than the max needed - * size, so that unwrap()s following a successful data transfer - * won't generate BUFFER_OVERFLOWS. - * - * We'll use a mix of direct and indirect ByteBuffers for - * tutorial purposes only. In reality, only use direct - * ByteBuffers when they give a clear performance enhancement. - */ - clientIn = ByteBuffer.allocate(appBufferMax + 50); - serverIn = ByteBuffer.allocate(appBufferMax + 50); - - cTOs = ByteBuffer.allocateDirect(netBufferMax); - sTOc = ByteBuffer.allocateDirect(netBufferMax); - - // No need to write anything on the client side, it will - // just confuse the output. - clientOut = ByteBuffer.wrap("".getBytes()); - // 10 bytes long - serverOut = ByteBuffer.wrap("Hi Client!".getBytes()); - } - - /* - * If the result indicates that we have outstanding tasks to do, - * go ahead and run them in this thread. - */ - private static void runDelegatedTasks(SSLEngineResult result, - SSLEngine engine) throws Exception { - - if (result.getHandshakeStatus() == HandshakeStatus.NEED_TASK) { - Runnable runnable; - while ((runnable = engine.getDelegatedTask()) != null) { - log("\trunning delegated task..."); - runnable.run(); - } - HandshakeStatus hsStatus = engine.getHandshakeStatus(); - if (hsStatus == HandshakeStatus.NEED_TASK) { - throw new Exception( - "handshake shouldn't need additional tasks"); - } - log("\tnew HandshakeStatus: " + hsStatus); - } - } - private static boolean isEngineClosed(SSLEngine engine) { return (engine.isOutboundDone() && engine.isInboundDone()); } - /* - * Simple check to make sure everything came across as expected. - */ - private static void checkTransfer(ByteBuffer a, ByteBuffer b) - throws Exception { - a.flip(); - b.flip(); - - if (!a.equals(b)) { - throw new Exception("Data didn't transfer cleanly"); - } else { - log("\tData transferred cleanly"); - } - - a.position(a.limit()); - b.position(b.limit()); - a.limit(a.capacity()); - b.limit(b.capacity()); - } - /* * Logging code */ diff --git a/test/jdk/sun/security/ssl/HandshakeOutStream/NullCerts.java b/test/jdk/sun/security/ssl/HandshakeOutStream/NullCerts.java index 51e37a0d5af..36ecd43a33a 100644 --- a/test/jdk/sun/security/ssl/HandshakeOutStream/NullCerts.java +++ b/test/jdk/sun/security/ssl/HandshakeOutStream/NullCerts.java @@ -26,6 +26,7 @@ * @bug 4453053 * @summary If a server shuts down correctly during handshaking, the client * doesn't see it. + * @library /javax/net/ssl/templates * @run main/othervm NullCerts * * SunJSSE does not support dynamic system properties, no way to re-use @@ -34,40 +35,11 @@ */ import java.io.*; -import java.net.*; -import java.security.*; import javax.net.ssl.*; -public class NullCerts { +public class NullCerts extends SSLSocketTemplate { - /* - * ============================================================= - * Set the various variables needed for the tests, then - * specify what tests to run on each side. - */ - - /* - * Should we run the client or server in a separate thread? - * Both sides can throw exceptions, but do you have a preference - * as to which side should be the main thread. - */ - private static boolean separateServerThread = true; - - /* - * Where do we find the keystores? - */ - private final static String pathToStores = "../../../../javax/net/ssl/etc"; - private final static String keyStoreFile = "keystore"; - private final static String trustStoreFile = "truststore"; - private final static String passwd = "passphrase"; - private final static char[] cpasswd = "passphrase".toCharArray(); - - /* - * Is the server ready to serve? - */ - volatile static boolean serverReady = false; - - /* + /* * Turn on SSL debugging? */ private final static boolean DEBUG = false; @@ -81,29 +53,22 @@ public class NullCerts { * smart about it.... */ + @Override + protected void configureServerSocket(SSLServerSocket socket) { + socket.setNeedClientAuth(true); + socket.setUseClientMode(false); + } + /* * Define the server side of the test. * * If the server prematurely exits, serverReady will be set to true * to avoid infinite hangs. */ - private void doServerSide() throws Exception { - SSLServerSocketFactory sslssf = - (SSLServerSocketFactory) SSLServerSocketFactory.getDefault(); - SSLServerSocket sslServerSocket = - (SSLServerSocket) sslssf.createServerSocket(serverPort, 3); - sslServerSocket.setNeedClientAuth(true); - - serverPort = sslServerSocket.getLocalPort(); - - /* - * Signal Client, we're ready for his connect. - */ - serverReady = true; - - SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept(); - InputStream sslIS = sslSocket.getInputStream(); - OutputStream sslOS = sslSocket.getOutputStream(); + @Override + protected void runServerApplication(SSLSocket socket) throws Exception { + InputStream sslIS = socket.getInputStream(); + OutputStream sslOS = socket.getOutputStream(); try { sslIS.read(); @@ -115,7 +80,6 @@ private void doServerSide() throws Exception { + e.toString()); } - sslSocket.close(); System.out.println("Server done and exiting!"); } @@ -125,36 +89,11 @@ private void doServerSide() throws Exception { * If the server prematurely exits, serverReady will be set to true * to avoid infinite hangs. */ - private void doClientSide() throws Exception { - - /* - * Wait for server to get started. - */ - while (!serverReady) { - Thread.sleep(50); - } + @Override + protected void runClientApplication(SSLSocket sslSocket) throws Exception { System.out.println("Starting test"); - KeyStore ks = KeyStore.getInstance("JKS"); - KeyStore uks = KeyStore.getInstance("JKS"); - SSLContext ctx = SSLContext.getInstance("TLS"); - KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); - TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); - - uks.load(new FileInputStream(unknownFilename), cpasswd); - kmf.init(uks, cpasswd); - - ks.load(new FileInputStream(trustFilename), cpasswd); - tmf.init(ks); - - ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); - - SSLSocketFactory sslsf = - (SSLSocketFactory) ctx.getSocketFactory(); - SSLSocket sslSocket = (SSLSocket) - sslsf.createSocket("localhost", serverPort); - InputStream sslIS = sslSocket.getInputStream(); OutputStream sslOS = sslSocket.getOutputStream(); @@ -163,7 +102,6 @@ private void doClientSide() throws Exception { sslOS.flush(); sslIS.read(); - sslSocket.close(); } catch (IOException e) { String str = "\nYou will either see a bad_certificate SSLException\n" + @@ -174,131 +112,21 @@ private void doClientSide() throws Exception { } } - /* - * ============================================================= - * The remainder is just support stuff - */ - - // use any free port by default - volatile int serverPort = 0; - - private volatile Exception serverException = null; - private volatile Exception clientException = null; - - private final static String keyFilename = - System.getProperty("test.src", ".") + "/" + pathToStores + - "/" + keyStoreFile; - private final static String trustFilename = - System.getProperty("test.src", ".") + "/" + pathToStores + - "/" + trustStoreFile; - private final static String unknownFilename = - System.getProperty("test.src", ".") + "/" + pathToStores + - "/" + "unknown_keystore"; + @Override + protected KeyManager createClientKeyManager() throws Exception { + return createKeyManager(new Cert[]{Cert.DSA_SHA1_1024_EXPIRED}, + getClientContextParameters()); + } // Used for running test standalone public static void main(String[] args) throws Exception { - String testRoot = System.getProperty("test.src", "."); - System.setProperty("javax.net.ssl.keyStore", keyFilename); - System.setProperty("javax.net.ssl.keyStorePassword", passwd); - System.setProperty("javax.net.ssl.trustStore", trustFilename); - System.setProperty("javax.net.ssl.trustStorePassword", passwd); - if (DEBUG) System.setProperty("javax.net.debug", "all"); /* * Start the tests. */ - new NullCerts(); - } - - private Thread clientThread = null; - private Thread serverThread = null; - - /* - * Primary constructor, used to drive remainder of the test. - * - * Fork off the other side, then do your work. - */ - NullCerts() throws Exception { - - if (separateServerThread) { - startServer(true); - startClient(false); - } else { - startClient(true); - startServer(false); - } - - /* - * Wait for other side to close down. - */ - if (separateServerThread) { - serverThread.join(); - } else { - clientThread.join(); - } - - /* - * When we get here, the test is pretty much over. - * - * If the main thread excepted, that propagates back - * immediately. If the other thread threw an exception, we - * should report back. - */ - if (serverException != null) { - System.err.print("Server Exception:"); - throw serverException; - } - if (clientException != null) { - System.err.print("Client Exception:"); - throw clientException; - } - } - - private void startServer(boolean newThread) throws Exception { - if (newThread) { - serverThread = new Thread() { - public void run() { - try { - doServerSide(); - } catch (Exception e) { - /* - * Our server thread just died. - * - * Release the client, if not active already... - */ - System.err.println("Server died..."); - serverReady = true; - serverException = e; - } - } - }; - serverThread.start(); - } else { - doServerSide(); - } - } - - private void startClient(boolean newThread) throws Exception { - if (newThread) { - clientThread = new Thread() { - public void run() { - try { - doClientSide(); - } catch (Exception e) { - /* - * Our client thread just died. - */ - System.err.println("Client died..."); - clientException = e; - } - } - }; - clientThread.start(); - } else { - doClientSide(); - } + new NullCerts().run(); } } diff --git a/test/jdk/sun/security/ssl/SSLEngineImpl/CloseEngineException.java b/test/jdk/sun/security/ssl/SSLEngineImpl/CloseEngineException.java index 390da17f8e0..9a1e259cd16 100644 --- a/test/jdk/sun/security/ssl/SSLEngineImpl/CloseEngineException.java +++ b/test/jdk/sun/security/ssl/SSLEngineImpl/CloseEngineException.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2023, Oracle and/or its affiliates. All rights reserved. * 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 @@ * @bug 4969799 * @summary javax.net.ssl.SSLSocket.SSLSocket(InetAddress,int) shouldn't * throw exception + * @library /javax/net/ssl/templates * @run main/othervm CloseEngineException */ @@ -40,128 +41,85 @@ // import javax.net.ssl.*; -import javax.net.ssl.SSLEngineResult.*; -import java.io.*; -import java.security.*; -import java.nio.*; // Note that this test case depends on JSSE provider implementation details. -public class CloseEngineException { +public class CloseEngineException extends SSLEngineTemplate { private static boolean debug = true; - private SSLContext sslc; - private SSLEngine ssle1; // client - private SSLEngine ssle2; // server - - private static String pathToStores = "../../../../javax/net/ssl/etc"; - private static String keyStoreFile = "keystore"; - private static String trustStoreFile = "truststore"; - private static String passwd = "passphrase"; - - private static String keyFilename = - System.getProperty("test.src", "./") + "/" + pathToStores + - "/" + keyStoreFile; - private static String trustFilename = - System.getProperty("test.src", "./") + "/" + pathToStores + - "/" + trustStoreFile; - - private ByteBuffer appOut1; // write side of ssle1 - private ByteBuffer appIn1; // read side of ssle1 - private ByteBuffer appOut2; // write side of ssle2 - private ByteBuffer appIn2; // read side of ssle2 - - private ByteBuffer oneToTwo; // "reliable" transport ssle1->ssle2 - private ByteBuffer twoToOne; // "reliable" transport ssle2->ssle1 - - /* - * Majority of the test case is here, setup is done below. - */ - private void createSSLEngines() throws Exception { - ssle1 = sslc.createSSLEngine("client", 1); - ssle1.setUseClientMode(true); - - ssle2 = sslc.createSSLEngine(); - ssle2.setUseClientMode(false); - ssle2.setNeedClientAuth(true); - } - private void runTest() throws Exception { boolean dataDone = false; - createSSLEngines(); - createBuffers(); - - SSLEngineResult result1; // ssle1's results from last operation + SSLEngineResult result1; // clientEngine's results from last operation SSLEngineResult result2; // ssle2's results from last operation - while (!isEngineClosed(ssle1) && !isEngineClosed(ssle2)) { + while (!isEngineClosed(clientEngine) && !isEngineClosed(serverEngine)) { log("================"); - if (!isEngineClosed(ssle1)) { - result1 = ssle1.wrap(appOut1, oneToTwo); - runDelegatedTasks(result1, ssle1); + if (!isEngineClosed(clientEngine)) { + result1 = clientEngine.wrap(clientOut, cTOs); + runDelegatedTasks(clientEngine); log("wrap1: " + result1); - log("oneToTwo = " + oneToTwo); + log("oneToTwo = " + cTOs); log(""); - oneToTwo.flip(); + cTOs.flip(); } - if (!isEngineClosed(ssle2)) { - result2 = ssle2.wrap(appOut2, twoToOne); - runDelegatedTasks(result2, ssle2); + if (!isEngineClosed(serverEngine)) { + result2 = serverEngine.wrap(serverOut, sTOc); + runDelegatedTasks(serverEngine); log("wrap2: " + result2); - log("twoToOne = " + twoToOne); + log("twoToOne = " + sTOc); - twoToOne.flip(); + sTOc.flip(); } log("----"); - if (!isEngineClosed(ssle1) && !dataDone) { + if (!isEngineClosed(clientEngine) && !dataDone) { log("--"); - result1 = ssle1.unwrap(twoToOne, appIn1); - runDelegatedTasks(result1, ssle1); + result1 = clientEngine.unwrap(sTOc, clientIn); + runDelegatedTasks(clientEngine); log("unwrap1: " + result1); - log("twoToOne = " + twoToOne); + log("twoToOne = " + sTOc); log(""); - twoToOne.compact(); + sTOc.compact(); } - if (!isEngineClosed(ssle2)) { + if (!isEngineClosed(serverEngine)) { log("---"); - result2 = ssle2.unwrap(oneToTwo, appIn2); - runDelegatedTasks(result2, ssle2); + result2 = serverEngine.unwrap(cTOs, serverIn); + runDelegatedTasks(serverEngine); log("unwrap2: " + result2); - log("oneToTwo = " + oneToTwo); + log("oneToTwo = " + cTOs); - oneToTwo.compact(); + cTOs.compact(); } /* * If we've transfered all the data between app1 and app2, * we try to close and see what that gets us. */ - if (!dataDone && (appOut1.limit() == appIn2.position()) && - (appOut2.limit() == appIn1.position())) { + if (!dataDone && (clientOut.limit() == serverIn.position()) && + (serverOut.limit() == clientIn.position())) { - checkTransfer(appOut1, appIn2); - checkTransfer(appOut2, appIn1); + checkTransfer(clientOut, serverIn); + checkTransfer(serverOut, clientIn); - log("Closing ssle1's *OUTBOUND*..."); - ssle1.closeOutbound(); + log("Closing clientEngine's *OUTBOUND*..."); + clientEngine.closeOutbound(); dataDone = true; try { /* * Check that closed Outbound generates. */ - ssle1.beginHandshake(); + clientEngine.beginHandshake(); throw new Exception( "TEST FAILED: didn't throw Exception"); } catch (SSLException e) { @@ -174,7 +132,7 @@ private void runTest() throws Exception { /* * Check that closed Inbound generates. */ - ssle2.beginHandshake(); + serverEngine.beginHandshake(); throw new Exception( "TEST FAILED: didn't throw Exception"); } catch (SSLException e) { @@ -184,12 +142,7 @@ private void runTest() throws Exception { public static void main(String args[]) throws Exception { - CloseEngineException test; - - test = new CloseEngineException(); - - test.createSSLEngines(); - + CloseEngineException test = new CloseEngineException(); test.runTest(); System.err.println("Test Passed."); @@ -202,90 +155,20 @@ public static void main(String args[]) throws Exception { */ public CloseEngineException() throws Exception { - sslc = getSSLContext(keyFilename, trustFilename); + super(); } - /* - * Create an initialized SSLContext to use for this test. - */ - private SSLContext getSSLContext(String keyFile, String trustFile) - throws Exception { - - KeyStore ks = KeyStore.getInstance("JKS"); - KeyStore ts = KeyStore.getInstance("JKS"); - - char[] passphrase = "passphrase".toCharArray(); - - ks.load(new FileInputStream(keyFile), passphrase); - ts.load(new FileInputStream(trustFile), passphrase); - - KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); - kmf.init(ks, passphrase); - - TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); - tmf.init(ts); - - SSLContext sslCtx = SSLContext.getInstance("TLS"); - - sslCtx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); - - return sslCtx; - } - - private void createBuffers() { - // Size the buffers as appropriate. - - SSLSession session = ssle1.getSession(); - int appBufferMax = session.getApplicationBufferSize(); - int netBufferMax = session.getPacketBufferSize(); - - appIn1 = ByteBuffer.allocateDirect(appBufferMax + 50); - appIn2 = ByteBuffer.allocateDirect(appBufferMax + 50); - - oneToTwo = ByteBuffer.allocateDirect(netBufferMax); - twoToOne = ByteBuffer.allocateDirect(netBufferMax); - - appOut1 = ByteBuffer.wrap("Hi Engine2, I'm SSLEngine1".getBytes()); - appOut2 = ByteBuffer.wrap("Hello Engine1, I'm SSLEngine2".getBytes()); - - log("AppOut1 = " + appOut1); - log("AppOut2 = " + appOut2); - log(""); - } - - private static void runDelegatedTasks(SSLEngineResult result, - SSLEngine engine) throws Exception { - - if (result.getHandshakeStatus() == HandshakeStatus.NEED_TASK) { - Runnable runnable; - while ((runnable = engine.getDelegatedTask()) != null) { - log("running delegated task..."); - runnable.run(); - } - } + @Override + protected SSLEngine configureServerEngine(SSLEngine engine) { + engine.setUseClientMode(false); + engine.setNeedClientAuth(true); + return engine; } private static boolean isEngineClosed(SSLEngine engine) { return (engine.isOutboundDone() && engine.isInboundDone()); } - private static void checkTransfer(ByteBuffer a, ByteBuffer b) - throws Exception { - a.flip(); - b.flip(); - - if (!a.equals(b)) { - throw new Exception("Data didn't transfer cleanly"); - } else { - log("Data transferred cleanly"); - } - - a.position(a.limit()); - b.position(b.limit()); - a.limit(a.capacity()); - b.limit(b.capacity()); - } - private static void log(String str) { if (debug) { System.err.println(str); diff --git a/test/jdk/sun/security/ssl/SSLEngineImpl/CloseStart.java b/test/jdk/sun/security/ssl/SSLEngineImpl/CloseStart.java index 30c2a74234b..ba5b04148c3 100644 --- a/test/jdk/sun/security/ssl/SSLEngineImpl/CloseStart.java +++ b/test/jdk/sun/security/ssl/SSLEngineImpl/CloseStart.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2004, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2004, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -30,6 +30,7 @@ * @test * @bug 5019096 * @summary Add scatter/gather APIs for SSLEngine + * @library /javax/net/ssl/templates * @run main/othervm CloseStart */ @@ -38,26 +39,8 @@ // import javax.net.ssl.*; -import javax.net.ssl.SSLEngineResult.*; -import java.io.*; -import java.security.*; -import java.nio.*; -public class CloseStart { - - private static boolean debug = false; - - private static String pathToStores = "../../../../javax/net/ssl/etc"; - private static String keyStoreFile = "keystore"; - private static String trustStoreFile = "truststore"; - private static String passwd = "passphrase"; - - private static String keyFilename = - System.getProperty("test.src", "./") + "/" + pathToStores + - "/" + keyStoreFile; - private static String trustFilename = - System.getProperty("test.src", "./") + "/" + pathToStores + - "/" + trustStoreFile; +public class CloseStart extends SSLContextTemplate { private static void checkDone(SSLEngine ssle) throws Exception { if (!ssle.isInboundDone()) { @@ -74,14 +57,17 @@ private static void runTest2(SSLEngine ssle) throws Exception { } public static void main(String args[]) throws Exception { + new CloseStart().run(); + } - SSLEngine ssle = createSSLEngine(keyFilename, trustFilename); + private void run() throws Exception { + SSLEngine ssle = createSSLEngine(); ssle.closeInbound(); if (!ssle.isInboundDone()) { throw new Exception("isInboundDone isn't done"); } - ssle = createSSLEngine(keyFilename, trustFilename); + ssle = createSSLEngine(); ssle.closeOutbound(); if (!ssle.isOutboundDone()) { throw new Exception("isOutboundDone isn't done"); @@ -93,30 +79,10 @@ public static void main(String args[]) throws Exception { /* * Create an initialized SSLContext to use for this test. */ - static private SSLEngine createSSLEngine(String keyFile, String trustFile) - throws Exception { - - SSLEngine ssle; - - KeyStore ks = KeyStore.getInstance("JKS"); - KeyStore ts = KeyStore.getInstance("JKS"); - - char[] passphrase = "passphrase".toCharArray(); - - ks.load(new FileInputStream(keyFile), passphrase); - ts.load(new FileInputStream(trustFile), passphrase); - - KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); - kmf.init(ks, passphrase); - - TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); - tmf.init(ts); - - SSLContext sslCtx = SSLContext.getInstance("TLS"); - - sslCtx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); + private SSLEngine createSSLEngine() throws Exception { - ssle = sslCtx.createSSLEngine("client", 1001); + SSLContext sslCtx = createClientSSLContext(); + SSLEngine ssle = sslCtx.createSSLEngine("client", 1001); ssle.setUseClientMode(true); return ssle; diff --git a/test/jdk/sun/security/ssl/SSLEngineImpl/DelegatedTaskWrongException.java b/test/jdk/sun/security/ssl/SSLEngineImpl/DelegatedTaskWrongException.java index 7c75f0e1402..e54f8ffec42 100644 --- a/test/jdk/sun/security/ssl/SSLEngineImpl/DelegatedTaskWrongException.java +++ b/test/jdk/sun/security/ssl/SSLEngineImpl/DelegatedTaskWrongException.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -30,72 +30,38 @@ * @test * @bug 4969459 * @summary Delegated tasks are not reflecting the subclasses of SSLException + * @library /javax/net/ssl/templates * @run main/othervm DelegatedTaskWrongException */ import javax.net.ssl.*; -import javax.net.ssl.SSLEngineResult.*; -import java.io.*; import java.security.*; -import java.nio.*; -public class DelegatedTaskWrongException { +public class DelegatedTaskWrongException extends SSLEngineTemplate { private static boolean debug = false; - private SSLContext sslc; - private SSLEngine ssle1; // client - private SSLEngine ssle2; // server - - private static String pathToStores = "../../../../javax/net/ssl/etc"; - private static String keyStoreFile = "keystore"; - private static String trustStoreFile = "truststore"; - private static String passwd = "passphrase"; - - private static String keyFilename = - System.getProperty("test.src", "./") + "/" + pathToStores + - "/" + keyStoreFile; - private static String trustFilename = - System.getProperty("test.src", "./") + "/" + pathToStores + - "/" + trustStoreFile; - - private ByteBuffer appOut1; // write side of ssle1 - private ByteBuffer appIn1; // read side of ssle1 - private ByteBuffer appOut2; // write side of ssle2 - private ByteBuffer appIn2; // read side of ssle2 - - private ByteBuffer oneToTwo; // "reliable" transport ssle1->ssle2 - private ByteBuffer twoToOne; // "reliable" transport ssle2->ssle1 - - /* - * Majority of the test case is here, setup is done below. - */ - private void createSSLEngines() throws Exception { - ssle1 = sslc.createSSLEngine("client", 1); - ssle1.setUseClientMode(true); - - ssle2 = sslc.createSSLEngine(); - ssle2.setUseClientMode(false); + @Override + protected SSLEngine configureServerEngine(SSLEngine engine) { + engine.setUseClientMode(false); + engine.setEnabledProtocols(new String [] { "TLSv1" }); + return engine; + } - ssle1.setEnabledProtocols(new String [] { "SSLv3" }); - ssle2.setEnabledProtocols(new String [] { "TLSv1" }); + @Override + protected SSLEngine configureClientEngine(SSLEngine engine) { + engine.setUseClientMode(true); + engine.setEnabledProtocols(new String [] { "SSLv3" }); + return engine; } private void runTest() throws Exception { - boolean dataDone = false; - - createSSLEngines(); - createBuffers(); - - SSLEngineResult result1; // ssle1's results from last operation - SSLEngineResult result2; // ssle2's results from last operation - - result1 = ssle1.wrap(appOut1, oneToTwo); - oneToTwo.flip(); - result2 = ssle2.unwrap(oneToTwo, appIn2); + clientEngine.wrap(clientOut, cTOs); + cTOs.flip(); - runDelegatedTasks(result2, ssle2); + serverEngine.unwrap(cTOs, serverIn); + runDelegatedTasks(serverEngine); try { /* @@ -103,7 +69,7 @@ private void runTest() throws Exception { * If this changes, we'll need to update this test. * Anything else and we fail. */ - result2 = ssle2.unwrap(oneToTwo, appIn2); + serverEngine.unwrap(cTOs, serverIn); throw new Exception( "TEST FAILED: Didn't generate any exception"); } catch (SSLHandshakeException e) { @@ -119,12 +85,7 @@ public static void main(String args[]) throws Exception { // and keys used in this test are not disabled. Security.setProperty("jdk.tls.disabledAlgorithms", ""); - DelegatedTaskWrongException test; - - test = new DelegatedTaskWrongException(); - - test.createSSLEngines(); - + DelegatedTaskWrongException test = new DelegatedTaskWrongException(); test.runTest(); System.out.println("Test Passed."); @@ -137,88 +98,7 @@ public static void main(String args[]) throws Exception { */ public DelegatedTaskWrongException() throws Exception { - sslc = getSSLContext(keyFilename, trustFilename); - } - - /* - * Create an initialized SSLContext to use for this test. - */ - private SSLContext getSSLContext(String keyFile, String trustFile) - throws Exception { - - KeyStore ks = KeyStore.getInstance("JKS"); - KeyStore ts = KeyStore.getInstance("JKS"); - - char[] passphrase = "passphrase".toCharArray(); - - ks.load(new FileInputStream(keyFile), passphrase); - ts.load(new FileInputStream(trustFile), passphrase); - - KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); - kmf.init(ks, passphrase); - - TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); - tmf.init(ts); - - SSLContext sslCtx = SSLContext.getInstance("TLS"); - - sslCtx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); - - return sslCtx; - } - - private void createBuffers() { - // Size the buffers as appropriate. - - SSLSession session = ssle1.getSession(); - int appBufferMax = session.getApplicationBufferSize(); - int netBufferMax = session.getPacketBufferSize(); - - appIn1 = ByteBuffer.allocateDirect(appBufferMax + 50); - appIn2 = ByteBuffer.allocateDirect(appBufferMax + 50); - - oneToTwo = ByteBuffer.allocateDirect(netBufferMax); - twoToOne = ByteBuffer.allocateDirect(netBufferMax); - - appOut1 = ByteBuffer.wrap("Hi Engine2, I'm SSLEngine1".getBytes()); - appOut2 = ByteBuffer.wrap("Hello Engine1, I'm SSLEngine2".getBytes()); - - log("AppOut1 = " + appOut1); - log("AppOut2 = " + appOut2); - log(""); - } - - private static void runDelegatedTasks(SSLEngineResult result, - SSLEngine engine) throws Exception { - - if (result.getHandshakeStatus() == HandshakeStatus.NEED_TASK) { - Runnable runnable; - while ((runnable = engine.getDelegatedTask()) != null) { - log("running delegated task..."); - runnable.run(); - } - } - } - - private static boolean isEngineClosed(SSLEngine engine) { - return (engine.isOutboundDone() && engine.isInboundDone()); - } - - private static void checkTransfer(ByteBuffer a, ByteBuffer b) - throws Exception { - a.flip(); - b.flip(); - - if (!a.equals(b)) { - throw new Exception("Data didn't transfer cleanly"); - } else { - log("Data transferred cleanly"); - } - - a.position(a.limit()); - b.position(b.limit()); - a.limit(a.capacity()); - b.limit(b.capacity()); + super(); } private static void log(String str) { diff --git a/test/jdk/sun/security/ssl/SSLEngineImpl/EmptyExtensionData.java b/test/jdk/sun/security/ssl/SSLEngineImpl/EmptyExtensionData.java index 7e9f314cfae..f86a1f81474 100644 --- a/test/jdk/sun/security/ssl/SSLEngineImpl/EmptyExtensionData.java +++ b/test/jdk/sun/security/ssl/SSLEngineImpl/EmptyExtensionData.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2008, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2008, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -30,44 +30,21 @@ * @test * @bug 6728126 * @summary Parsing Extensions in Client Hello message is done in a wrong way - * @library /test/lib + * @library /test/lib /javax/net/ssl/templates * @run main/othervm EmptyExtensionData */ import javax.net.ssl.*; import javax.net.ssl.SSLEngineResult.*; -import java.io.*; -import java.security.*; import java.nio.*; import jdk.test.lib.security.SecurityUtils; -public class EmptyExtensionData { +public class EmptyExtensionData extends SSLContextTemplate { private static boolean debug = false; - private static String pathToStores = "../../../../javax/net/ssl/etc"; - private static String keyStoreFile = "keystore"; - private static String trustStoreFile = "truststore"; - private static String passwd = "passphrase"; - - private static String keyFilename = - System.getProperty("test.src", "./") + "/" + pathToStores + - "/" + keyStoreFile; - private static String trustFilename = - System.getProperty("test.src", "./") + "/" + pathToStores + - "/" + trustStoreFile; - - private static void checkDone(SSLEngine ssle) throws Exception { - if (!ssle.isInboundDone()) { - throw new Exception("isInboundDone isn't done"); - } - if (!ssle.isOutboundDone()) { - throw new Exception("isOutboundDone isn't done"); - } - } - - private static void runTest(SSLEngine ssle) throws Exception { + private void runTest(SSLEngine ssle) throws Exception { // a client hello message with an empty extension data byte[] msg_clihello = { (byte)0x16, (byte)0x03, (byte)0x01, (byte)0x00, @@ -138,7 +115,7 @@ private static void runTest(SSLEngine ssle) throws Exception { * If the result indicates that we have outstanding tasks to do, * go ahead and run them in this thread. */ - private static void runDelegatedTasks(SSLEngineResult result, + private void runDelegatedTasks(SSLEngineResult result, SSLEngine engine) throws Exception { if (result.getHandshakeStatus() == HandshakeStatus.NEED_TASK) { @@ -159,46 +136,17 @@ private static void runDelegatedTasks(SSLEngineResult result, public static void main(String args[]) throws Exception { // Re-enable TLSv1 since test depends on it. SecurityUtils.removeFromDisabledTlsAlgs("TLSv1"); - - SSLEngine ssle = createSSLEngine(keyFilename, trustFilename); - runTest(ssle); - - System.out.println("Test Passed."); + new EmptyExtensionData().run(); } - /* - * Create an initialized SSLContext to use for this test. - */ - static private SSLEngine createSSLEngine(String keyFile, String trustFile) - throws Exception { - - SSLEngine ssle; - - KeyStore ks = KeyStore.getInstance("JKS"); - KeyStore ts = KeyStore.getInstance("JKS"); - - char[] passphrase = "passphrase".toCharArray(); - - ks.load(new FileInputStream(keyFile), passphrase); - ts.load(new FileInputStream(trustFile), passphrase); - - KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); - kmf.init(ks, passphrase); - - TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); - tmf.init(ts); - - SSLContext sslCtx = SSLContext.getInstance("TLS"); - - sslCtx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); - - ssle = sslCtx.createSSLEngine(); + private void run() throws Exception { + SSLEngine ssle = createServerSSLContext().createSSLEngine(); ssle.setUseClientMode(false); + runTest(ssle); - return ssle; + System.out.println("Test Passed."); } - private static void log(String str) { if (debug) { System.out.println(str); diff --git a/test/jdk/sun/security/ssl/SSLEngineImpl/EngineEnforceUseClientMode.java b/test/jdk/sun/security/ssl/SSLEngineImpl/EngineEnforceUseClientMode.java index 1457384a3f1..0b80eda24af 100644 --- a/test/jdk/sun/security/ssl/SSLEngineImpl/EngineEnforceUseClientMode.java +++ b/test/jdk/sun/security/ssl/SSLEngineImpl/EngineEnforceUseClientMode.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2004, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2004, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -30,67 +30,34 @@ * @test * @bug 4980882 8207250 8237474 * @summary SSLEngine should enforce setUseClientMode + * @library /javax/net/ssl/templates * @run main/othervm EngineEnforceUseClientMode * @author Brad R. Wetmore */ import javax.net.ssl.*; -import javax.net.ssl.SSLEngineResult.*; -import java.io.*; -import java.security.*; -import java.nio.*; -public class EngineEnforceUseClientMode { +public class EngineEnforceUseClientMode extends SSLEngineTemplate { private static boolean debug = false; - private SSLContext sslc; - private SSLEngine ssle1; // client - private SSLEngine ssle2; // server - - private SSLEngine ssle3; // server - private SSLEngine ssle4; // server - private SSLEngine ssle5; // server - - private static String pathToStores = "../../../../javax/net/ssl/etc"; - private static String keyStoreFile = "keystore"; - private static String trustStoreFile = "truststore"; - private static String passwd = "passphrase"; - - private static String keyFilename = - System.getProperty("test.src", "./") + "/" + pathToStores + - "/" + keyStoreFile; - private static String trustFilename = - System.getProperty("test.src", "./") + "/" + pathToStores + - "/" + trustStoreFile; - - private ByteBuffer appOut1; // write side of ssle1 - private ByteBuffer appIn1; // read side of ssle1 - private ByteBuffer appOut2; // write side of ssle2 - private ByteBuffer appIn2; // read side of ssle2 - - private ByteBuffer oneToTwo; // "reliable" transport ssle1->ssle2 - private ByteBuffer twoToOne; // "reliable" transport ssle2->ssle1 + private SSLEngine serverEngine2; // server + private SSLEngine serverEngine3; // server + private SSLEngine serverEngine4; // server /* * Majority of the test case is here, setup is done below. */ - private void createSSLEngines() throws Exception { - ssle1 = sslc.createSSLEngine("client", 1); - ssle1.setUseClientMode(true); - - ssle2 = sslc.createSSLEngine(); - ssle2.setUseClientMode(false); - ssle2.setNeedClientAuth(true); - + private void createAdditionalSSLEngines() throws Exception { + SSLContext sslc = createServerSSLContext(); /* * Note, these are not initialized to client/server */ - ssle3 = sslc.createSSLEngine(); - ssle4 = sslc.createSSLEngine(); - ssle5 = sslc.createSSLEngine(); + serverEngine2 = sslc.createSSLEngine(); + serverEngine3 = sslc.createSSLEngine(); + serverEngine4 = sslc.createSSLEngine(); //Check default SSLEngine role. - if (ssle5.getUseClientMode()) { + if (serverEngine4.getUseClientMode()) { throw new RuntimeException("Expected default role to be server"); } @@ -98,8 +65,7 @@ private void createSSLEngines() throws Exception { private void runTest() throws Exception { - createSSLEngines(); - createBuffers(); + createAdditionalSSLEngines(); /* * First try the engines with no client/server initialization @@ -107,35 +73,35 @@ private void runTest() throws Exception { */ try { System.out.println("Testing wrap()"); - ssle3.wrap(appOut1, oneToTwo); + serverEngine2.wrap(clientOut, cTOs); throw new RuntimeException( "wrap(): Didn't catch the exception properly"); } catch (IllegalStateException e) { System.out.println("Caught the correct exception."); - oneToTwo.flip(); - if (oneToTwo.hasRemaining()) { + cTOs.flip(); + if (cTOs.hasRemaining()) { throw new Exception("wrap generated data"); } - oneToTwo.clear(); + cTOs.clear(); } try { System.out.println("Testing unwrap()"); - ssle4.unwrap(oneToTwo, appIn1); + serverEngine3.unwrap(cTOs, clientIn); throw new RuntimeException( "unwrap(): Didn't catch the exception properly"); } catch (IllegalStateException e) { System.out.println("Caught the correct exception."); - appIn1.flip(); - if (appIn1.hasRemaining()) { + clientIn.flip(); + if (clientIn.hasRemaining()) { throw new Exception("unwrap generated data"); } - appIn1.clear(); + clientIn.clear(); } try { System.out.println("Testing beginHandshake()"); - ssle5.beginHandshake(); + serverEngine4.beginHandshake(); throw new RuntimeException( "unwrap(): Didn't catch the exception properly"); } catch (IllegalStateException e) { @@ -147,60 +113,60 @@ private void runTest() throws Exception { SSLEngineResult result1; // ssle1's results from last operation SSLEngineResult result2; // ssle2's results from last operation - while (!isEngineClosed(ssle1) || !isEngineClosed(ssle2)) { + while (!isEngineClosed(clientEngine) || !isEngineClosed(serverEngine)) { log("================"); - result1 = ssle1.wrap(appOut1, oneToTwo); - result2 = ssle2.wrap(appOut2, twoToOne); + result1 = clientEngine.wrap(clientOut, cTOs); + result2 = serverEngine.wrap(serverOut, sTOc); log("wrap1: " + result1); - log("oneToTwo = " + oneToTwo); + log("oneToTwo = " + cTOs); log(""); log("wrap2: " + result2); - log("twoToOne = " + twoToOne); + log("twoToOne = " + sTOc); - runDelegatedTasks(result1, ssle1); - runDelegatedTasks(result2, ssle2); + runDelegatedTasks(clientEngine); + runDelegatedTasks(serverEngine); - oneToTwo.flip(); - twoToOne.flip(); + cTOs.flip(); + sTOc.flip(); log("----"); - result1 = ssle1.unwrap(twoToOne, appIn1); - result2 = ssle2.unwrap(oneToTwo, appIn2); + result1 = clientEngine.unwrap(sTOc, clientIn); + result2 = serverEngine.unwrap(cTOs, serverIn); log("unwrap1: " + result1); - log("twoToOne = " + twoToOne); + log("twoToOne = " + sTOc); log(""); log("unwrap2: " + result2); - log("oneToTwo = " + oneToTwo); + log("oneToTwo = " + cTOs); - runDelegatedTasks(result1, ssle1); - runDelegatedTasks(result2, ssle2); + runDelegatedTasks(clientEngine); + runDelegatedTasks(serverEngine); - oneToTwo.compact(); - twoToOne.compact(); + cTOs.compact(); + sTOc.compact(); /* * If we've transfered all the data between app1 and app2, * we try to close and see what that gets us. */ - if (!dataDone && (appOut1.limit() == appIn2.position()) && - (appOut2.limit() == appIn1.position())) { + if (!dataDone && (clientOut.limit() == serverIn.position()) && + (serverOut.limit() == clientIn.position())) { - checkTransfer(appOut1, appIn2); - checkTransfer(appOut2, appIn1); + checkTransfer(clientOut, serverIn); + checkTransfer(serverOut, clientIn); // Should not be able to set mode now, no matter if // it is the same of different. System.out.println("Try changing modes..."); for (boolean b : new Boolean[] {true, false}) { try { - ssle2.setUseClientMode(b); + serverEngine.setUseClientMode(b); throw new RuntimeException( "setUseClientMode(" + b + "): " + "Didn't catch the exception properly"); @@ -216,12 +182,8 @@ private void runTest() throws Exception { public static void main(String args[]) throws Exception { - EngineEnforceUseClientMode test; - - test = new EngineEnforceUseClientMode(); - - test.createSSLEngines(); - + EngineEnforceUseClientMode test = new EngineEnforceUseClientMode(); + test.createAdditionalSSLEngines(); test.runTest(); System.out.println("Test Passed."); @@ -234,89 +196,13 @@ public static void main(String args[]) throws Exception { */ public EngineEnforceUseClientMode() throws Exception { - sslc = getSSLContext(keyFilename, trustFilename); - } - - /* - * Create an initialized SSLContext to use for this test. - */ - private SSLContext getSSLContext(String keyFile, String trustFile) - throws Exception { - - KeyStore ks = KeyStore.getInstance("JKS"); - KeyStore ts = KeyStore.getInstance("JKS"); - - char[] passphrase = "passphrase".toCharArray(); - - ks.load(new FileInputStream(keyFile), passphrase); - ts.load(new FileInputStream(trustFile), passphrase); - - KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); - kmf.init(ks, passphrase); - - TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); - tmf.init(ts); - - SSLContext sslCtx = SSLContext.getInstance("TLS"); - - sslCtx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); - - return sslCtx; - } - - private void createBuffers() { - // Size the buffers as appropriate. - - SSLSession session = ssle1.getSession(); - int appBufferMax = session.getApplicationBufferSize(); - int netBufferMax = session.getPacketBufferSize(); - - appIn1 = ByteBuffer.allocateDirect(appBufferMax + 50); - appIn2 = ByteBuffer.allocateDirect(appBufferMax + 50); - - oneToTwo = ByteBuffer.allocateDirect(netBufferMax); - twoToOne = ByteBuffer.allocateDirect(netBufferMax); - - appOut1 = ByteBuffer.wrap("Hi Engine2, I'm SSLEngine1".getBytes()); - appOut2 = ByteBuffer.wrap("Hello Engine1, I'm SSLEngine2".getBytes()); - - log("AppOut1 = " + appOut1); - log("AppOut2 = " + appOut2); - log(""); - } - - private static void runDelegatedTasks(SSLEngineResult result, - SSLEngine engine) throws Exception { - - if (result.getHandshakeStatus() == HandshakeStatus.NEED_TASK) { - Runnable runnable; - while ((runnable = engine.getDelegatedTask()) != null) { - log("running delegated task..."); - runnable.run(); - } - } + super(); } private static boolean isEngineClosed(SSLEngine engine) { return (engine.isOutboundDone() && engine.isInboundDone()); } - private static void checkTransfer(ByteBuffer a, ByteBuffer b) - throws Exception { - a.flip(); - b.flip(); - - if (!a.equals(b)) { - throw new Exception("Data didn't transfer cleanly"); - } else { - log("Data transferred cleanly"); - } - - a.position(a.limit()); - b.position(b.limit()); - a.limit(a.capacity()); - b.limit(b.capacity()); - } private static void log(String str) { if (debug) { diff --git a/test/jdk/sun/security/ssl/SSLEngineImpl/RehandshakeFinished.java b/test/jdk/sun/security/ssl/SSLEngineImpl/RehandshakeFinished.java index 6967caccb99..740500f9db9 100644 --- a/test/jdk/sun/security/ssl/SSLEngineImpl/RehandshakeFinished.java +++ b/test/jdk/sun/security/ssl/SSLEngineImpl/RehandshakeFinished.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2004, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2004, 2023, Oracle and/or its affiliates. All rights reserved. * 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 @@ * @bug 6207322 * @summary SSLEngine is returning a premature FINISHED message when doing * an abbreviated handshake. + * @library /javax/net/ssl/templates * @run main/othervm RehandshakeFinished * @author Brad Wetmore */ @@ -86,11 +87,9 @@ import javax.net.ssl.*; import javax.net.ssl.SSLEngineResult.*; -import java.io.*; -import java.security.*; import java.nio.*; -public class RehandshakeFinished { +public class RehandshakeFinished extends SSLContextTemplate { /* * Enables logging of the SSLEngine operations. @@ -108,7 +107,7 @@ public class RehandshakeFinished { */ private static boolean debug = false; - static private SSLContext sslc; + private final SSLContext sslc; private SSLEngine clientEngine; // client Engine private ByteBuffer clientOut; // write side of clientEngine @@ -126,46 +125,8 @@ public class RehandshakeFinished { private ByteBuffer cTOs; // "reliable" transport client->server private ByteBuffer sTOc; // "reliable" transport server->client - /* - * The following is to set up the keystores. - */ - private static String pathToStores = "../../../../javax/net/ssl/etc"; - private static String keyStoreFile = "keystore"; - private static String trustStoreFile = "truststore"; - private static String passwd = "passphrase"; - - private static String keyFilename = - System.getProperty("test.src", "./") + "/" + pathToStores + - "/" + keyStoreFile; - private static String trustFilename = - System.getProperty("test.src", "./") + "/" + pathToStores + - "/" + trustStoreFile; - - private static Exception loadException = null; - - static { - try { - KeyStore ks = KeyStore.getInstance("JKS"); - KeyStore ts = KeyStore.getInstance("JKS"); - - char[] passphrase = "passphrase".toCharArray(); - - ks.load(new FileInputStream(keyFilename), passphrase); - ts.load(new FileInputStream(trustFilename), passphrase); - - KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); - kmf.init(ks, passphrase); - - TrustManagerFactory tmf = - TrustManagerFactory.getInstance("SunX509"); - tmf.init(ts); - - SSLContext sslCtx = SSLContext.getInstance("TLSv1.2"); - sslCtx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); - sslc = sslCtx; - } catch (Exception e) { - loadException = e; - } + public RehandshakeFinished() throws Exception { + sslc = createServerSSLContext(); } /* @@ -176,14 +137,10 @@ public static void main(String args[]) throws Exception { System.setProperty("javax.net.debug", "all"); } - if (loadException != null) { - throw loadException; - } - + RehandshakeFinished test = new RehandshakeFinished(); // Prime the session cache with a good session // Second connection should be a simple session resumption. - if ((new RehandshakeFinished().runTest()) != - new RehandshakeFinished().runRehandshake()) { + if (test.runTest() != test.runRehandshake()) { throw new Exception("Sessions not equivalent"); } @@ -412,6 +369,11 @@ private void createSSLEngines() throws Exception { clientEngine.setUseClientMode(true); } + @Override + protected ContextParameters getServerContextParameters() { + return new ContextParameters("TLSv1.2", "PKIX", "NewSunX509"); + } + /* * Create and size the buffers appropriately. */ diff --git a/test/jdk/sun/security/ssl/SSLEngineImpl/SSLEngineDeadlock.java b/test/jdk/sun/security/ssl/SSLEngineImpl/SSLEngineDeadlock.java index d61b25bd886..931830db16d 100644 --- a/test/jdk/sun/security/ssl/SSLEngineImpl/SSLEngineDeadlock.java +++ b/test/jdk/sun/security/ssl/SSLEngineImpl/SSLEngineDeadlock.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -28,6 +28,7 @@ * @test * @bug 6492872 * @summary Deadlock in SSLEngine + * @library /javax/net/ssl/templates * @run main/othervm SSLEngineDeadlock * @author Brad R. Wetmore */ @@ -70,12 +71,9 @@ import javax.net.ssl.*; import javax.net.ssl.SSLEngineResult.*; -import java.io.*; -import java.security.*; -import java.nio.*; import java.lang.management.*; -public class SSLEngineDeadlock { +public class SSLEngineDeadlock extends SSLEngineTemplate { /* * Enables logging of the SSLEngine operations. @@ -93,41 +91,8 @@ public class SSLEngineDeadlock { */ private static boolean debug = false; - private SSLContext sslc; - - private SSLEngine clientEngine; // client Engine - private ByteBuffer clientOut; // write side of clientEngine - private ByteBuffer clientIn; // read side of clientEngine - - private SSLEngine serverEngine; // server Engine - private ByteBuffer serverOut; // write side of serverEngine - private ByteBuffer serverIn; // read side of serverEngine - private volatile boolean testDone = false; - /* - * For data transport, this example uses local ByteBuffers. This - * isn't really useful, but the purpose of this example is to show - * SSLEngine concepts, not how to do network transport. - */ - private ByteBuffer cTOs; // "reliable" transport client->server - private ByteBuffer sTOc; // "reliable" transport server->client - - /* - * The following is to set up the keystores. - */ - private static String pathToStores = "../../../../javax/net/ssl/etc"; - private static String keyStoreFile = "keystore"; - private static String trustStoreFile = "truststore"; - private static String passwd = "passphrase"; - - private static String keyFilename = - System.getProperty("test.src", ".") + "/" + pathToStores + - "/" + keyStoreFile; - private static String trustFilename = - System.getProperty("test.src", ".") + "/" + pathToStores + - "/" + trustStoreFile; - /* * Main entry point for this test. */ @@ -154,26 +119,7 @@ public static void main(String args[]) throws Exception { * Create an initialized SSLContext to use for these tests. */ public SSLEngineDeadlock() throws Exception { - - KeyStore ks = KeyStore.getInstance("JKS"); - KeyStore ts = KeyStore.getInstance("JKS"); - - char[] passphrase = "passphrase".toCharArray(); - - ks.load(new FileInputStream(keyFilename), passphrase); - ts.load(new FileInputStream(trustFilename), passphrase); - - KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); - kmf.init(ks, passphrase); - - TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); - tmf.init(ts); - - SSLContext sslCtx = SSLContext.getInstance("TLS"); - - sslCtx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); - - sslc = sslCtx; + super(); } /* @@ -214,9 +160,6 @@ private void doTask() { private void runTest() throws Exception { boolean dataDone = false; - createSSLEngines(); - createBuffers(); - SSLEngineResult clientResult; // results from client's last operation SSLEngineResult serverResult; // results from server's last operation @@ -287,82 +230,10 @@ public void run() { testDone = true; } - /* - * Using the SSLContext created during object creation, - * create/configure the SSLEngines we'll use for this test. - */ - private void createSSLEngines() throws Exception { - /* - * Configure the serverEngine to act as a server in the SSL/TLS - * handshake. Also, require SSL client authentication. - */ - serverEngine = sslc.createSSLEngine(); - serverEngine.setUseClientMode(false); - serverEngine.setNeedClientAuth(true); - - /* - * Similar to above, but using client mode instead. - */ - clientEngine = sslc.createSSLEngine("client", 80); - clientEngine.setUseClientMode(true); - } - - /* - * Create and size the buffers appropriately. - */ - private void createBuffers() { - - /* - * We'll assume the buffer sizes are the same - * between client and server. - */ - SSLSession session = clientEngine.getSession(); - int appBufferMax = session.getApplicationBufferSize(); - int netBufferMax = session.getPacketBufferSize(); - - /* - * We'll make the input buffers a bit bigger than the max needed - * size, so that unwrap()s following a successful data transfer - * won't generate BUFFER_OVERFLOWS. - * - * We'll use a mix of direct and indirect ByteBuffers for - * tutorial purposes only. In reality, only use direct - * ByteBuffers when they give a clear performance enhancement. - */ - clientIn = ByteBuffer.allocate(appBufferMax + 50); - serverIn = ByteBuffer.allocate(appBufferMax + 50); - - cTOs = ByteBuffer.allocateDirect(netBufferMax); - sTOc = ByteBuffer.allocateDirect(netBufferMax); - - clientOut = ByteBuffer.wrap("Hi Server, I'm Client".getBytes()); - serverOut = ByteBuffer.wrap("Hello Client, I'm Server".getBytes()); - } - private static boolean isEngineClosed(SSLEngine engine) { return (engine.isOutboundDone() && engine.isInboundDone()); } - /* - * Simple check to make sure everything came across as expected. - */ - private static void checkTransfer(ByteBuffer a, ByteBuffer b) - throws Exception { - a.flip(); - b.flip(); - - if (!a.equals(b)) { - throw new Exception("Data didn't transfer cleanly"); - } else { - log("\tData transferred cleanly"); - } - - a.position(a.limit()); - b.position(b.limit()); - a.limit(a.capacity()); - b.limit(b.capacity()); - } - /* * Detect dead lock */ diff --git a/test/jdk/sun/security/ssl/SSLEngineImpl/SSLEngineFailedALPN.java b/test/jdk/sun/security/ssl/SSLEngineImpl/SSLEngineFailedALPN.java index 0b5a2c3d054..90a6e2525d0 100644 --- a/test/jdk/sun/security/ssl/SSLEngineImpl/SSLEngineFailedALPN.java +++ b/test/jdk/sun/security/ssl/SSLEngineImpl/SSLEngineFailedALPN.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -29,6 +29,7 @@ * @bug 8207317 * @summary SSLEngine negotiation fail Exception behavior changed from * fail-fast to fail-lazy + * @library /javax/net/ssl/templates * @run main/othervm SSLEngineFailedALPN */ /** @@ -68,11 +69,8 @@ */ import javax.net.ssl.*; import javax.net.ssl.SSLEngineResult.*; -import java.io.*; -import java.security.*; -import java.nio.*; -public class SSLEngineFailedALPN { +public class SSLEngineFailedALPN extends SSLEngineTemplate { /* * Enables logging of the SSLEngine operations. @@ -90,39 +88,6 @@ public class SSLEngineFailedALPN { */ private static final boolean debug = false; - private final SSLContext sslc; - - private SSLEngine clientEngine; // client Engine - private ByteBuffer clientOut; // write side of clientEngine - private ByteBuffer clientIn; // read side of clientEngine - - private SSLEngine serverEngine; // server Engine - private ByteBuffer serverOut; // write side of serverEngine - private ByteBuffer serverIn; // read side of serverEngine - - /* - * For data transport, this example uses local ByteBuffers. This - * isn't really useful, but the purpose of this example is to show - * SSLEngine concepts, not how to do network transport. - */ - private ByteBuffer cTOs; // "reliable" transport client->server - private ByteBuffer sTOc; // "reliable" transport server->client - - /* - * The following is to set up the keystores. - */ - private static final String pathToStores = "../../../../javax/net/ssl/etc"; - private static final String keyStoreFile = "keystore"; - private static final String trustStoreFile = "truststore"; - private static final char[] passphrase = "passphrase".toCharArray(); - - private static final String keyFilename = - System.getProperty("test.src", ".") + "/" + pathToStores + - "/" + keyStoreFile; - private static final String trustFilename = - System.getProperty("test.src", ".") + "/" + pathToStores + - "/" + trustStoreFile; - /* * Main entry point for this test. */ @@ -141,24 +106,7 @@ public static void main(String args[]) throws Exception { * Create an initialized SSLContext to use for these tests. */ public SSLEngineFailedALPN() throws Exception { - - KeyStore ks = KeyStore.getInstance("JKS"); - KeyStore ts = KeyStore.getInstance("JKS"); - - ks.load(new FileInputStream(keyFilename), passphrase); - ts.load(new FileInputStream(trustFilename), passphrase); - - KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); - kmf.init(ks, passphrase); - - TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); - tmf.init(ts); - - SSLContext sslCtx = SSLContext.getInstance("TLS"); - - sslCtx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); - - sslc = sslCtx; + super(); } /* @@ -181,9 +129,6 @@ public SSLEngineFailedALPN() throws Exception { private void runTest() throws Exception { boolean dataDone = false; - createSSLEngines(); - createBuffers(); - // results from client's last operation SSLEngineResult clientResult; @@ -309,113 +254,33 @@ private static void logEngineStatus(SSLEngine engine) { log("\tisOutboundDone(): " + engine.isOutboundDone()); } - /* - * Using the SSLContext created during object creation, - * create/configure the SSLEngines we'll use for this test. - */ - private void createSSLEngines() throws Exception { - /* - * Configure the serverEngine to act as a server in the SSL/TLS - * handshake. Also, require SSL client authentication. - */ - serverEngine = sslc.createSSLEngine(); - serverEngine.setUseClientMode(false); - serverEngine.setNeedClientAuth(true); + @Override + protected SSLEngine configureServerEngine(SSLEngine engine) { + engine.setUseClientMode(false); + engine.setNeedClientAuth(true); // Get/set parameters if needed - SSLParameters paramsServer = serverEngine.getSSLParameters(); + SSLParameters paramsServer = engine.getSSLParameters(); paramsServer.setApplicationProtocols(new String[]{"one"}); - serverEngine.setSSLParameters(paramsServer); + engine.setSSLParameters(paramsServer); + return engine; + } - /* - * Similar to above, but using client mode instead. - */ - clientEngine = sslc.createSSLEngine("client", 80); - clientEngine.setUseClientMode(true); + @Override + protected SSLEngine configureClientEngine(SSLEngine engine) { + engine.setUseClientMode(true); // Get/set parameters if needed - SSLParameters paramsClient = clientEngine.getSSLParameters(); + SSLParameters paramsClient = engine.getSSLParameters(); paramsClient.setApplicationProtocols(new String[]{"two"}); - clientEngine.setSSLParameters(paramsClient); - } - - /* - * Create and size the buffers appropriately. - */ - private void createBuffers() { - - /* - * We'll assume the buffer sizes are the same - * between client and server. - */ - SSLSession session = clientEngine.getSession(); - int appBufferMax = session.getApplicationBufferSize(); - int netBufferMax = session.getPacketBufferSize(); - - /* - * We'll make the input buffers a bit bigger than the max needed - * size, so that unwrap()s following a successful data transfer - * won't generate BUFFER_OVERFLOWS. - * - * We'll use a mix of direct and indirect ByteBuffers for - * tutorial purposes only. In reality, only use direct - * ByteBuffers when they give a clear performance enhancement. - */ - clientIn = ByteBuffer.allocate(appBufferMax + 50); - serverIn = ByteBuffer.allocate(appBufferMax + 50); - - cTOs = ByteBuffer.allocateDirect(netBufferMax); - sTOc = ByteBuffer.allocateDirect(netBufferMax); - - clientOut = ByteBuffer.wrap("Hi Server, I'm Client".getBytes()); - serverOut = ByteBuffer.wrap("Hello Client, I'm Server".getBytes()); - } - - /* - * If the result indicates that we have outstanding tasks to do, - * go ahead and run them in this thread. - */ - private static void runDelegatedTasks(SSLEngine engine) throws Exception { - - if (engine.getHandshakeStatus() == HandshakeStatus.NEED_TASK) { - Runnable runnable; - while ((runnable = engine.getDelegatedTask()) != null) { - log(" running delegated task..."); - runnable.run(); - } - HandshakeStatus hsStatus = engine.getHandshakeStatus(); - if (hsStatus == HandshakeStatus.NEED_TASK) { - throw new Exception( - "handshake shouldn't need additional tasks"); - } - logEngineStatus(engine); - } + engine.setSSLParameters(paramsClient); + return engine; } private static boolean isEngineClosed(SSLEngine engine) { return (engine.isOutboundDone() && engine.isInboundDone()); } - /* - * Simple check to make sure everything came across as expected. - */ - private static void checkTransfer(ByteBuffer a, ByteBuffer b) - throws Exception { - a.flip(); - b.flip(); - - if (!a.equals(b)) { - throw new Exception("Data didn't transfer cleanly"); - } else { - log("\tData transferred cleanly"); - } - - a.position(a.limit()); - b.position(b.limit()); - a.limit(a.capacity()); - b.limit(b.capacity()); - } - /* * Logging code */ diff --git a/test/jdk/sun/security/ssl/SSLEngineImpl/SSLEngineKeyLimit.java b/test/jdk/sun/security/ssl/SSLEngineImpl/SSLEngineKeyLimit.java index 58c3c4a0d3b..d6ec20c93d2 100644 --- a/test/jdk/sun/security/ssl/SSLEngineImpl/SSLEngineKeyLimit.java +++ b/test/jdk/sun/security/ssl/SSLEngineImpl/SSLEngineKeyLimit.java @@ -25,7 +25,8 @@ * @test * @bug 8164879 8300285 * @library ../../ - * @library /test/lib + * /test/lib + * /javax/net/ssl/templates * @summary Verify AEAD TLS cipher suite limits set in the jdk.tls.keyLimits * property * start a new handshake sequence to renegotiate the symmetric key with an @@ -49,23 +50,19 @@ * success. */ -import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLEngineResult; -import javax.net.ssl.TrustManagerFactory; import java.io.File; import java.io.PrintWriter; import java.nio.ByteBuffer; -import java.security.KeyStore; -import java.security.SecureRandom; import java.util.Arrays; import jdk.test.lib.process.ProcessTools; import jdk.test.lib.process.OutputAnalyzer; import jdk.test.lib.Utils; -public class SSLEngineKeyLimit { +public class SSLEngineKeyLimit extends SSLContextTemplate { SSLEngine eng; static ByteBuffer cTos; @@ -73,11 +70,6 @@ public class SSLEngineKeyLimit { static ByteBuffer outdata; ByteBuffer buf; static boolean ready = false; - - static String pathToStores = "../../../../javax/net/ssl/etc/"; - static String keyStoreFile = "keystore"; - static String passwd = "passphrase"; - static String keyFilename; static int dataLen = 10240; static boolean serverwrite = true; int totalDataLen = 0; @@ -126,7 +118,7 @@ public static void main(String args[]) throws Exception { System.out.println("test.java.opts: " + System.getProperty("test.java.opts")); - ProcessBuilder pb = ProcessTools.createTestJvm( + ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder( Utils.addTestJavaOpts("SSLEngineKeyLimit", "p", args[1], args[2])); @@ -164,13 +156,6 @@ public static void main(String args[]) throws Exception { } cTos = ByteBuffer.allocateDirect(dataLen*4); - keyFilename = - System.getProperty("test.src", "./") + "/" + pathToStores + - "/" + keyStoreFile; - - System.setProperty("javax.net.ssl.keyStore", keyFilename); - System.setProperty("javax.net.ssl.keyStorePassword", passwd); - sToc = ByteBuffer.allocateDirect(dataLen*4); outdata = ByteBuffer.allocateDirect(dataLen); @@ -412,19 +397,12 @@ ByteBuffer getWriteBuf() { SSLContext initContext() throws Exception { - SSLContext sc = SSLContext.getInstance("TLSv1.3"); - KeyStore ks = KeyStore.getInstance( - new File(System.getProperty("javax.net.ssl.keyStore")), - passwd.toCharArray()); - KeyManagerFactory kmf = KeyManagerFactory.getInstance( - KeyManagerFactory.getDefaultAlgorithm()); - kmf.init(ks, passwd.toCharArray()); - TrustManagerFactory tmf = TrustManagerFactory.getInstance( - TrustManagerFactory.getDefaultAlgorithm()); - tmf.init(ks); - sc.init(kmf.getKeyManagers(), - tmf.getTrustManagers(), new SecureRandom()); - return sc; + return createServerSSLContext(); + } + + @Override + protected ContextParameters getServerContextParameters() { + return new ContextParameters("TLSv1.3", "PKIX", "NewSunX509"); } static class Server extends SSLEngineKeyLimit implements Runnable { diff --git a/test/jdk/sun/security/ssl/SSLEngineImpl/TLS13BeginHandshake.java b/test/jdk/sun/security/ssl/SSLEngineImpl/TLS13BeginHandshake.java index 7c2b9f723b1..e5409be8d02 100644 --- a/test/jdk/sun/security/ssl/SSLEngineImpl/TLS13BeginHandshake.java +++ b/test/jdk/sun/security/ssl/SSLEngineImpl/TLS13BeginHandshake.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2023, Oracle and/or its affiliates. All rights reserved. * 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,52 +25,36 @@ * @test * @summary Test SSLEngine.begineHandshake() triggers a KeyUpdate handshake * in TLSv1.3 + * @library /javax/net/ssl/templates * @run main/othervm TLS13BeginHandshake */ -import javax.net.ssl.KeyManagerFactory; -import javax.net.ssl.SSLContext; import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLEngineResult; -import javax.net.ssl.SSLEngineResult.HandshakeStatus; -import javax.net.ssl.SSLSession; -import javax.net.ssl.TrustManagerFactory; -import java.io.File; -import java.nio.ByteBuffer; -import java.security.KeyStore; -import java.security.SecureRandom; - -public class TLS13BeginHandshake { - static String pathToStores = - System.getProperty("test.src") + "/../../../../javax/net/ssl/etc/"; - static String keyStoreFile = "keystore"; - static String passwd = "passphrase"; - - private SSLEngine serverEngine, clientEngine; + +public class TLS13BeginHandshake extends SSLEngineTemplate { SSLEngineResult clientResult, serverResult; - private ByteBuffer clientOut, clientIn; - private ByteBuffer serverOut, serverIn; - private ByteBuffer cTOs,sTOc; public static void main(String args[]) throws Exception{ new TLS13BeginHandshake().runDemo(); } + public TLS13BeginHandshake() throws Exception { + super(); + } + private void runDemo() throws Exception { int done = 0; - createSSLEngines(); - createBuffers(); - while (!isEngineClosed(clientEngine) || !isEngineClosed(serverEngine)) { System.out.println("================"); clientResult = clientEngine.wrap(clientOut, cTOs); System.out.println("client wrap: " + clientResult); - runDelegatedTasks(clientResult, clientEngine); + runDelegatedTasks(clientEngine); serverResult = serverEngine.wrap(serverOut, sTOc); System.out.println("server wrap: " + serverResult); - runDelegatedTasks(serverResult, serverEngine); + runDelegatedTasks(serverEngine); cTOs.flip(); sTOc.flip(); @@ -80,10 +64,11 @@ private void runDemo() throws Exception { System.out.println("client unwrap: " + clientResult); if (clientResult.getStatus() == SSLEngineResult.Status.CLOSED) { break; - } runDelegatedTasks(clientResult, clientEngine); + } + runDelegatedTasks(clientEngine); serverResult = serverEngine.unwrap(cTOs, serverIn); System.out.println("server unwrap: " + serverResult); - runDelegatedTasks(serverResult, serverEngine); + runDelegatedTasks(serverEngine); cTOs.compact(); sTOc.compact(); @@ -121,71 +106,13 @@ private static boolean isEngineClosed(SSLEngine engine) { return (engine.isOutboundDone() && engine.isInboundDone()); } - private static void checkTransfer(ByteBuffer a, ByteBuffer b) - throws Exception { - a.flip(); - b.flip(); - - if (!a.equals(b)) { - throw new Exception("Data didn't transfer cleanly"); - } else { - System.out.println("\tData transferred cleanly"); - } - - a.compact(); - b.compact(); - - } - private void createBuffers() { - SSLSession session = clientEngine.getSession(); - int appBufferMax = session.getApplicationBufferSize(); - int netBufferMax = session.getPacketBufferSize(); - - clientIn = ByteBuffer.allocate(appBufferMax + 50); - serverIn = ByteBuffer.allocate(appBufferMax + 50); - - cTOs = ByteBuffer.allocateDirect(netBufferMax); - sTOc = ByteBuffer.allocateDirect(netBufferMax); - - clientOut = ByteBuffer.wrap("client".getBytes()); - serverOut = ByteBuffer.wrap("server".getBytes()); - } - - private void createSSLEngines() throws Exception { - serverEngine = initContext().createSSLEngine(); - serverEngine.setUseClientMode(false); - serverEngine.setNeedClientAuth(true); - - clientEngine = initContext().createSSLEngine("client", 80); - clientEngine.setUseClientMode(true); + @Override + protected ContextParameters getServerContextParameters() { + return new ContextParameters("TLSv1.3", "PKIX", "NewSunX509"); } - private SSLContext initContext() throws Exception { - SSLContext sc = SSLContext.getInstance("TLSv1.3"); - KeyStore ks = KeyStore.getInstance(new File(pathToStores + keyStoreFile), - passwd.toCharArray()); - KeyManagerFactory kmf = - KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); - kmf.init(ks, passwd.toCharArray()); - TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); - tmf.init(ks); - sc.init(kmf.getKeyManagers(), tmf.getTrustManagers(), new SecureRandom()); - return sc; - } - - private static void runDelegatedTasks(SSLEngineResult result, - SSLEngine engine) throws Exception { - - if (result.getHandshakeStatus() == HandshakeStatus.NEED_TASK) { - Runnable runnable; - while ((runnable = engine.getDelegatedTask()) != null) { - runnable.run(); - } - HandshakeStatus hsStatus = engine.getHandshakeStatus(); - if (hsStatus == HandshakeStatus.NEED_TASK) { - throw new Exception( - "handshake shouldn't need additional tasks"); - } - } + @Override + protected ContextParameters getClientContextParameters() { + return new ContextParameters("TLSv1.3", "PKIX", "NewSunX509"); } } diff --git a/test/jdk/sun/security/ssl/SSLSessionImpl/HashCodeMissing.java b/test/jdk/sun/security/ssl/SSLSessionImpl/HashCodeMissing.java index 61f0c6cb477..43ec90d8f8e 100644 --- a/test/jdk/sun/security/ssl/SSLSessionImpl/HashCodeMissing.java +++ b/test/jdk/sun/security/ssl/SSLSessionImpl/HashCodeMissing.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2023, Oracle and/or its affiliates. All rights reserved. * 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,6 +25,7 @@ * @test * @bug 4910892 * @summary 4518403 was not properly fixed. hashcode should be hashCode. + * @library /javax/net/ssl/templates * @run main/othervm HashCodeMissing * * SunJSSE does not support dynamic system properties, no way to re-use @@ -33,72 +34,19 @@ */ import java.io.*; -import java.net.*; import javax.net.ssl.*; import java.lang.reflect.*; -public class HashCodeMissing { - - /* - * ============================================================= - * Set the various variables needed for the tests, then - * specify what tests to run on each side. - */ - - /* - * Should we run the client or server in a separate thread? - * Both sides can throw exceptions, but do you have a preference - * as to which side should be the main thread. - */ - static boolean separateServerThread = false; - - /* - * Where do we find the keystores? - */ - static String pathToStores = "../../../../javax/net/ssl/etc"; - static String keyStoreFile = "keystore"; - static String trustStoreFile = "truststore"; - static String passwd = "passphrase"; - - /* - * Is the server ready to serve? - */ - volatile static boolean serverReady = false; +public class HashCodeMissing extends SSLSocketTemplate { /* * Turn on SSL debugging? */ static boolean debug = false; - /* - * If the client or server is doing some kind of object creation - * that the other side depends on, and that thread prematurely - * exits, you may experience a hang. The test harness will - * terminate all hung threads after its timeout has expired, - * currently 3 minutes by default, but you might try to be - * smart about it.... - */ - /* - * Define the server side of the test. - * - * If the server prematurely exits, serverReady will be set to true - * to avoid infinite hangs. - */ - void doServerSide() throws Exception { - SSLServerSocketFactory sslssf = - (SSLServerSocketFactory) SSLServerSocketFactory.getDefault(); - SSLServerSocket sslServerSocket = - (SSLServerSocket) sslssf.createServerSocket(serverPort); - - serverPort = sslServerSocket.getLocalPort(); - - /* - * Signal Client, we're ready for his connect. - */ - serverReady = true; - - SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept(); + @Override + protected void runServerApplication(SSLSocket sslSocket) throws Exception { InputStream sslIS = sslSocket.getInputStream(); OutputStream sslOS = sslSocket.getOutputStream(); @@ -106,28 +54,10 @@ void doServerSide() throws Exception { sslOS.write(85); sslOS.flush(); - sslSocket.close(); } - /* - * Define the client side of the test. - * - * If the server prematurely exits, serverReady will be set to true - * to avoid infinite hangs. - */ - void doClientSide() throws Exception { - - /* - * Wait for server to get started. - */ - while (!serverReady) { - Thread.sleep(50); - } - - SSLSocketFactory sslsf = - (SSLSocketFactory) SSLSocketFactory.getDefault(); - SSLSocket sslSocket = (SSLSocket) - sslsf.createSocket("localhost", serverPort); + @Override + protected void runClientApplication(SSLSocket sslSocket) throws Exception { InputStream sslIS = sslSocket.getInputStream(); OutputStream sslOS = sslSocket.getOutputStream(); @@ -150,29 +80,7 @@ void doClientSide() throws Exception { System.out.println("Method = " + method); } - /* - * ============================================================= - * The remainder is just support stuff - */ - - // use any free port by default - volatile int serverPort = 0; - - volatile Exception serverException = null; - volatile Exception clientException = null; - public static void main(String[] args) throws Exception { - String keyFilename = - System.getProperty("test.src", "./") + "/" + pathToStores + - "/" + keyStoreFile; - String trustFilename = - System.getProperty("test.src", "./") + "/" + pathToStores + - "/" + trustStoreFile; - - System.setProperty("javax.net.ssl.keyStore", keyFilename); - System.setProperty("javax.net.ssl.keyStorePassword", passwd); - System.setProperty("javax.net.ssl.trustStore", trustFilename); - System.setProperty("javax.net.ssl.trustStorePassword", passwd); if (debug) System.setProperty("javax.net.debug", "all"); @@ -180,129 +88,7 @@ public static void main(String[] args) throws Exception { /* * Start the tests. */ - new HashCodeMissing(); + new HashCodeMissing().run(); } - Thread clientThread = null; - Thread serverThread = null; - - /* - * Primary constructor, used to drive remainder of the test. - * - * Fork off the other side, then do your work. - */ - HashCodeMissing() throws Exception { - try { - if (separateServerThread) { - startServer(true); - startClient(false); - } else { - startClient(true); - startServer(false); - } - } catch (Exception e) { - //swallow for now. Show later - } - - /* - * Wait for other side to close down. - */ - if (separateServerThread) { - serverThread.join(); - } else { - clientThread.join(); - } - - /* - * When we get here, the test is pretty much over. - * Which side threw the error? - */ - Exception local; - Exception remote; - String whichRemote; - - if (separateServerThread) { - remote = serverException; - local = clientException; - whichRemote = "server"; - } else { - remote = clientException; - local = serverException; - whichRemote = "client"; - } - - /* - * If both failed, return the curthread's exception, but also - * print the remote side Exception - */ - if ((local != null) && (remote != null)) { - System.out.println(whichRemote + " also threw:"); - remote.printStackTrace(); - System.out.println(); - throw local; - } - - if (remote != null) { - throw remote; - } - - if (local != null) { - throw local; - } - } - - void startServer(boolean newThread) throws Exception { - if (newThread) { - serverThread = new Thread() { - public void run() { - try { - doServerSide(); - } catch (Exception e) { - /* - * Our server thread just died. - * - * Release the client, if not active already... - */ - System.err.println("Server died..."); - serverReady = true; - serverException = e; - } - } - }; - serverThread.start(); - } else { - try { - doServerSide(); - } catch (Exception e) { - serverException = e; - } finally { - serverReady = true; - } - } - } - - void startClient(boolean newThread) throws Exception { - if (newThread) { - clientThread = new Thread() { - public void run() { - try { - doClientSide(); - } catch (Exception e) { - /* - * Our client thread just died. - */ - System.err.println("Client died..."); - clientException = e; - } - } - }; - clientThread.start(); - } else { - try { - doClientSide(); - } catch (Exception e) { - clientException = e; - } - } - } } diff --git a/test/jdk/sun/security/ssl/SSLSessionImpl/ResumeChecksClient.java b/test/jdk/sun/security/ssl/SSLSessionImpl/ResumeChecksClient.java index 90939b5862a..e2885e38779 100644 --- a/test/jdk/sun/security/ssl/SSLSessionImpl/ResumeChecksClient.java +++ b/test/jdk/sun/security/ssl/SSLSessionImpl/ResumeChecksClient.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,6 +26,7 @@ * @bug 8206929 8212885 * @summary ensure that client only resumes a session if certain properties * of the session are compatible with the new connection + * @library /javax/net/ssl/templates * @run main/othervm -Djdk.tls.client.protocols=TLSv1.2 -Djdk.tls.server.enableSessionTicketExtension=false -Djdk.tls.client.enableSessionTicketExtension=false ResumeChecksClient BASIC * @run main/othervm -Djdk.tls.client.protocols=TLSv1.2 -Djdk.tls.server.enableSessionTicketExtension=true -Djdk.tls.client.enableSessionTicketExtension=false ResumeChecksClient BASIC * @run main/othervm -Djdk.tls.client.protocols=TLSv1.2 -Djdk.tls.server.enableSessionTicketExtension=true -Djdk.tls.client.enableSessionTicketExtension=true ResumeChecksClient BASIC @@ -47,13 +48,7 @@ import java.net.*; import java.util.*; -public class ResumeChecksClient { - - static String pathToStores = "../../../../javax/net/ssl/etc"; - static String keyStoreFile = "keystore"; - static String trustStoreFile = "truststore"; - static String passwd = "passphrase"; - +public class ResumeChecksClient extends SSLContextTemplate { enum TestMode { BASIC, VERSION_2_TO_3, @@ -63,38 +58,32 @@ enum TestMode { } public static void main(String[] args) throws Exception { + new ResumeChecksClient(TestMode.valueOf(args[0])).run(); + } - TestMode mode = TestMode.valueOf(args[0]); - - String keyFilename = - System.getProperty("test.src", "./") + "/" + pathToStores + - "/" + keyStoreFile; - String trustFilename = - System.getProperty("test.src", "./") + "/" + pathToStores + - "/" + trustStoreFile; - - System.setProperty("javax.net.ssl.keyStore", keyFilename); - System.setProperty("javax.net.ssl.keyStorePassword", passwd); - System.setProperty("javax.net.ssl.trustStore", trustFilename); - System.setProperty("javax.net.ssl.trustStorePassword", passwd); + private final TestMode testMode; + public ResumeChecksClient(TestMode mode) { + this.testMode = mode; + } + private void run() throws Exception { Server server = startServer(); server.signal(); - SSLContext sslContext = SSLContext.getDefault(); + SSLContext sslContext = createClientSSLContext(); while (!server.started) { Thread.yield(); } - SSLSession firstSession = connect(sslContext, server.port, mode, false); + SSLSession firstSession = connect(sslContext, server.port, testMode, false); server.signal(); long secondStartTime = System.currentTimeMillis(); Thread.sleep(10); - SSLSession secondSession = connect(sslContext, server.port, mode, true); + SSLSession secondSession = connect(sslContext, server.port, testMode, true); server.go = false; server.signal(); - switch (mode) { + switch (testMode) { case BASIC: // fail if session is not resumed checkResumedSession(firstSession, secondSession); @@ -109,7 +98,7 @@ public static void main(String[] args) throws Exception { } break; default: - throw new RuntimeException("unknown mode: " + mode); + throw new RuntimeException("unknown mode: " + testMode); } } @@ -291,7 +280,7 @@ private static Server startServer() { return server; } - private static class Server implements Runnable { + private static class Server extends SSLContextTemplate implements Runnable { public volatile boolean go = true; private boolean signal = false; @@ -317,7 +306,7 @@ public synchronized void signal() { public void run() { try { - SSLContext sc = SSLContext.getDefault(); + SSLContext sc = createServerSSLContext(); ServerSocketFactory fac = sc.getServerSocketFactory(); SSLServerSocket ssock = (SSLServerSocket) fac.createServerSocket(0); diff --git a/test/jdk/sun/security/ssl/SSLSessionImpl/ResumeChecksClientStateless.java b/test/jdk/sun/security/ssl/SSLSessionImpl/ResumeChecksClientStateless.java index b428a12d478..06829d2c96e 100644 --- a/test/jdk/sun/security/ssl/SSLSessionImpl/ResumeChecksClientStateless.java +++ b/test/jdk/sun/security/ssl/SSLSessionImpl/ResumeChecksClientStateless.java @@ -26,6 +26,7 @@ * @bug 8211018 * @summary ensure that client only resumes a session if certain properties * of the session are compatible with the new connection + * @library /javax/net/ssl/templates * @run main/othervm -Djdk.tls.client.protocols=TLSv1.2 -Djdk.tls.server.enableSessionTicketExtension=false -Djdk.tls.client.enableSessionTicketExtension=false ResumeChecksClient BASIC * @run main/othervm -Djdk.tls.client.protocols=TLSv1.2 -Djdk.tls.server.enableSessionTicketExtension=true -Djdk.tls.client.enableSessionTicketExtension=false ResumeChecksClient BASIC * @run main/othervm -Djdk.tls.client.protocols=TLSv1.2 -Djdk.tls.server.enableSessionTicketExtension=true -Djdk.tls.client.enableSessionTicketExtension=true ResumeChecksClient BASIC diff --git a/test/jdk/sun/security/ssl/SSLSessionImpl/ResumeChecksServer.java b/test/jdk/sun/security/ssl/SSLSessionImpl/ResumeChecksServer.java index 2ee859d2799..0d5413d1fa2 100644 --- a/test/jdk/sun/security/ssl/SSLSessionImpl/ResumeChecksServer.java +++ b/test/jdk/sun/security/ssl/SSLSessionImpl/ResumeChecksServer.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,6 +26,7 @@ * @bug 8206929 * @summary ensure that server only resumes a session if certain properties * of the session are compatible with the new connection + * @library /javax/net/ssl/templates * @run main/othervm -Djdk.tls.client.protocols=TLSv1.2 -Djdk.tls.server.enableSessionTicketExtension=false -Djdk.tls.client.enableSessionTicketExtension=false ResumeChecksServer BASIC * @run main/othervm -Djdk.tls.client.protocols=TLSv1.2 -Djdk.tls.server.enableSessionTicketExtension=true -Djdk.tls.client.enableSessionTicketExtension=false ResumeChecksServer BASIC * @run main/othervm -Djdk.tls.client.protocols=TLSv1.2 -Djdk.tls.server.enableSessionTicketExtension=true -Djdk.tls.client.enableSessionTicketExtension=true ResumeChecksServer BASIC @@ -48,12 +49,7 @@ import java.net.*; import java.util.*; -public class ResumeChecksServer { - - static String pathToStores = "../../../../javax/net/ssl/etc"; - static String keyStoreFile = "keystore"; - static String trustStoreFile = "truststore"; - static String passwd = "passphrase"; +public class ResumeChecksServer extends SSLContextTemplate { enum TestMode { BASIC, @@ -66,23 +62,18 @@ enum TestMode { public static void main(String[] args) throws Exception { - TestMode mode = TestMode.valueOf(args[0]); - - String keyFilename = - System.getProperty("test.src", "./") + "/" + pathToStores + - "/" + keyStoreFile; - String trustFilename = - System.getProperty("test.src", "./") + "/" + pathToStores + - "/" + trustStoreFile; + new ResumeChecksServer(TestMode.valueOf(args[0])).run(); + } + private final TestMode testMode; - System.setProperty("javax.net.ssl.keyStore", keyFilename); - System.setProperty("javax.net.ssl.keyStorePassword", passwd); - System.setProperty("javax.net.ssl.trustStore", trustFilename); - System.setProperty("javax.net.ssl.trustStorePassword", passwd); + public ResumeChecksServer(TestMode testMode) { + this.testMode = testMode; + } + private void run() throws Exception { SSLSession secondSession = null; - SSLContext sslContext = SSLContext.getDefault(); + SSLContext sslContext = createServerSSLContext(); ServerSocketFactory fac = sslContext.getServerSocketFactory(); SSLServerSocket ssock = (SSLServerSocket) fac.createServerSocket(0); @@ -90,7 +81,7 @@ public static void main(String[] args) throws Exception { Client client = startClient(ssock.getLocalPort()); try { - connect(client, ssock, mode, false); + connect(client, ssock, testMode, false); } catch (Exception ex) { throw new RuntimeException(ex); } @@ -98,7 +89,7 @@ public static void main(String[] args) throws Exception { long secondStartTime = System.currentTimeMillis(); Thread.sleep(10); try { - secondSession = connect(client, ssock, mode, true); + secondSession = connect(client, ssock, testMode, true); } catch (SSLHandshakeException ex) { // this is expected } catch (Exception ex) { @@ -108,7 +99,7 @@ public static void main(String[] args) throws Exception { client.go = false; client.signal(); - switch (mode) { + switch (testMode) { case BASIC: // fail if session is not resumed if (secondSession.getCreationTime() > secondStartTime) { @@ -129,7 +120,7 @@ public static void main(String[] args) throws Exception { } break; default: - throw new RuntimeException("unknown mode: " + mode); + throw new RuntimeException("unknown mode: " + testMode); } } @@ -244,7 +235,7 @@ private static Client startClient(int port) { return client; } - private static class Client implements Runnable { + private static class Client extends SSLContextTemplate implements Runnable { public volatile boolean go = true; private boolean signal = false; @@ -278,7 +269,7 @@ public synchronized void signal() { public void run() { try { - SSLContext sc = SSLContext.getDefault(); + SSLContext sc = createClientSSLContext(); waitForSignal(); while (go) { diff --git a/test/jdk/sun/security/ssl/SSLSessionImpl/ResumeChecksServerStateless.java b/test/jdk/sun/security/ssl/SSLSessionImpl/ResumeChecksServerStateless.java index 32041114f9c..8071bb1ced8 100644 --- a/test/jdk/sun/security/ssl/SSLSessionImpl/ResumeChecksServerStateless.java +++ b/test/jdk/sun/security/ssl/SSLSessionImpl/ResumeChecksServerStateless.java @@ -26,6 +26,7 @@ * @bug 8211018 * @summary ensure that server only resumes a session if certain properties * of the session are compatible with the new connection + * @library /javax/net/ssl/templates * @run main/othervm -Djdk.tls.client.protocols=TLSv1.3 ResumeChecksServer BASIC * @run main/othervm -Djdk.tls.client.protocols=TLSv1.3 ResumeChecksServer CLIENT_AUTH * @run main/othervm ResumeChecksServer VERSION_2_TO_3 diff --git a/test/jdk/sun/security/ssl/SSLSessionImpl/ResumptionUpdateBoundValues.java b/test/jdk/sun/security/ssl/SSLSessionImpl/ResumptionUpdateBoundValues.java index b9426bcfa95..ea7f4895785 100644 --- a/test/jdk/sun/security/ssl/SSLSessionImpl/ResumptionUpdateBoundValues.java +++ b/test/jdk/sun/security/ssl/SSLSessionImpl/ResumptionUpdateBoundValues.java @@ -23,7 +23,7 @@ /* * @test - * @library /test/lib + * @library /test/lib /javax/net/ssl/templates * @summary Test that a New Session Ticket will be generated when a * SSLSessionBindingListener is set (boundValues) * @run main/othervm ResumptionUpdateBoundValues @@ -47,7 +47,7 @@ import jdk.test.lib.process.ProcessTools; import jdk.test.lib.Utils; -public class ResumptionUpdateBoundValues { +public class ResumptionUpdateBoundValues extends SSLContextTemplate { static boolean separateServerThread = true; @@ -76,8 +76,7 @@ public class ResumptionUpdateBoundValues { * to avoid infinite hangs. */ void doServerSide() throws Exception { - SSLServerSocketFactory sslssf = - (SSLServerSocketFactory) SSLServerSocketFactory.getDefault(); + SSLServerSocketFactory sslssf = createServerSSLContext().getServerSocketFactory(); SSLServerSocket sslServerSocket = (SSLServerSocket) sslssf.createServerSocket(serverPort); serverPort = sslServerSocket.getLocalPort(); @@ -122,8 +121,7 @@ SBListener doClientSide() throws Exception { Thread.sleep(50); } - SSLSocketFactory sslsf = - (SSLSocketFactory) SSLSocketFactory.getDefault(); + SSLSocketFactory sslsf = createClientSSLContext().getSocketFactory(); try { SSLSocket sslSocket = (SSLSocket) @@ -189,7 +187,7 @@ public static void main(String[] args) throws Exception { System.out.println("test.java.opts: " + System.getProperty("test.java.opts")); - ProcessBuilder pb = ProcessTools.createTestJvm( + ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder( Utils.addTestJavaOpts("ResumptionUpdateBoundValues", "p")); OutputAnalyzer output = ProcessTools.executeProcess(pb); @@ -209,17 +207,6 @@ public static void main(String[] args) throws Exception { return; } - String keyFilename = - System.getProperty("test.src", "./") + "/" + pathToStores + - "/" + keyStoreFile; - String trustFilename = - System.getProperty("test.src", "./") + "/" + pathToStores + - "/" + trustStoreFile; - System.setProperty("javax.net.ssl.keyStore", keyFilename); - System.setProperty("javax.net.ssl.keyStorePassword", passwd); - System.setProperty("javax.net.ssl.trustStore", trustFilename); - System.setProperty("javax.net.ssl.trustStorePassword", passwd); - if (debug) System.setProperty("javax.net.debug", "all"); @@ -227,19 +214,14 @@ public static void main(String[] args) throws Exception { * Start the tests. */ - new ResumptionUpdateBoundValues(); + new ResumptionUpdateBoundValues().run(); } ArrayBlockingQueue threads = new ArrayBlockingQueue(100); ArrayBlockingQueue sbListeners = new ArrayBlockingQueue<>(100); - /* - * Primary constructor, used to drive remainder of the test. - * - * Fork off the other side, then do your work. - */ - ResumptionUpdateBoundValues() throws Exception { + private void run() throws Exception { final int count = 1; if (separateServerThread) { startServer(true); diff --git a/test/jdk/sun/security/ssl/SSLSocketImpl/SSLSocketKeyLimit.java b/test/jdk/sun/security/ssl/SSLSocketImpl/SSLSocketKeyLimit.java index 8b19d39af7e..f0519a94249 100644 --- a/test/jdk/sun/security/ssl/SSLSocketImpl/SSLSocketKeyLimit.java +++ b/test/jdk/sun/security/ssl/SSLSocketImpl/SSLSocketKeyLimit.java @@ -134,7 +134,7 @@ public static void main(String args[]) throws Exception { System.out.println("test.java.opts: " + System.getProperty("test.java.opts")); - ProcessBuilder pb = ProcessTools.createTestJvm( + ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder( Utils.addTestJavaOpts("SSLSocketKeyLimit", "p", args[1], args[2])); diff --git a/test/jdk/sun/security/ssl/X509TrustManagerImpl/Symantec/Distrust.java b/test/jdk/sun/security/ssl/X509TrustManagerImpl/Symantec/Distrust.java deleted file mode 100644 index ba008c68cdc..00000000000 --- a/test/jdk/sun/security/ssl/X509TrustManagerImpl/Symantec/Distrust.java +++ /dev/null @@ -1,292 +0,0 @@ -/* - * Copyright (c) 2018, 2022, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -import java.io.*; -import java.math.BigInteger; -import java.security.*; -import java.security.cert.*; -import java.time.*; -import java.util.*; -import javax.net.ssl.*; -import sun.security.validator.Validator; -import sun.security.validator.ValidatorException; - -import jdk.test.lib.security.SecurityUtils; - -/** - * @test - * @bug 8207258 8216280 - * @summary Check that TLS Server certificates chaining back to distrusted - * Symantec roots are invalid - * @library /test/lib - * @modules java.base/sun.security.validator - * @run main/othervm Distrust after policyOn invalid - * @run main/othervm Distrust after policyOff valid - * @run main/othervm Distrust before policyOn valid - * @run main/othervm Distrust before policyOff valid - */ - -public class Distrust { - - private static final String TEST_SRC = System.getProperty("test.src", "."); - private static CertificateFactory cf; - - // Each of the roots have a test certificate chain stored in a file - // named "-chain.pem". - private static String[] rootsToTest = new String[] { - "geotrustprimarycag2", "geotrustprimarycag3", - "geotrustuniversalca", "thawteprimaryrootca", "thawteprimaryrootcag2", - "thawteprimaryrootcag3", "verisignclass3g3ca", "verisignclass3g4ca", - "verisignclass3g5ca", "verisignuniversalrootca" }; - - // Each of the subCAs with a delayed distrust date have a test certificate - // chain stored in a file named "-chain.pem". - private static String[] subCAsToTest = new String[]{"appleistca8g1"}; - - // A date that is after the restrictions take affect - private static final Date APRIL_17_2019 = - Date.from(LocalDate.of(2019, 4, 17) - .atStartOfDay(ZoneOffset.UTC) - .toInstant()); - - // A date that is a second before the restrictions take affect - private static final Date BEFORE_APRIL_17_2019 = - Date.from(LocalDate.of(2019, 4, 17) - .atStartOfDay(ZoneOffset.UTC) - .minusSeconds(1) - .toInstant()); - - // A date that is after the subCA restrictions take affect - private static final Date JANUARY_1_2020 = - Date.from(LocalDate.of(2020, 1, 1) - .atStartOfDay(ZoneOffset.UTC) - .toInstant()); - - // A date that is a second before the subCA restrictions take affect - private static final Date BEFORE_JANUARY_1_2020 = - Date.from(LocalDate.of(2020, 1, 1) - .atStartOfDay(ZoneOffset.UTC) - .minusSeconds(1) - .toInstant()); - - public static void main(String[] args) throws Exception { - - cf = CertificateFactory.getInstance("X.509"); - - boolean before = args[0].equals("before"); - boolean policyOn = args[1].equals("policyOn"); - boolean isValid = args[2].equals("valid"); - - if (!policyOn) { - // disable policy (default is on) - Security.setProperty("jdk.security.caDistrustPolicies", ""); - } - - Date notBefore = before ? BEFORE_APRIL_17_2019 : APRIL_17_2019; - - X509TrustManager pkixTM = getTMF("PKIX", null); - X509TrustManager sunX509TM = getTMF("SunX509", null); - for (String test : rootsToTest) { - System.err.println("Testing " + test); - X509Certificate[] chain = loadCertificateChain(test); - - testTM(sunX509TM, chain, notBefore, isValid); - testTM(pkixTM, chain, notBefore, isValid); - } - - // test chain if params are passed to TrustManager - System.err.println("Testing verisignuniversalrootca with params"); - testTM(getTMF("PKIX", getParams()), - loadCertificateChain("verisignuniversalrootca"), - notBefore, isValid); - - // test code-signing chain (should be valid as restrictions don't apply) - System.err.println("Testing verisignclass3g5ca code-signing chain"); - Validator v = Validator.getInstance(Validator.TYPE_PKIX, - Validator.VAR_CODE_SIGNING, - getParams()); - // set validation date so this will still pass when cert expires - v.setValidationDate(new Date(1544197375493l)); - v.validate(loadCertificateChain("verisignclass3g5ca-codesigning")); - - // test chains issued through subCAs - notBefore = before ? BEFORE_JANUARY_1_2020 : JANUARY_1_2020; - for (String test : subCAsToTest) { - System.err.println("Testing " + test); - X509Certificate[] chain = loadCertificateChain(test); - - testTM(sunX509TM, chain, notBefore, isValid); - testTM(pkixTM, chain, notBefore, isValid); - } - } - - private static X509TrustManager getTMF(String type, - PKIXBuilderParameters params) throws Exception { - TrustManagerFactory tmf = TrustManagerFactory.getInstance(type); - if (params == null) { - tmf.init((KeyStore)null); - } else { - tmf.init(new CertPathTrustManagerParameters(params)); - } - TrustManager[] tms = tmf.getTrustManagers(); - for (TrustManager tm : tms) { - X509TrustManager xtm = (X509TrustManager)tm; - return xtm; - } - throw new Exception("No TrustManager for " + type); - } - - private static PKIXBuilderParameters getParams() throws Exception { - PKIXBuilderParameters pbp = - new PKIXBuilderParameters(SecurityUtils.getCacertsKeyStore(), - new X509CertSelector()); - pbp.setRevocationEnabled(false); - return pbp; - } - - private static void testTM(X509TrustManager xtm, X509Certificate[] chain, - Date notBefore, boolean valid) throws Exception { - // Check if TLS Server certificate (the first element of the chain) - // is issued after the specified notBefore date (should be rejected - // unless distrust property is false). To do this, we need to - // fake the notBefore date since none of the test certs are issued - // after then. - chain[0] = new DistrustedTLSServerCert(chain[0], notBefore); - - try { - xtm.checkServerTrusted(chain, "ECDHE_RSA"); - if (!valid) { - throw new Exception("chain should be invalid"); - } - } catch (CertificateException ce) { - // expired TLS certificates should not be treated as failure - if (expired(ce)) { - System.err.println("Test is N/A, chain is expired"); - return; - } - if (valid) { - throw new Exception("Unexpected exception, chain " + - "should be valid", ce); - } - if (ce instanceof ValidatorException) { - ValidatorException ve = (ValidatorException)ce; - if (ve.getErrorType() != ValidatorException.T_UNTRUSTED_CERT) { - ce.printStackTrace(System.err); - throw new Exception("Unexpected exception: " + ce); - } - } else { - throw new Exception("Unexpected exception: " + ce); - } - } - } - - // check if a cause of exception is an expired cert - private static boolean expired(CertificateException ce) { - if (ce instanceof CertificateExpiredException) { - return true; - } - Throwable t = ce.getCause(); - while (t != null) { - if (t instanceof CertificateExpiredException) { - return true; - } - t = t.getCause(); - } - return false; - } - - private static X509Certificate[] loadCertificateChain(String name) - throws Exception { - try (InputStream in = new FileInputStream(TEST_SRC + File.separator + - name + "-chain.pem")) { - Collection certs = - (Collection)cf.generateCertificates(in); - return certs.toArray(new X509Certificate[0]); - } - } - - private static class DistrustedTLSServerCert extends X509Certificate { - private final X509Certificate cert; - private final Date notBefore; - DistrustedTLSServerCert(X509Certificate cert, Date notBefore) { - this.cert = cert; - this.notBefore = notBefore; - } - public Set getCriticalExtensionOIDs() { - return cert.getCriticalExtensionOIDs(); - } - public byte[] getExtensionValue(String oid) { - return cert.getExtensionValue(oid); - } - public Set getNonCriticalExtensionOIDs() { - return cert.getNonCriticalExtensionOIDs(); - } - public boolean hasUnsupportedCriticalExtension() { - return cert.hasUnsupportedCriticalExtension(); - } - public void checkValidity() throws CertificateExpiredException, - CertificateNotYetValidException { - // always pass - } - public void checkValidity(Date date) throws CertificateExpiredException, - CertificateNotYetValidException { - // always pass - } - public int getVersion() { return cert.getVersion(); } - public BigInteger getSerialNumber() { return cert.getSerialNumber(); } - public Principal getIssuerDN() { return cert.getIssuerDN(); } - public Principal getSubjectDN() { return cert.getSubjectDN(); } - public Date getNotBefore() { return notBefore; } - public Date getNotAfter() { return cert.getNotAfter(); } - public byte[] getTBSCertificate() throws CertificateEncodingException { - return cert.getTBSCertificate(); - } - public byte[] getSignature() { return cert.getSignature(); } - public String getSigAlgName() { return cert.getSigAlgName(); } - public String getSigAlgOID() { return cert.getSigAlgOID(); } - public byte[] getSigAlgParams() { return cert.getSigAlgParams(); } - public boolean[] getIssuerUniqueID() { - return cert.getIssuerUniqueID(); - } - public boolean[] getSubjectUniqueID() { - return cert.getSubjectUniqueID(); - } - public boolean[] getKeyUsage() { return cert.getKeyUsage(); } - public int getBasicConstraints() { return cert.getBasicConstraints(); } - public byte[] getEncoded() throws CertificateEncodingException { - return cert.getEncoded(); - } - public void verify(PublicKey key) throws CertificateException, - InvalidKeyException, NoSuchAlgorithmException, - NoSuchProviderException, SignatureException { - cert.verify(key); - } - public void verify(PublicKey key, String sigProvider) throws - CertificateException, InvalidKeyException, NoSuchAlgorithmException, - NoSuchProviderException, SignatureException { - cert.verify(key, sigProvider); - } - public PublicKey getPublicKey() { return cert.getPublicKey(); } - public String toString() { return cert.toString(); } - } -} diff --git a/test/jdk/sun/security/ssl/X509TrustManagerImpl/Entrust/Distrust.java b/test/jdk/sun/security/ssl/X509TrustManagerImpl/distrust/Distrust.java similarity index 54% rename from test/jdk/sun/security/ssl/X509TrustManagerImpl/Entrust/Distrust.java rename to test/jdk/sun/security/ssl/X509TrustManagerImpl/distrust/Distrust.java index 1c1fcee3609..18178f65ec1 100644 --- a/test/jdk/sun/security/ssl/X509TrustManagerImpl/Entrust/Distrust.java +++ b/test/jdk/sun/security/ssl/X509TrustManagerImpl/distrust/Distrust.java @@ -25,7 +25,7 @@ import java.math.BigInteger; import java.security.*; import java.security.cert.*; -import java.time.*; +import java.time.ZonedDateTime; import java.util.*; import javax.net.ssl.*; import sun.security.validator.Validator; @@ -34,95 +34,80 @@ import jdk.test.lib.security.SecurityUtils; /** - * @test - * @bug 8337664 8341059 - * @summary Check that TLS Server certificates chaining back to distrusted - * Entrust roots are invalid - * @library /test/lib - * @modules java.base/sun.security.validator - * @run main/othervm Distrust after policyOn invalid - * @run main/othervm Distrust after policyOff valid - * @run main/othervm Distrust before policyOn valid - * @run main/othervm Distrust before policyOff valid + * Helper class that provides methods to facilitate testing of distrusted roots. */ - -public class Distrust { +public final class Distrust { private static final String TEST_SRC = System.getProperty("test.src", "."); private static CertificateFactory cf; - // Each of the roots have a test certificate chain stored in a file - // named "-chain.pem". - private static String[] rootsToTest = new String[] { - "entrustevca", "entrustrootcaec1", "entrustrootcag2", "entrustrootcag4", - "entrust2048ca", "affirmtrustcommercialca", "affirmtrustnetworkingca", - "affirmtrustpremiumca", "affirmtrustpremiumeccca" }; - - // A date that is after the restrictions take effect - private static final Date NOVEMBER_12_2024 = - Date.from(LocalDate.of(2024, 11, 12) - .atStartOfDay(ZoneOffset.UTC) - .toInstant()); - - // A date that is a second before the restrictions take effect - private static final Date BEFORE_NOVEMBER_12_2024 = - Date.from(LocalDate.of(2024, 11, 12) - .atStartOfDay(ZoneOffset.UTC) - .minusSeconds(1) - .toInstant()); - - public static void main(String[] args) throws Exception { + private final boolean before; + private final boolean policyOn; + private final boolean isValid; - cf = CertificateFactory.getInstance("X.509"); - - boolean before = args[0].equals("before"); - boolean policyOn = args[1].equals("policyOn"); - boolean isValid = args[2].equals("valid"); + public Distrust(String[] args) { + before = args[0].equals("before"); + policyOn = args[1].equals("policyOn"); + isValid = args[2].equals("valid"); if (!policyOn) { // disable policy (default is on) Security.setProperty("jdk.security.caDistrustPolicies", ""); } + } + + public Date getNotBefore(ZonedDateTime distrustDate) { + ZonedDateTime notBefore = before ? distrustDate.minusSeconds(1) : distrustDate; + return Date.from(notBefore.toInstant()); + } - Date notBefore = before ? BEFORE_NOVEMBER_12_2024 : NOVEMBER_12_2024; + public void testCodeSigningChain(String certPath, String name, Date validationDate) + throws Exception { + System.err.println("Testing " + name + " code-signing chain"); + Validator v = Validator.getInstance(Validator.TYPE_PKIX, + Validator.VAR_CODE_SIGNING, + getParams()); + // set validation date so this will still pass when cert expires + v.setValidationDate(validationDate); + v.validate(loadCertificateChain(certPath, name)); + } - X509TrustManager pkixTM = getTMF("PKIX", null); - X509TrustManager sunX509TM = getTMF("SunX509", null); - for (String test : rootsToTest) { + public void testCertificateChain(String certPath, Date notBefore, X509TrustManager[] tms, + String... tests) throws Exception { + for (String test : tests) { System.err.println("Testing " + test); - X509Certificate[] chain = loadCertificateChain(test); + X509Certificate[] chain = loadCertificateChain(certPath, test); - testTM(sunX509TM, chain, notBefore, isValid); - testTM(pkixTM, chain, notBefore, isValid); + for (X509TrustManager tm : tms) { + testTM(tm, chain, notBefore, isValid); + } } } - private static X509TrustManager getTMF(String type, - PKIXBuilderParameters params) throws Exception { + public X509TrustManager getTMF(String type, PKIXBuilderParameters params) throws Exception { TrustManagerFactory tmf = TrustManagerFactory.getInstance(type); if (params == null) { - tmf.init((KeyStore)null); + tmf.init((KeyStore) null); } else { tmf.init(new CertPathTrustManagerParameters(params)); } TrustManager[] tms = tmf.getTrustManagers(); for (TrustManager tm : tms) { - X509TrustManager xtm = (X509TrustManager)tm; - return xtm; + return (X509TrustManager) tm; } - throw new Exception("No TrustManager for " + type); + throw new RuntimeException("No TrustManager for " + type); } - private static PKIXBuilderParameters getParams() throws Exception { + public PKIXBuilderParameters getParams() throws Exception { PKIXBuilderParameters pbp = - new PKIXBuilderParameters(SecurityUtils.getCacertsKeyStore(), - new X509CertSelector()); + new PKIXBuilderParameters(SecurityUtils.getCacertsKeyStore(), + new X509CertSelector()); pbp.setRevocationEnabled(false); return pbp; } - private static void testTM(X509TrustManager xtm, X509Certificate[] chain, - Date notBefore, boolean valid) throws Exception { + public void testTM(X509TrustManager xtm, X509Certificate[] chain, + Date notBefore, boolean valid) { // Check if TLS Server certificate (the first element of the chain) // is issued after the specified notBefore date (should be rejected // unless distrust property is false). To do this, we need to @@ -130,67 +115,54 @@ private static void testTM(X509TrustManager xtm, X509Certificate[] chain, // after then. chain[0] = new DistrustedTLSServerCert(chain[0], notBefore); + // Wrap the intermediate and root CA certs in NonExpiringTLSServerCert + // so it will never throw a CertificateExpiredException + for (int i = 1; i < chain.length; i++) { + chain[i] = new NonExpiringTLSServerCert(chain[i]); + } + try { xtm.checkServerTrusted(chain, "ECDHE_RSA"); if (!valid) { - throw new Exception("chain should be invalid"); + throw new RuntimeException("chain should be invalid"); } } catch (CertificateException ce) { - // expired TLS certificates should not be treated as failure - if (expired(ce)) { - System.err.println("Test is N/A, chain is expired"); - return; - } if (valid) { - throw new Exception("Unexpected exception, chain " + - "should be valid", ce); + throw new RuntimeException("Unexpected exception, chain " + + "should be valid", ce); } if (ce instanceof ValidatorException) { - ValidatorException ve = (ValidatorException)ce; + ValidatorException ve = (ValidatorException) ce; if (ve.getErrorType() != ValidatorException.T_UNTRUSTED_CERT) { ce.printStackTrace(System.err); - throw new Exception("Unexpected exception: " + ce); + throw new RuntimeException("Unexpected exception: " + ce); } } else { - throw new Exception("Unexpected exception: " + ce); + throw new RuntimeException(ce); } } } - // check if a cause of exception is an expired cert - private static boolean expired(CertificateException ce) { - if (ce instanceof CertificateExpiredException) { - return true; - } - Throwable t = ce.getCause(); - while (t != null) { - if (t instanceof CertificateExpiredException) { - return true; - } - t = t.getCause(); - } - return false; - } - - private static X509Certificate[] loadCertificateChain(String name) + private X509Certificate[] loadCertificateChain(String certPath, String name) throws Exception { - try (InputStream in = new FileInputStream(TEST_SRC + File.separator + - name + "-chain.pem")) { + if (cf == null) { + cf = CertificateFactory.getInstance("X.509"); + } + try (InputStream in = new FileInputStream(TEST_SRC + File.separator + certPath + + File.separator + name + "-chain.pem")) { Collection certs = - (Collection)cf.generateCertificates(in); + (Collection) cf.generateCertificates(in); return certs.toArray(new X509Certificate[0]); } } - private static class DistrustedTLSServerCert extends X509Certificate { + private static class NonExpiringTLSServerCert extends X509Certificate { private final X509Certificate cert; - private final Date notBefore; - DistrustedTLSServerCert(X509Certificate cert, Date notBefore) { + NonExpiringTLSServerCert(X509Certificate cert) { this.cert = cert; - this.notBefore = notBefore; } public Set getCriticalExtensionOIDs() { - return cert.getCriticalExtensionOIDs(); + return cert.getCriticalExtensionOIDs(); } public byte[] getExtensionValue(String oid) { return cert.getExtensionValue(oid); @@ -201,19 +173,17 @@ public Set getNonCriticalExtensionOIDs() { public boolean hasUnsupportedCriticalExtension() { return cert.hasUnsupportedCriticalExtension(); } - public void checkValidity() throws CertificateExpiredException, - CertificateNotYetValidException { + public void checkValidity() { // always pass } - public void checkValidity(Date date) throws CertificateExpiredException, - CertificateNotYetValidException { + public void checkValidity(Date date) { // always pass } public int getVersion() { return cert.getVersion(); } public BigInteger getSerialNumber() { return cert.getSerialNumber(); } public Principal getIssuerDN() { return cert.getIssuerDN(); } public Principal getSubjectDN() { return cert.getSubjectDN(); } - public Date getNotBefore() { return notBefore; } + public Date getNotBefore() { return cert.getNotBefore(); } public Date getNotAfter() { return cert.getNotAfter(); } public byte[] getTBSCertificate() throws CertificateEncodingException { return cert.getTBSCertificate(); @@ -234,16 +204,25 @@ public byte[] getEncoded() throws CertificateEncodingException { return cert.getEncoded(); } public void verify(PublicKey key) throws CertificateException, - InvalidKeyException, NoSuchAlgorithmException, - NoSuchProviderException, SignatureException { + InvalidKeyException, NoSuchAlgorithmException, + NoSuchProviderException, SignatureException { cert.verify(key); } public void verify(PublicKey key, String sigProvider) throws - CertificateException, InvalidKeyException, NoSuchAlgorithmException, - NoSuchProviderException, SignatureException { + CertificateException, InvalidKeyException, NoSuchAlgorithmException, + NoSuchProviderException, SignatureException { cert.verify(key, sigProvider); } public PublicKey getPublicKey() { return cert.getPublicKey(); } public String toString() { return cert.toString(); } } + + private static class DistrustedTLSServerCert extends NonExpiringTLSServerCert { + private final Date notBefore; + DistrustedTLSServerCert(X509Certificate cert, Date notBefore) { + super(cert); + this.notBefore = notBefore; + } + public Date getNotBefore() { return notBefore; } + } } diff --git a/test/jdk/sun/security/ssl/X509TrustManagerImpl/distrust/Entrust.java b/test/jdk/sun/security/ssl/X509TrustManagerImpl/distrust/Entrust.java new file mode 100644 index 00000000000..809674e8f20 --- /dev/null +++ b/test/jdk/sun/security/ssl/X509TrustManagerImpl/distrust/Entrust.java @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.io.File; +import java.time.*; +import java.util.*; +import javax.net.ssl.*; + +/** + * @test + * @bug 8337664 8341059 + * @summary Check that TLS Server certificates chaining back to distrusted + * Entrust roots are invalid + * @library /test/lib + * @modules java.base/sun.security.validator + * @run main/othervm Entrust after policyOn invalid + * @run main/othervm Entrust after policyOff valid + * @run main/othervm Entrust before policyOn valid + * @run main/othervm Entrust before policyOff valid + */ + +public class Entrust { + + private static final String certPath = "chains" + File.separator + "entrust"; + + // Each of the roots have a test certificate chain stored in a file + // named "-chain.pem". + private static String[] rootsToTest = new String[]{ + "entrustevca", "entrustrootcaec1", "entrustrootcag2", "entrustrootcag4", + "entrust2048ca", "affirmtrustcommercialca", "affirmtrustnetworkingca", + "affirmtrustpremiumca", "affirmtrustpremiumeccca"}; + + // Date when the restrictions take effect + private static final ZonedDateTime DISTRUST_DATE = + LocalDate.of(2024, 11, 12).atStartOfDay(ZoneOffset.UTC); + + public static void main(String[] args) throws Exception { + Distrust distrust = new Distrust(args); + + X509TrustManager[] tms = new X509TrustManager[]{ + distrust.getTMF("PKIX", null), + distrust.getTMF("SunX509", null) + }; + + Date notBefore = distrust.getNotBefore(DISTRUST_DATE); + distrust.testCertificateChain(certPath, notBefore, tms, rootsToTest); + } +} diff --git a/test/jdk/sun/security/ssl/X509TrustManagerImpl/distrust/Symantec.java b/test/jdk/sun/security/ssl/X509TrustManagerImpl/distrust/Symantec.java new file mode 100644 index 00000000000..4e099a8de8d --- /dev/null +++ b/test/jdk/sun/security/ssl/X509TrustManagerImpl/distrust/Symantec.java @@ -0,0 +1,95 @@ +/* + * Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import javax.net.ssl.X509TrustManager; +import java.io.File; +import java.time.*; +import java.util.*; + + +/** + * @test + * @bug 8207258 8216280 + * @summary Check that TLS Server certificates chaining back to distrusted + * Symantec roots are invalid + * @library /test/lib + * @modules java.base/sun.security.validator + * @run main/othervm Symantec after policyOn invalid + * @run main/othervm Symantec after policyOff valid + * @run main/othervm Symantec before policyOn valid + * @run main/othervm Symantec before policyOff valid + */ + +public class Symantec { + + private static final String certPath = "chains" + File.separator + "symantec"; + + // Each of the roots have a test certificate chain stored in a file + // named "-chain.pem". + private static final String[] rootsToTest = new String[]{ + "geotrustprimarycag2", "geotrustprimarycag3", "geotrustuniversalca", + "thawteprimaryrootca", "thawteprimaryrootcag2", "thawteprimaryrootcag3", + "verisignclass3g3ca", "verisignclass3g4ca", "verisignclass3g5ca", + "verisignuniversalrootca" + }; + + // Each of the subCAs with a delayed distrust date have a test certificate + // chain stored in a file named "-chain.pem". + private static String[] subCAsToTest = new String[]{"appleistca8g1"}; + + // Date when the restrictions take effect + private static final ZonedDateTime ROOTS_DISTRUST_DATE = + LocalDate.of(2019, 4, 17).atStartOfDay(ZoneOffset.UTC); + + // Date when the subCA restrictions take effect + private static final ZonedDateTime SUBCA_DISTRUST_DATE = + LocalDate.of(2020, 1, 1).atStartOfDay(ZoneOffset.UTC); + + public static void main(String[] args) throws Exception { + Distrust distrust = new Distrust(args); + X509TrustManager[] tms = new X509TrustManager[]{ + distrust.getTMF("PKIX", null), + distrust.getTMF("SunX509", null) + }; + + // test chains issued through roots + Date notBefore = distrust.getNotBefore(ROOTS_DISTRUST_DATE); + distrust.testCertificateChain(certPath, notBefore, tms, rootsToTest); + + // test chain if params are passed to TrustManager + System.err.println("Testing verisignuniversalrootca with params"); + X509TrustManager[] tmsParams = new X509TrustManager[]{ + distrust.getTMF("PKIX", distrust.getParams()) + }; + distrust.testCertificateChain(certPath, notBefore, tmsParams, + "verisignuniversalrootca"); + + // test code-signing chain (should be valid as restrictions don't apply) + Date validationDate = new Date(1544197375493L); + distrust.testCodeSigningChain(certPath, "verisignclass3g5ca-codesigning", validationDate); + + // test chains issued through subCAs + notBefore = distrust.getNotBefore(SUBCA_DISTRUST_DATE); + distrust.testCertificateChain(certPath, notBefore, tms, subCAsToTest); + } +} diff --git a/test/jdk/sun/security/ssl/X509TrustManagerImpl/Entrust/affirmtrustcommercialca-chain.pem b/test/jdk/sun/security/ssl/X509TrustManagerImpl/distrust/chains/entrust/affirmtrustcommercialca-chain.pem similarity index 100% rename from test/jdk/sun/security/ssl/X509TrustManagerImpl/Entrust/affirmtrustcommercialca-chain.pem rename to test/jdk/sun/security/ssl/X509TrustManagerImpl/distrust/chains/entrust/affirmtrustcommercialca-chain.pem diff --git a/test/jdk/sun/security/ssl/X509TrustManagerImpl/Entrust/affirmtrustnetworkingca-chain.pem b/test/jdk/sun/security/ssl/X509TrustManagerImpl/distrust/chains/entrust/affirmtrustnetworkingca-chain.pem similarity index 100% rename from test/jdk/sun/security/ssl/X509TrustManagerImpl/Entrust/affirmtrustnetworkingca-chain.pem rename to test/jdk/sun/security/ssl/X509TrustManagerImpl/distrust/chains/entrust/affirmtrustnetworkingca-chain.pem diff --git a/test/jdk/sun/security/ssl/X509TrustManagerImpl/Entrust/affirmtrustpremiumca-chain.pem b/test/jdk/sun/security/ssl/X509TrustManagerImpl/distrust/chains/entrust/affirmtrustpremiumca-chain.pem similarity index 100% rename from test/jdk/sun/security/ssl/X509TrustManagerImpl/Entrust/affirmtrustpremiumca-chain.pem rename to test/jdk/sun/security/ssl/X509TrustManagerImpl/distrust/chains/entrust/affirmtrustpremiumca-chain.pem diff --git a/test/jdk/sun/security/ssl/X509TrustManagerImpl/Entrust/affirmtrustpremiumeccca-chain.pem b/test/jdk/sun/security/ssl/X509TrustManagerImpl/distrust/chains/entrust/affirmtrustpremiumeccca-chain.pem similarity index 100% rename from test/jdk/sun/security/ssl/X509TrustManagerImpl/Entrust/affirmtrustpremiumeccca-chain.pem rename to test/jdk/sun/security/ssl/X509TrustManagerImpl/distrust/chains/entrust/affirmtrustpremiumeccca-chain.pem diff --git a/test/jdk/sun/security/ssl/X509TrustManagerImpl/Entrust/entrust2048ca-chain.pem b/test/jdk/sun/security/ssl/X509TrustManagerImpl/distrust/chains/entrust/entrust2048ca-chain.pem similarity index 100% rename from test/jdk/sun/security/ssl/X509TrustManagerImpl/Entrust/entrust2048ca-chain.pem rename to test/jdk/sun/security/ssl/X509TrustManagerImpl/distrust/chains/entrust/entrust2048ca-chain.pem diff --git a/test/jdk/sun/security/ssl/X509TrustManagerImpl/Entrust/entrustevca-chain.pem b/test/jdk/sun/security/ssl/X509TrustManagerImpl/distrust/chains/entrust/entrustevca-chain.pem similarity index 100% rename from test/jdk/sun/security/ssl/X509TrustManagerImpl/Entrust/entrustevca-chain.pem rename to test/jdk/sun/security/ssl/X509TrustManagerImpl/distrust/chains/entrust/entrustevca-chain.pem diff --git a/test/jdk/sun/security/ssl/X509TrustManagerImpl/Entrust/entrustrootcaec1-chain.pem b/test/jdk/sun/security/ssl/X509TrustManagerImpl/distrust/chains/entrust/entrustrootcaec1-chain.pem similarity index 100% rename from test/jdk/sun/security/ssl/X509TrustManagerImpl/Entrust/entrustrootcaec1-chain.pem rename to test/jdk/sun/security/ssl/X509TrustManagerImpl/distrust/chains/entrust/entrustrootcaec1-chain.pem diff --git a/test/jdk/sun/security/ssl/X509TrustManagerImpl/Entrust/entrustrootcag2-chain.pem b/test/jdk/sun/security/ssl/X509TrustManagerImpl/distrust/chains/entrust/entrustrootcag2-chain.pem similarity index 100% rename from test/jdk/sun/security/ssl/X509TrustManagerImpl/Entrust/entrustrootcag2-chain.pem rename to test/jdk/sun/security/ssl/X509TrustManagerImpl/distrust/chains/entrust/entrustrootcag2-chain.pem diff --git a/test/jdk/sun/security/ssl/X509TrustManagerImpl/Entrust/entrustrootcag4-chain.pem b/test/jdk/sun/security/ssl/X509TrustManagerImpl/distrust/chains/entrust/entrustrootcag4-chain.pem similarity index 100% rename from test/jdk/sun/security/ssl/X509TrustManagerImpl/Entrust/entrustrootcag4-chain.pem rename to test/jdk/sun/security/ssl/X509TrustManagerImpl/distrust/chains/entrust/entrustrootcag4-chain.pem diff --git a/test/jdk/sun/security/ssl/X509TrustManagerImpl/Symantec/appleistca8g1-chain.pem b/test/jdk/sun/security/ssl/X509TrustManagerImpl/distrust/chains/symantec/appleistca8g1-chain.pem similarity index 100% rename from test/jdk/sun/security/ssl/X509TrustManagerImpl/Symantec/appleistca8g1-chain.pem rename to test/jdk/sun/security/ssl/X509TrustManagerImpl/distrust/chains/symantec/appleistca8g1-chain.pem diff --git a/test/jdk/sun/security/ssl/X509TrustManagerImpl/Symantec/geotrustprimarycag2-chain.pem b/test/jdk/sun/security/ssl/X509TrustManagerImpl/distrust/chains/symantec/geotrustprimarycag2-chain.pem similarity index 100% rename from test/jdk/sun/security/ssl/X509TrustManagerImpl/Symantec/geotrustprimarycag2-chain.pem rename to test/jdk/sun/security/ssl/X509TrustManagerImpl/distrust/chains/symantec/geotrustprimarycag2-chain.pem diff --git a/test/jdk/sun/security/ssl/X509TrustManagerImpl/Symantec/geotrustprimarycag3-chain.pem b/test/jdk/sun/security/ssl/X509TrustManagerImpl/distrust/chains/symantec/geotrustprimarycag3-chain.pem similarity index 100% rename from test/jdk/sun/security/ssl/X509TrustManagerImpl/Symantec/geotrustprimarycag3-chain.pem rename to test/jdk/sun/security/ssl/X509TrustManagerImpl/distrust/chains/symantec/geotrustprimarycag3-chain.pem diff --git a/test/jdk/sun/security/ssl/X509TrustManagerImpl/Symantec/geotrustuniversalca-chain.pem b/test/jdk/sun/security/ssl/X509TrustManagerImpl/distrust/chains/symantec/geotrustuniversalca-chain.pem similarity index 100% rename from test/jdk/sun/security/ssl/X509TrustManagerImpl/Symantec/geotrustuniversalca-chain.pem rename to test/jdk/sun/security/ssl/X509TrustManagerImpl/distrust/chains/symantec/geotrustuniversalca-chain.pem diff --git a/test/jdk/sun/security/ssl/X509TrustManagerImpl/Symantec/thawteprimaryrootca-chain.pem b/test/jdk/sun/security/ssl/X509TrustManagerImpl/distrust/chains/symantec/thawteprimaryrootca-chain.pem similarity index 100% rename from test/jdk/sun/security/ssl/X509TrustManagerImpl/Symantec/thawteprimaryrootca-chain.pem rename to test/jdk/sun/security/ssl/X509TrustManagerImpl/distrust/chains/symantec/thawteprimaryrootca-chain.pem diff --git a/test/jdk/sun/security/ssl/X509TrustManagerImpl/Symantec/thawteprimaryrootcag2-chain.pem b/test/jdk/sun/security/ssl/X509TrustManagerImpl/distrust/chains/symantec/thawteprimaryrootcag2-chain.pem similarity index 100% rename from test/jdk/sun/security/ssl/X509TrustManagerImpl/Symantec/thawteprimaryrootcag2-chain.pem rename to test/jdk/sun/security/ssl/X509TrustManagerImpl/distrust/chains/symantec/thawteprimaryrootcag2-chain.pem diff --git a/test/jdk/sun/security/ssl/X509TrustManagerImpl/Symantec/thawteprimaryrootcag3-chain.pem b/test/jdk/sun/security/ssl/X509TrustManagerImpl/distrust/chains/symantec/thawteprimaryrootcag3-chain.pem similarity index 100% rename from test/jdk/sun/security/ssl/X509TrustManagerImpl/Symantec/thawteprimaryrootcag3-chain.pem rename to test/jdk/sun/security/ssl/X509TrustManagerImpl/distrust/chains/symantec/thawteprimaryrootcag3-chain.pem diff --git a/test/jdk/sun/security/ssl/X509TrustManagerImpl/Symantec/verisignclass3g3ca-chain.pem b/test/jdk/sun/security/ssl/X509TrustManagerImpl/distrust/chains/symantec/verisignclass3g3ca-chain.pem similarity index 100% rename from test/jdk/sun/security/ssl/X509TrustManagerImpl/Symantec/verisignclass3g3ca-chain.pem rename to test/jdk/sun/security/ssl/X509TrustManagerImpl/distrust/chains/symantec/verisignclass3g3ca-chain.pem diff --git a/test/jdk/sun/security/ssl/X509TrustManagerImpl/Symantec/verisignclass3g4ca-chain.pem b/test/jdk/sun/security/ssl/X509TrustManagerImpl/distrust/chains/symantec/verisignclass3g4ca-chain.pem similarity index 100% rename from test/jdk/sun/security/ssl/X509TrustManagerImpl/Symantec/verisignclass3g4ca-chain.pem rename to test/jdk/sun/security/ssl/X509TrustManagerImpl/distrust/chains/symantec/verisignclass3g4ca-chain.pem diff --git a/test/jdk/sun/security/ssl/X509TrustManagerImpl/Symantec/verisignclass3g5ca-chain.pem b/test/jdk/sun/security/ssl/X509TrustManagerImpl/distrust/chains/symantec/verisignclass3g5ca-chain.pem similarity index 100% rename from test/jdk/sun/security/ssl/X509TrustManagerImpl/Symantec/verisignclass3g5ca-chain.pem rename to test/jdk/sun/security/ssl/X509TrustManagerImpl/distrust/chains/symantec/verisignclass3g5ca-chain.pem diff --git a/test/jdk/sun/security/ssl/X509TrustManagerImpl/Symantec/verisignclass3g5ca-codesigning-chain.pem b/test/jdk/sun/security/ssl/X509TrustManagerImpl/distrust/chains/symantec/verisignclass3g5ca-codesigning-chain.pem similarity index 100% rename from test/jdk/sun/security/ssl/X509TrustManagerImpl/Symantec/verisignclass3g5ca-codesigning-chain.pem rename to test/jdk/sun/security/ssl/X509TrustManagerImpl/distrust/chains/symantec/verisignclass3g5ca-codesigning-chain.pem diff --git a/test/jdk/sun/security/ssl/X509TrustManagerImpl/Symantec/verisignuniversalrootca-chain.pem b/test/jdk/sun/security/ssl/X509TrustManagerImpl/distrust/chains/symantec/verisignuniversalrootca-chain.pem similarity index 100% rename from test/jdk/sun/security/ssl/X509TrustManagerImpl/Symantec/verisignuniversalrootca-chain.pem rename to test/jdk/sun/security/ssl/X509TrustManagerImpl/distrust/chains/symantec/verisignuniversalrootca-chain.pem diff --git a/test/jdk/sun/security/tools/keytool/KeyToolTest.java b/test/jdk/sun/security/tools/keytool/KeyToolTest.java index 76dd15b19ee..8eda0dce712 100644 --- a/test/jdk/sun/security/tools/keytool/KeyToolTest.java +++ b/test/jdk/sun/security/tools/keytool/KeyToolTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,6 +23,7 @@ /* * @test + * @library /java/security/testlibrary * @bug 6251120 8231950 8242151 * @summary Testing keytool * @@ -1865,172 +1866,4 @@ class TestException extends Exception { public TestException(String e) { super(e); } -} - -/** - * HumanInputStream tries to act like a human sitting in front of a computer - * terminal typing on the keyboard while the keytool program is running. - * - * keytool has called InputStream.read() and BufferedReader.readLine() in - * various places. a call to B.readLine() will try to buffer as much input as - * possible. Thus, a trivial InputStream will find it impossible to feed - * anything to I.read() after a B.readLine() call. - * - * This is why i create HumanInputStream, which will only send a single line - * to B.readLine(), no more, no less, and the next I.read() can have a chance - * to read the exact character right after "\n". - * - * I don't know why HumanInputStream works. - */ -class HumanInputStream extends InputStream { - byte[] src; - int pos; - int length; - boolean inLine; - int stopIt; - - public HumanInputStream(String input) { - src = input.getBytes(); - pos = 0; - length = src.length; - stopIt = 0; - inLine = false; - } - - // the trick: when called through read(byte[], int, int), - // return -1 twice after "\n" - - @Override public int read() throws IOException { - int re; - if(pos < length) { - re = src[pos]; - if(inLine) { - if(stopIt > 0) { - stopIt--; - re = -1; - } else { - if(re == '\n') { - stopIt = 2; - } - pos++; - } - } else { - pos++; - } - } else { - re = -1;//throw new IOException("NO MORE TO READ"); - } - //if (re < 32) System.err.printf("[%02d]", re); - //else System.err.printf("[%c]", (char)re); - return re; - } - @Override public int read(byte[] buffer, int offset, int len) { - inLine = true; - try { - int re = super.read(buffer, offset, len); - return re; - } catch(Exception e) { - throw new RuntimeException("HumanInputStream error"); - } finally { - inLine = false; - } - } - @Override public int available() { - if(pos < length) return 1; - return 0; - } - - // test part - static void assertTrue(boolean bool) { - if(!bool) - throw new RuntimeException(); - } - - public static void test() throws Exception { - - class Tester { - HumanInputStream is; - BufferedReader reader; - Tester(String s) { - is = new HumanInputStream(s); - reader = new BufferedReader(new InputStreamReader(is)); - } - - // three kinds of test method - // 1. read byte by byte from InputStream - void testStreamReadOnce(int expection) throws Exception { - assertTrue(is.read() == expection); - } - void testStreamReadMany(String expection) throws Exception { - char[] keys = expection.toCharArray(); - for(int i=0; i { // warm-up predicate return s.contains("Welcome to JShell"); diff --git a/test/jdk/sun/tools/jhsdb/JStackStressTest.java b/test/jdk/sun/tools/jhsdb/JStackStressTest.java index 9870908a3b2..97945b6092b 100644 --- a/test/jdk/sun/tools/jhsdb/JStackStressTest.java +++ b/test/jdk/sun/tools/jhsdb/JStackStressTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2021, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -93,7 +93,9 @@ public static void launchJshell() throws IOException { System.out.println("Starting Jshell"); long startTime = System.currentTimeMillis(); try { - ProcessBuilder pb = new ProcessBuilder(JDKToolFinder.getTestJDKTool("jshell")); + JDKToolLauncher launcher = JDKToolLauncher.createUsingTestJDK("jshell"); + launcher.addVMArgs(Utils.getTestJavaOpts()); + ProcessBuilder pb = new ProcessBuilder(launcher.getCommand()); jShellProcess = ProcessTools.startProcess("JShell", pb); } catch (Exception ex) { throw new RuntimeException("Test ERROR " + ex, ex); diff --git a/test/jdk/sun/tools/jinfo/JInfoTest.java b/test/jdk/sun/tools/jinfo/JInfoTest.java index bea0e4b796c..79512ddf0df 100644 --- a/test/jdk/sun/tools/jinfo/JInfoTest.java +++ b/test/jdk/sun/tools/jinfo/JInfoTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2023, Oracle and/or its affiliates. All rights reserved. * 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,9 +60,8 @@ private static void setFlag() throws Exception { LingeredApp app1 = new JInfoTestLingeredApp(); LingeredApp app2 = new JInfoTestLingeredApp(); try { - String[] params = new String[0];; - LingeredApp.startAppExactJvmOpts(app1, params); - LingeredApp.startAppExactJvmOpts(app2, params); + LingeredApp.startApp(app1); + LingeredApp.startApp(app2); OutputAnalyzer output = jinfo("-flag", "MinHeapFreeRatio=1", "JInfoTestLingeredApp"); output.shouldHaveExitValue(0); output = jinfo("-flag", "MinHeapFreeRatio", "JInfoTestLingeredApp"); @@ -89,9 +88,8 @@ private static void classNameMatch() throws Exception { LingeredApp app1 = new JInfoTestLingeredApp(); LingeredApp app2 = new JInfoTestLingeredApp(); try { - String[] params = new String[0]; - LingeredApp.startAppExactJvmOpts(app1, params); - LingeredApp.startAppExactJvmOpts(app2, params); + LingeredApp.startApp(app1); + LingeredApp.startApp(app2); OutputAnalyzer output = jinfo("JInfoTestLingeredApp"); output.shouldHaveExitValue(0); // "Runtime Environment" written once per proc diff --git a/test/jdk/sun/tools/jstat/JStatInterval.java b/test/jdk/sun/tools/jstat/JStatInterval.java index c3ff9404745..0719e1d11b6 100644 --- a/test/jdk/sun/tools/jstat/JStatInterval.java +++ b/test/jdk/sun/tools/jstat/JStatInterval.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -24,6 +24,7 @@ /** * @test * @bug 8035668 + * @requires vm.flagless * @library /test/lib * @summary Test checks case when target application finishes execution and jstat didn't complete work. jstat is started with interval = 100 (jstat -compiler 100) and monitored application finishes @@ -60,9 +61,7 @@ public static void main(String[] args) { } } public static void main(String[] args) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( - "-cp", - System.getProperty("test.class.path"), + ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder( "-XX:+UsePerfData", Application.class.getName() ); diff --git a/test/jdk/sun/util/calendar/zi/Month.java b/test/jdk/sun/util/calendar/zi/Month.java index cb60b8d4411..bab909f7637 100644 --- a/test/jdk/sun/util/calendar/zi/Month.java +++ b/test/jdk/sun/util/calendar/zi/Month.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,11 +21,6 @@ * questions. */ -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - /** * Month enum handles month related manipulation. * @@ -47,15 +42,6 @@ enum Month { private final String abbr; - private static final Map abbreviations - = new HashMap(12); - - static { - for (Month m : Month.values()) { - abbreviations.put(m.abbr, m); - } - } - private Month(String abbr) { this.abbr = abbr; } @@ -70,11 +56,22 @@ int value() { * @return the Month value */ static Month parse(String name) { - Month m = abbreviations.get(name); - if (m != null) { - return m; - } - return null; + int len = name.length(); + + if (name.regionMatches(true, 0, "January", 0, len)) return Month.JANUARY; + if (name.regionMatches(true, 0, "February", 0, len)) return Month.FEBRUARY; + if (name.regionMatches(true, 0, "March", 0, len)) return Month.MARCH; + if (name.regionMatches(true, 0, "April", 0, len)) return Month.APRIL; + if (name.regionMatches(true, 0, "May", 0, len)) return Month.MAY; + if (name.regionMatches(true, 0, "June", 0, len)) return Month.JUNE; + if (name.regionMatches(true, 0, "July", 0, len)) return Month.JULY; + if (name.regionMatches(true, 0, "August", 0, len)) return Month.AUGUST; + if (name.regionMatches(true, 0, "September", 0, len)) return Month.SEPTEMBER; + if (name.regionMatches(true, 0, "October", 0, len)) return Month.OCTOBER; + if (name.regionMatches(true, 0, "November", 0, len)) return Month.NOVEMBER; + if (name.regionMatches(true, 0, "December", 0, len)) return Month.DECEMBER; + + throw new IllegalArgumentException("Unknown month: " + name); } /** diff --git a/test/jdk/sun/util/calendar/zi/RuleDay.java b/test/jdk/sun/util/calendar/zi/RuleDay.java index bc730944b4c..9cd81c1e524 100644 --- a/test/jdk/sun/util/calendar/zi/RuleDay.java +++ b/test/jdk/sun/util/calendar/zi/RuleDay.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,11 +21,6 @@ * questions. */ -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - /** * RuleDay class represents the value of the "ON" field. The day of * week values start from 1 following the {@link java.util.Calendar} @@ -34,13 +29,6 @@ * @since 1.4 */ class RuleDay { - private static final Map abbreviations = new HashMap(7); - static { - for (DayOfWeek day : DayOfWeek.values()) { - abbreviations.put(day.getAbbr(), day); - } - } - private String dayName = null; private DayOfWeek dow; private boolean lastOne = false; @@ -166,13 +154,23 @@ String getDayOfWeekForSimpleTimeZone() { return sign + toString(d); } - private static DayOfWeek getDOW(String abbr) { - return abbreviations.get(abbr); + private static DayOfWeek getDOW(String name) { + int len = name.length(); + + if (name.regionMatches(true, 0, "Monday", 0, len)) return DayOfWeek.MONDAY; + if (name.regionMatches(true, 0, "Tuesday", 0, len)) return DayOfWeek.TUESDAY; + if (name.regionMatches(true, 0, "Wednesday", 0, len)) return DayOfWeek.WEDNESDAY; + if (name.regionMatches(true, 0, "Thursday", 0, len)) return DayOfWeek.THURSDAY; + if (name.regionMatches(true, 0, "Friday", 0, len)) return DayOfWeek.FRIDAY; + if (name.regionMatches(true, 0, "Saturday", 0, len)) return DayOfWeek.SATURDAY; + if (name.regionMatches(true, 0, "Sunday", 0, len)) return DayOfWeek.SUNDAY; + + throw new IllegalArgumentException("Unknown day-of-week: " + name); } /** * Converts the specified day of week value to the day-of-week - * name defined in {@link java.util.Calenda}. + * name defined in {@link java.util.Calendar}. * @param dow 1-based day of week value * @return the Calendar day of week name with "Calendar." prefix. * @throws IllegalArgumentException if the specified dow value is out of range. diff --git a/test/jdk/tools/jimage/JImageToolTest.java b/test/jdk/tools/jimage/JImageToolTest.java index fce9a0ac347..feb6a56a968 100644 --- a/test/jdk/tools/jimage/JImageToolTest.java +++ b/test/jdk/tools/jimage/JImageToolTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2023, Oracle and/or its affiliates. All rights reserved. * 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 @@ private static void jimage(String... jimageArgs) throws Exception { args.add("jdk.tools.jimage.Main"); args.addAll(Arrays.asList(jimageArgs)); - ProcessBuilder builder = ProcessTools.createJavaProcessBuilder(args.toArray(new String[args.size()])); + ProcessBuilder builder = ProcessTools.createLimitedTestJavaProcessBuilder(args.toArray(new String[args.size()])); int res = builder.inheritIO().start().waitFor(); if (res != 0) { diff --git a/test/jdk/tools/launcher/TestXcheckJNIWarnings.java b/test/jdk/tools/launcher/TestXcheckJNIWarnings.java index 9917ddb39a0..78a32342f95 100644 --- a/test/jdk/tools/launcher/TestXcheckJNIWarnings.java +++ b/test/jdk/tools/launcher/TestXcheckJNIWarnings.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2022, Oracle and/or its affiliates. All rights reserved. * 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,14 +25,22 @@ import java.io.IOException; /** - * @test + * @test id=noagent * @bug 8187442 * @summary Launching app shouldn't produce any jni warnings. * @modules jdk.compiler * jdk.zipfs - * @compile TestXcheckJNIWarnings.java * @run main TestXcheckJNIWarnings */ + +/** + * @test id=jdwp-agent + * @bug 8187442 + * @summary Launching app with jdwp agent shouldn't produce any jni warnings. + * @modules jdk.compiler + * jdk.zipfs + * @run main TestXcheckJNIWarnings -agentlib:jdwp=transport=dt_socket,server=y,suspend=n + */ public final class TestXcheckJNIWarnings extends TestHelper { static void createJarFile(File testJar) throws IOException { @@ -46,8 +54,14 @@ static void createJarFile(File testJar) throws IOException { public static void main(String... args) throws IOException { File testJarFile = new File("test.jar"); createJarFile(testJarFile); - TestResult tr = doExec(javaCmd, "-jar", "-Xcheck:jni", - testJarFile.getName()); + + TestResult tr; + if (args.length > 0) { + tr = doExec(javaCmd, "-jar", "-Xcheck:jni", args[0], testJarFile.getName()); + } else { + tr = doExec(javaCmd, "-jar", "-Xcheck:jni", testJarFile.getName()); + } + if (!tr.isOK()) { System.out.println(tr); throw new RuntimeException("test returned non-positive value"); diff --git a/test/jdk/tools/launcher/modules/basic/BasicTest.java b/test/jdk/tools/launcher/modules/basic/BasicTest.java index 6a91cdc6d7c..ac831119988 100644 --- a/test/jdk/tools/launcher/modules/basic/BasicTest.java +++ b/test/jdk/tools/launcher/modules/basic/BasicTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -270,7 +270,7 @@ public void testTryRunWithMainClassInWrongModule() throws Exception { * while setting the _JAVA_LAUNCHER_DEBUG environment variable. */ private ProcessBuilder createProcessWithLauncherDebugging(String... cmds) { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(Utils.addTestJavaOpts(cmds)); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(Utils.addTestJavaOpts(cmds)); pb.environment().put("_JAVA_LAUNCHER_DEBUG", "true"); return pb; diff --git a/test/jdk/tools/launcher/modules/classpath/JavaClassPathTest.java b/test/jdk/tools/launcher/modules/classpath/JavaClassPathTest.java index 0526c881d8a..5854021c4a3 100644 --- a/test/jdk/tools/launcher/modules/classpath/JavaClassPathTest.java +++ b/test/jdk/tools/launcher/modules/classpath/JavaClassPathTest.java @@ -200,7 +200,7 @@ public void testClassPathAttribute() throws Throwable { } private OutputAnalyzer execute(List options) throws Throwable { - // can't use ProcessTools.createJavaProcessBuilder as it always adds -cp + // can't use ProcessTools.createLimitedTestJavaProcessBuilder as it always adds -cp ProcessBuilder pb = new ProcessBuilder( Stream.concat(Stream.of(JDKToolFinder.getTestJDKTool("java")), options.stream() diff --git a/test/langtools/jdk/jshell/ExceptionMessageTest.java b/test/langtools/jdk/jshell/ExceptionMessageTest.java index 9f8b53f1563..fe8eec57739 100644 --- a/test/langtools/jdk/jshell/ExceptionMessageTest.java +++ b/test/langtools/jdk/jshell/ExceptionMessageTest.java @@ -26,6 +26,7 @@ * @bug 8185108 * @summary Test exception().getMessage() in events returned by eval() * @run testng ExceptionMessageTest + * @key intermittent */ import java.util.HashMap; diff --git a/test/langtools/tools/javac/Paths/Class-Path.sh b/test/langtools/tools/javac/Paths/Class-Path.sh deleted file mode 100644 index db4957366da..00000000000 --- a/test/langtools/tools/javac/Paths/Class-Path.sh +++ /dev/null @@ -1,198 +0,0 @@ -#!/bin/sh - -# -# Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved. -# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. -# -# This code is free software; you can redistribute it and/or modify it -# under the terms of the GNU General Public License version 2 only, as -# published by the Free Software Foundation. -# -# This code is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License -# version 2 for more details (a copy is included in the LICENSE file that -# accompanied this code). -# -# You should have received a copy of the GNU General Public License version -# 2 along with this work; if not, write to the Free Software Foundation, -# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA -# or visit www.oracle.com if you need additional information or have any -# questions. -# - - -# @test -# @bug 4212732 -# @summary Test handling of the Class-Path attribute in jar file manifests -# @author Martin Buchholz -# -# @run shell Class-Path.sh - -# To run this test manually, simply do ./Class-Path.sh - -. ${TESTSRC-.}/Util.sh - -set -u - -Cleanup() { - Sys rm -rf pkg Main.java Main.class Main.jar jars - Sys rm -rf MANIFEST.MF A.jar B.zip -} - -Cleanup -Sys mkdir pkg - -#---------------------------------------------------------------- -# Create mutually referential jar files -#---------------------------------------------------------------- -cat >pkg/A.java <pkg/B.java <Main.java <> MANIFEST.MF -Sys "$jar" cmf MANIFEST.MF Main.jar Main.class - -Success "$java" ${TESTVMOPTS} -jar Main.jar - -MkManifestWithClassPath "." -Sys "$jar" cmf MANIFEST.MF A.jar pkg/A.class - -Success "$javac" ${TESTTOOLVMOPTS} -cp "A.jar" Main.java -Success "$java" ${TESTVMOPTS} -jar Main.jar - -MkManifestWithClassPath "" -Sys "$jar" cmf MANIFEST.MF A.jar pkg/A.class - -Failure "$javac" ${TESTTOOLVMOPTS} -cp "A.jar" Main.java -Failure "$java" ${TESTVMOPTS} -jar Main.jar - -#---------------------------------------------------------------- -# Test new flag -e (application entry point) -#---------------------------------------------------------------- - -cat > Hello.java < Bye.java <> MANIFEST.MF - -# test for error: " 'e' flag and manifest with the 'Main-Class' -# attribute cannot be specified together, during creation -Failure "$jar" cmfe MANIFEST.MF "Bye.jar" "Bye" Bye.class - -# test for overriding the manifest when updating the jar -# -Success "$jar" cfe "greetings.jar" "Hello" Hello.class -Success "$jar" ufe "greetings.jar" "Bye" Bye.class -Success "$java" ${TESTVMOPTS} -jar greetings.jar - -# test for error: " 'e' flag and manifest with the 'Main-Class' -# attribute cannot be specified together, during update -Failure "$jar" umfe MANIFEST.MF "greetings.jar" "Hello" - -# test jar updation when there are no inputfiles -# -Success "$jar" ufe "Hello.jar" "Bye" -Failure "$java" ${TESTVMOPTS} -jar Hello.jar -Success "$jar" umf MANIFEST.MF "Hello.jar" - -# test creating jar when the to-be-archived files -# do not contain the specified main class, there is no check done -# for the presence of the main class, so the test will pass -# -Success "$jar" cfe "Hello.jar" "Hello" Bye.class - -# Jar creation and update when there is no manifest and inputfiles -# specified -Failure "$jar" cvf "A.jar" -Failure "$jar" uvf "A.jar" - -# error: no such file or directory -Failure "$jar" cvf "A.jar" non-existing.file -Failure "$jar" uvf "A.jar" non-existing.file - -Cleanup - -Bottom Line diff --git a/test/langtools/tools/javac/Paths/Class-Path2.sh b/test/langtools/tools/javac/Paths/Class-Path2.sh deleted file mode 100644 index fc37c6fdbfc..00000000000 --- a/test/langtools/tools/javac/Paths/Class-Path2.sh +++ /dev/null @@ -1,111 +0,0 @@ -#!/bin/sh -# -# Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved. -# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. -# -# This code is free software; you can redistribute it and/or modify it -# under the terms of the GNU General Public License version 2 only, as -# published by the Free Software Foundation. -# -# This code is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License -# version 2 for more details (a copy is included in the LICENSE file that -# accompanied this code). -# -# You should have received a copy of the GNU General Public License version -# 2 along with this work; if not, write to the Free Software Foundation, -# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA -# or visit www.oracle.com if you need additional information or have any -# questions. -# - -# @test -# @bug 4212732 6485027 -# @summary Test handling of the Class-Path attribute in jar file manifests -# @author Martin Buchholz -# -# @run shell Class-Path2.sh - -# To run this test manually, simply do ./Class-Path2.sh - -. ${TESTSRC-.}/Util.sh - -set -u - -Cleanup() { - Sys rm -rf pkg Main.java Main.class Main.jar jars - Sys rm -rf MANIFEST.MF A.jar B.zip -} - -Cleanup -Sys mkdir pkg - -#---------------------------------------------------------------- -# Create mutually referential jar files -#---------------------------------------------------------------- -cat >pkg/A.java <pkg/B.java <Main.java <&1`; rc="$?" - output2=`echo "$output" | grep -v "bootstrap class path not set in conjunction with -source"` - test -n "$output2" && echo "$output" - test $rc -eq 0 || Fail "Command \"$*\" failed with exitValue $rc"; - case "$output2" in *warning:*) gotwarning="yes";; *) gotwarning="no";; esac - - if test "$gotwarning" = "yes" -a "$NO" = "no"; then - Fail "Command \"$*\" printed an unexpected warning" - elif test "$gotwarning" = "no" -a "$NO" != "no"; then - Fail "Command \"$*\" did not generate the expected warning" - fi -} - -Error() { - HorizontalRule - echo "$@" - output=`"$@" 2>&1`; rc="$?" - test -n "$output" && echo "$output" - case "$output" in *error:*) goterror="yes";; *) goterror="no";; esac - - if test "$NO" = "no"; then - test "$rc" -ne 0 && \ - Fail "Command \"$*\" failed with return code $rc" - test "$goterror" = "yes" && \ - Fail "Command \"$*\" did not generate any error message" - else - test "$rc" -eq 0 && \ - Fail "Command \"$*\" was supposed to Die with fatal error"; - test "$goterror" = "no" && \ - Fail "Command \"$*\" printed an unexpected error message" - fi -} - -Cleanup() { - Sys rm -rf Main.java Main.class - Sys rm -rf classes classes.foo classes.jar classes.war classes.zip - Sys rm -rf MANIFEST.MF classesRef.jar classesRefRef.jar jars -} - -Cleanup -echo "public class Main{public static void main(String[]a){}}" > Main.java - -# We need to set -source 8 -target 8 for those cases where the option is -# not legal in 9 and later. However, that triggers an additional warning -# about not setting bootclasspath, which is filtered out in Warning. -# The alternative would be to extract a minimal rt.jar from JDK and -# specify that with -bootclasspath. -SRCTRG8="-source 8 -target 8" - -#---------------------------------------------------------------- -# No warnings unless -Xlint:path is used -#---------------------------------------------------------------- -No Warning "$javac" ${TESTTOOLVMOPTS} Main.java -No Warning "$javac" ${TESTTOOLVMOPTS} -cp ".${PS}classes" Main.java - -#---------------------------------------------------------------- -# Warn for missing elts in user-specified paths -#---------------------------------------------------------------- -Warning "$javac" ${TESTTOOLVMOPTS} -Xlint:path -cp ".${PS}classes" Main.java -Warning "$javac" ${TESTTOOLVMOPTS} ${SRCTRG8} -Xlint:path "-Xbootclasspath/p:classes" Main.java -Warning "$javac" ${TESTTOOLVMOPTS} ${SRCTRG8} -Xlint "-Xbootclasspath/a:classes" Main.java - -Warning "$javac" ${TESTTOOLVMOPTS} ${SRCTRG8} -Xlint:path "-endorseddirs" "classes" Main.java -Warning "$javac" ${TESTTOOLVMOPTS} ${SRCTRG8} -Xlint "-extdirs" "classes" Main.java -#Warning "$javac" ${TESTTOOLVMOPTS} ${SRCTRG8} -Xlint:path "-Xbootclasspath:classes${PS}${BCP}" Main.java - -#---------------------------------------------------------------- -# No warning for missing elts in "system" paths -#---------------------------------------------------------------- -# No Warning "$javac" ${TESTTOOLVMOPTS} -Xlint:path "-J-Djava.endorsed.dirs=classes" Main.java -# No Warning "$javac" ${TESTTOOLVMOPTS} -Xlint:path "-J-Djava.ext.dirs=classes" Main.java -# No Warning "$javac" ${TESTTOOLVMOPTS} -Xlint:path "-J-Xbootclasspath/p:classes" Main.java -# No Warning "$javac" ${TESTTOOLVMOPTS} -Xlint:path "-J-Xbootclasspath/a:classes" Main.java -# No Warning "$javac" ${TESTTOOLVMOPTS} -Xlint:path "-J-Xbootclasspath:classes${PS}${BCP}" Main.java - -#---------------------------------------------------------------- -# No warning if class path element exists -#---------------------------------------------------------------- -Sys mkdir classes -No Warning "$javac" ${TESTTOOLVMOPTS} -Xlint:path -cp ".${PS}classes" Main.java -No Warning "$javac" ${TESTTOOLVMOPTS} ${SRCTRG8} -Xlint:path "-endorseddirs" "classes" Main.java -No Warning "$javac" ${TESTTOOLVMOPTS} ${SRCTRG8} -Xlint:path "-extdirs" "classes" Main.java -No Warning "$javac" ${TESTTOOLVMOPTS} ${SRCTRG8} -Xlint:path "-Xbootclasspath/p:classes" Main.java -No Warning "$javac" ${TESTTOOLVMOPTS} ${SRCTRG8} -Xlint:path "-Xbootclasspath/a:classes" Main.java -#No Warning "$javac" ${TESTTOOLVMOPTS} ${SRCTRG8} -Xlint:path "-Xbootclasspath:classes${PS}${BCP}" Main.java - -Sys "$jar" cf classes.jar Main.class -Sys cp classes.jar classes.war -Sys cp classes.war classes.zip -No Warning "$javac" ${TESTTOOLVMOPTS} -Xlint:path -cp ".${PS}classes.jar" Main.java - Warning "$javac" ${TESTTOOLVMOPTS} -Xlint:path -cp ".${PS}classes.war" Main.java -No Warning "$javac" ${TESTTOOLVMOPTS} -Xlint:path -cp ".${PS}classes.zip" Main.java - -#---------------------------------------------------------------- -# Warn if -Xlint is used and if class path element refers to -# regular file which doesn't look like a zip file, but is -#---------------------------------------------------------------- -Sys cp classes.war classes.foo - Warning "$javac" ${TESTTOOLVMOPTS} -Xlint:path -cp ".${PS}classes.foo" Main.java - - -#---------------------------------------------------------------- -# No error if class path element refers to regular file which is -# not a zip file -#---------------------------------------------------------------- -No Error "$javac" ${TESTTOOLVMOPTS} -cp Main.java Main.java # Main.java is NOT a jar file -No Error "$javac" ${TESTTOOLVMOPTS} Main.java - -#---------------------------------------------------------------- -# Warn if -Xlint is used and if class path element refers to -# regular file which is not a zip file -#---------------------------------------------------------------- -Warning "$javac" ${TESTTOOLVMOPTS} -Xlint -cp Main.java Main.java # Main.java is NOT a jar file - -#---------------------------------------------------------------- -# Test jar file class path reference recursion -#---------------------------------------------------------------- -MkManifestWithClassPath classesRef.jar -Sys "$jar" cmf MANIFEST.MF classesRefRef.jar Main.class - -#---------------------------------------------------------------- -# Non-existent recursive Class-Path reference gives warning -#---------------------------------------------------------------- -No Warning "$javac" ${TESTTOOLVMOPTS} -classpath classesRefRef.jar Main.java - Warning "$javac" ${TESTTOOLVMOPTS} -Xlint -classpath classesRefRef.jar Main.java -No Warning "$javac" ${TESTTOOLVMOPTS} ${SRCTRG8} -Xlint -Xbootclasspath/p:classesRefRef.jar Main.java - -BadJarFile classesRef.jar - -#---------------------------------------------------------------- -# Non-jar file recursive Class-Path reference gives error -#---------------------------------------------------------------- - Error "$javac" ${TESTTOOLVMOPTS} -classpath classesRefRef.jar Main.java -No Error "$javac" ${TESTTOOLVMOPTS} ${SRCTRG8} -Xbootclasspath/a:classesRefRef.jar Main.java - -MkManifestWithClassPath classes -Sys "$jar" cmf MANIFEST.MF classesRef.jar Main.class - -#---------------------------------------------------------------- -# Jar file recursive Class-Path reference is OK -#---------------------------------------------------------------- -No Warning "$javac" ${TESTTOOLVMOPTS} -Xlint -classpath classesRefRef.jar Main.java -No Warning "$javac" ${TESTTOOLVMOPTS} ${SRCTRG8} -Xlint -Xbootclasspath/p:classesRefRef.jar Main.java - -#---------------------------------------------------------------- -# Class-Path attribute followed in extdirs or endorseddirs -#---------------------------------------------------------------- -Sys mkdir jars -Sys cp classesRefRef.jar jars/. - Warning "$javac" ${TESTTOOLVMOPTS} ${SRCTRG8} -Xlint -extdirs jars Main.java - Warning "$javac" ${TESTTOOLVMOPTS} ${SRCTRG8} -Xlint -endorseddirs jars Main.java - -#---------------------------------------------------------------- -# Bad Jar file in extdirs and endorseddirs should not be ignored -#---------------------------------------------------------------- -BadJarFile jars/classesRef.jar - Error "$javac" ${TESTTOOLVMOPTS} ${SRCTRG8} -Xlint -extdirs jars Main.java - Error "$javac" ${TESTTOOLVMOPTS} ${SRCTRG8} -Xlint -endorseddirs jars Main.java - -Cleanup - -Bottom Line diff --git a/test/langtools/tools/javac/Paths/Help.java b/test/langtools/tools/javac/Paths/Help.java new file mode 100644 index 00000000000..af1e0ff32dd --- /dev/null +++ b/test/langtools/tools/javac/Paths/Help.java @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2003, 2022, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute 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 4940642 8293877 + * @summary Check for -help and -X flags + */ + +/* + * Converted from Help.sh, originally written by Martin Buchholz + * + * For the last version of the original, Help.sh, see + * https://git.openjdk.org/jdk/blob/jdk-19%2B36/test/langtools/tools/javac/Paths/Help.sh + * + * This class provides rudimentary tests of the javac command-line help. + */ + +import java.io.PrintWriter; +import java.io.StringWriter; +import java.util.spi.ToolProvider; + +public class Help { + public static void main(String... args) throws Exception { + new Help().run(args); + } + + void run(String... args) throws Exception { + String helpText = javac("-help"); + check(helpText, + "-X ", "-J", "-classpath ", "-cp ", "-bootclasspath ", "-sourcepath "); + + String xText = javac("-X"); + check(xText, "-Xbootclasspath/p:"); + } + + void check(String text, String... options) throws Exception { + for (String opt : options) { + System.err.println("Checking '" + opt + "'"); + if (!text.contains(opt)) { + text.lines().forEach(System.err::println); + throw new Exception("Bad help output"); + } + } + } + + String javac(String... args) throws Exception { + var javac = ToolProvider.findFirst("javac") + .orElseThrow(() -> new Exception("cannot find javac")); + try (StringWriter sw = new StringWriter(); + PrintWriter pw = new PrintWriter(sw)) { + int rc = javac.run(pw, pw, args); + if (rc != 0) { + throw new Error("unexpected exit from javac: " + rc); + } + pw.flush(); + return sw.toString(); + } + } +} + diff --git a/test/langtools/tools/javac/Paths/Help.sh b/test/langtools/tools/javac/Paths/Help.sh deleted file mode 100644 index 9453622a116..00000000000 --- a/test/langtools/tools/javac/Paths/Help.sh +++ /dev/null @@ -1,69 +0,0 @@ -#!/bin/sh - -# -# Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved. -# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. -# -# This code is free software; you can redistribute it and/or modify it -# under the terms of the GNU General Public License version 2 only, as -# published by the Free Software Foundation. -# -# This code is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License -# version 2 for more details (a copy is included in the LICENSE file that -# accompanied this code). -# -# You should have received a copy of the GNU General Public License version -# 2 along with this work; if not, write to the Free Software Foundation, -# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA -# or visit www.oracle.com if you need additional information or have any -# questions. -# - -# -# @test -# @bug 4940642 -# @summary Check for -help and -X flags -# @author Martin Buchholz -# -# @run shell Help.sh - -# To run this test manually, simply do ./MineField.sh - - -. ${TESTSRC-.}/Util.sh - -set -u - -DiagnosticsInEnglishPlease - -HELP="`\"$javac\" ${TESTTOOLVMOPTS} -help 2>&1`" -XHELP="`\"$javac\" ${TESTTOOLVMOPTS} -X 2>&1`" - -#---------------------------------------------------------------- -# Standard options -#---------------------------------------------------------------- -for opt in \ - "-X " \ - "-J" \ - "-classpath " \ - "-cp " \ - "-bootclasspath " \ - "-sourcepath "; -do - case "$HELP" in *"$opt"*) ;; *) Fail "Bad help output" ;; esac -done - -#---------------------------------------------------------------- -# Non-standard options -#---------------------------------------------------------------- -for opt in \ - "-Xbootclasspath/p:"; -do - case "$XHELP" in *"$opt"*) ;; *) Fail "Bad help output" ;; esac -done - -Bottom Line diff --git a/test/langtools/tools/javac/Paths/MineField.java b/test/langtools/tools/javac/Paths/MineField.java new file mode 100644 index 00000000000..ee8ead00027 --- /dev/null +++ b/test/langtools/tools/javac/Paths/MineField.java @@ -0,0 +1,352 @@ +/* + * Copyright (c) 2003, 2022, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute 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 4758537 4809833 8149599 8293877 + * @summary Test that javac and java find files in similar ways + * @library /tools/lib + * @build toolbox.ToolBox Util MineField + * @run main MineField + */ + +/* + * Converted from MineField.sh, originally written by Martin Buchholz. + * + * For the last version of the original, MineField.sh, see + * https://git.openjdk.org/jdk/blob/jdk-19%2B36/test/langtools/tools/javac/Paths/MineField.sh + * + * This class primarily tests that javac and the java launcher provide + * equivalent handling of all path-related options, like {@code -classpath}. + */ + +/* +#---------------------------------------------------------------- +# The search order for classes used by both java and javac is: +# +# -Xbootclasspath/p: +# -endorseddirs or -Djava.endorsed.dirs= (search for jar/zip only) +# -bootclasspath or -Xbootclasspath: +# -Xbootclasspath/a: +# -extdirs or -Djava.ext.dirs= (search for jar/zip only) +# -classpath , -cp , env CLASSPATH= +# +# Peculiarities of the class file search: +# - Empty elements of the (user) classpath default to ".", +# while empty elements of other paths are ignored. +# - Only for the user classpath is an empty string value equivalent to "." +# - Specifying a bootclasspath on the command line obliterates any +# previous -Xbootclasspath/p: or -Xbootclasspath/a: command line flags. +# +# JDK 9 update: +# java: The java launcher does not support any of the following: +# * -Xbootclasspath/p: -Xbootclasspath: +# * -endorseddirs -Djava.endorsed.dirs +# * -extdirs -Djava.ext.dirs +# All test cases exercising these features have been removed. +# javac: The following features are only supported when compiling +# for older releases: +# * -Xbootclasspath/p: -Xbootclasspath: -bootclasspath -Xbootclasspath/a: +# * -endorseddirs -Djava.endorsed.dirs +# * -extdirs -Djava.ext.dirs +# All test cases exercising these features have been modified to +# use -source 8 -target 8. In addition, javac test cases involving +# use of the runtime properties java.endorsed.dirs and java.extdirs +# (by means of -J-Dname=value) have been removed. +# Although the primary purpose of the test cases in this file is to +# compare javac and java behavior, some tests remain for javac for +# which there is no java equivalent. However, the cases remain as useful +# test cases for javac handling of the paths involved. + */ + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; + +public class MineField extends Util { + public static void main(String... args) throws Exception { + new MineField().run(args); + } + + void run(String... args) throws Exception{ + setup(); + tests(); + cleanup(); + bottomLine(); + } + + void cleanup() throws IOException { + deleteFiles("GooSrc", "GooJar", "GooZip", "GooClass"); + deleteFiles("BadSrc", "BadJar", "BadZip", "BadClass"); + deleteFiles("OneDir", "Main.java", "MANIFEST.MF"); + deleteFiles(listFiles(Path.of("."), "*.class")); + deleteFiles("java-lang.jar"); + } + + /** + * "Prepare the minefield". + */ + void setup() throws Exception { + cleanup(); + + tb.createDirectories("GooSrc", "GooJar", "GooZip", "GooClass"); + tb.createDirectories("BadSrc", "BadJar", "BadZip", "BadClass"); + + Files.writeString(Path.of("Lib.java"), + "public class Lib {public static void f(){}}"); + javac("Lib.java"); + jar("cf", "GooJar/Lib.jar", "Lib.class"); + jar("cf", "GooZip/Lib.zip", "Lib.class"); + tb.moveFile("Lib.class", "GooClass/."); + tb.moveFile("Lib.java", "GooSrc/."); + checkFiles("GooZip/Lib.zip", "GooJar/Lib.jar", "GooSrc/Lib.java"); + + Files.writeString(Path.of("Lib.java"), + "public class Lib {/* Bad */}"); + javac("Lib.java"); + jar("cf", "BadJar/Lib.jar", "Lib.class"); + jar("cf", "BadZip/Lib.zip", "Lib.class"); + tb.moveFile("Lib.class", "BadClass/."); + tb.moveFile("Lib.java", "BadSrc/."); + checkFiles("BadZip/Lib.zip", "BadJar/Lib.jar", "BadSrc/Lib.java"); + + Files.writeString(Path.of("Main.java"), + "public class Main {public static void main(String[] a) {Lib.f();}}"); + Path libModules = javaHome.resolve("lib").resolve("modules"); + if (Files.isReadable(libModules)) { + jimage("extract", "--dir", "modules", libModules.toString()); + jar("cf", "java-lang.jar", "-C", "modules/java.base", "java/lang"); + deleteFiles("modules"); + } else { + Path modules = javaHome.resolve("modules"); + if (Files.isDirectory(modules)) { + jar("cf", "java-lang.jar", "-C", modules.resolve("java.base").toString(), "java/lang"); + } else { + throw new Exception("Cannot create java-lang.jar"); + } + } + } + + void tests() throws Exception { + + //---------------------------------------------------------------- + // Verify that javac class search order is the same as java's + //---------------------------------------------------------------- + + expectFail(JAVAC, """ + -source 8 -target 8 + -Xbootclasspath/p:GooClass + -bootclasspath java-lang.jar${PS}BadZip/Lib.zip + Main.java"""); + + expectPass(JAVAC, """ + -source 8 -target 8 + -Xbootclasspath/p:BadClass${PS}GooClass + -bootclasspath java-lang.jar${PS}GooZip/Lib.zip${PS}BadClass + Main.java"""); + + expectPass(JAVAC, """ + -source 8 -target 8 + -Xbootclasspath/p:BadJar/Lib.jar + -Xbootclasspath:java-lang.jar${PS}GooClass + Main.java"""); + + //---------------------------------------------------------------- + + expectFail(JAVAC, """ + -source 8 -target 8 + -bootclasspath java-lang.jar${PS}GooZip/Lib.zip + -Xbootclasspath/p:BadClass + Main.java"""); + + expectPass(JAVAC, """ + -source 8 -target 8 + -bootclasspath java-lang.jar${PS}BadZip/Lib.zip + -Xbootclasspath/p:GooClass${PS}BadJar/Lib.jar + Main.java"""); + + //---------------------------------------------------------------- + + expectFail(JAVAC, """ + -source 8 -target 8 + -Xbootclasspath/p:BadClass + -Xbootclasspath/a:GooClass + Main.java"""); + + expectPass(JAVAC, """ + -source 8 -target 8 + -Xbootclasspath/p:GooClass${PS}BadClass + -Xbootclasspath/a:BadClass + Main.java"""); + + expectPass(JAVA, """ + -Xbootclasspath/a:GooClass + Main"""); + + //---------------------------------------------------------------- + + expectFail(JAVAC, """ + -source 8 -target 8 + -Xbootclasspath/p:GooClass + -Xbootclasspath:BadClass${PS}java-lang.jar + -Xbootclasspath/a:GooClass + Main.java"""); + + expectPass(JAVAC, """ + -source 8 -target 8 + -Xbootclasspath/p:BadClass + -Xbootclasspath:GooClass${PS}BadClass${PS}java-lang.jar + -Xbootclasspath/a:BadClass + Main.java"""); + + //---------------------------------------------------------------- + + expectPass(JAVAC, """ + -source 8 -target 8 + -endorseddirs BadClass${PS}GooZip${PS}BadJar + -Xbootclasspath:"BadClass${PS}java-lang.jar + Main.java"""); + + expectPass(JAVAC, """ + -source 8 -target 8 + -Djava.endorsed.dirs=BadClass${PS}GooZip${PS}BadJar + -Xbootclasspath:BadClass${PS}java-lang.jar + Main.java"""); + + //---------------------------------------------------------------- + + expectFail(JAVAC, """ + -source 8 -target 8 + -Xbootclasspath/a:BadClass + -extdirs GooZip + Main.java"""); + + expectPass(JAVAC, """ + -source 8 -target 8 + -Xbootclasspath/a:GooClass${PS}BadClass + -extdirs BadZip + Main.java"""); + + //---------------------------------------------------------------- + + expectFail(JAVAC, """ + -source 8 -target 8 + -extdirs GooClass${PS}BadZip + -cp GooZip/Lib.zip + Main.java"""); + + expectPass(JAVAC, """ + -source 8 -target 8 + -extdirs BadClass${PS}GooZip${PS}BadJar + -cp BadZip/Lib.zip + Main.java"""); + + expectPass(JAVAC, """ + -source 8 -target 8 + -Djava.ext.dirs=GooZip${PS}BadJar + -classpath BadZip/Lib.zip + Main.java"""); + + //---------------------------------------------------------------- + + expectFail(JAVAC, "-classpath BadClass${PS}GooClass Main.java"); + expectPass(JAVAC, "-classpath GooClass${PS}BadClass Main.java"); + expectFail(JAVA, "-classpath BadClass${PS}GooClass${PS}. Main"); + expectPass(JAVA, "-classpath GooClass${PS}BadClass${PS}. Main"); + + expectFail(JAVAC, "-cp BadJar/Lib.jar${PS}GooZip/Lib.zip Main.java"); + expectPass(JAVAC, "-cp GooJar/Lib.jar${PS}BadZip/Lib.zip Main.java"); + expectFail(JAVA, "-cp BadJar/Lib.jar${PS}${PS}GooZip/Lib.zip Main"); + expectPass(JAVA, "-cp GooJar/Lib.jar${PS}${PS}BadZip/Lib.zip Main"); + + //---------------------------------------------------------------- + + expectFail(classpath("BadZip/Lib.zip${PS}GooJar/Lib.jar"), JAVAC,"Main.java"); + expectPass(classpath("GooZip/Lib.zip${PS}BadJar/Lib.jar"), JAVAC, "Main.java"); + expectFail(classpath("${PS}BadZip/Lib.zip${PS}GooJar/Lib.jar"), JAVA, "Main"); + expectPass(classpath("${PS}GooZip/Lib.zip${PS}BadJar/Lib.jar"), JAVA, "Main"); + + //---------------------------------------------------------------- + // Check behavior of empty paths and empty path elements + //---------------------------------------------------------------- + + Path GooClass = Path.of("GooClass"); + Path GooJar = Path.of("GooJar"); + + expectFail(GooClass, JAVAC, "-cp .. ../Main.java"); + expectFail(GooClass, JAVA, "-cp .. Main"); + + // Unspecified classpath defaults to "." + Path OneDir = Path.of("OneDir"); + tb.createDirectories(OneDir); + tb.copyFile(Path.of("Main.java"), OneDir); + tb.copyFile(GooClass.resolve("Lib.class"), OneDir); + expectPass(OneDir, JAVAC, "Main.java"); + expectPass(OneDir, JAVA, "Main"); + + // Empty classpath elements mean "." + expectPass(GooClass, JAVAC, "-cp ${PS}.. ../Main.java"); + expectPass(GooClass, JAVA, "-cp ${PS}.. Main"); + + expectPass(GooClass, JAVAC, "-cp ..${PS} ../Main.java"); + expectPass(GooClass, JAVA, "-cp ..${PS} Main"); + + expectPass(GooClass, JAVAC, "-cp ..${PS}${PS}/xyzzy ../Main.java"); + expectPass(GooClass, JAVA, "-cp ..${PS}${PS}/xyzzy Main"); + + // All other empty path elements are ignored. + + // note presence of empty arg in this invocation + expectFail(GooJar, null, JAVAC, "-source", "8", "-target", "8", "-extdirs", "", "-cp", "..", "../Main.java"); + + expectFail(GooJar, JAVAC, "-source 8 -target 8 -extdirs ${PS} -cp .. ../Main.java"); + expectFail(GooJar, JAVAC, "-source 8 -target 8 -Djava.ext.dirs=${PS} -cp .. ../Main.java"); + + expectPass(GooJar, JAVAC, "-source 8 -target 8 -extdirs . -cp .. ../Main.java"); + expectPass(GooJar, JAVAC, "-source 8 -target 8 -Djava.ext.dirs=. -cp .. ../Main.java"); + + expectFail(GooJar, JAVAC, "-source 8 -target 8 -Djava.endorsed.dirs= -cp .. ../Main.java"); + + expectFail(GooJar, JAVAC, "-source 8 -target 8 -endorseddirs ${PS} -cp .. ../Main.java"); + + expectPass(GooJar, JAVAC, "-source 8 -target 8 -Djava.endorsed.dirs=. -cp .. ../Main.java"); + + expectFail(GooClass, JAVAC, "-source 8 -target 8 -Xbootclasspath/p: -cp .. ../Main.java"); + + expectPass(GooClass, JAVAC, "-source 8 -target 8 -Xbootclasspath/p:. -cp .. ../Main.java"); + + expectFail(GooClass, JAVAC, "-source 8 -target 8 -Xbootclasspath:../java-lang.jar -cp .. ../Main.java"); + + expectPass(GooClass, JAVAC, "-source 8 -target 8 -Xbootclasspath:../java-lang.jar${PS}. -cp .. ../Main.java"); + + expectFail(GooClass, JAVAC, "-source 8 -target 8 -Xbootclasspath/a: -cp .. ../Main.java"); + expectFail(GooClass, JAVA, "-Xbootclasspath/a: -cp .. Main"); + + expectPass(GooClass, JAVAC, "-source 8 -target 8 -Xbootclasspath/a:. -cp .. ../Main.java"); + expectPass(GooClass, JAVA, "-Xbootclasspath/a:. -cp .. Main"); + + } + + +} diff --git a/test/langtools/tools/javac/Paths/MineField.sh b/test/langtools/tools/javac/Paths/MineField.sh deleted file mode 100644 index cfacc28fbcb..00000000000 --- a/test/langtools/tools/javac/Paths/MineField.sh +++ /dev/null @@ -1,277 +0,0 @@ -#!/bin/sh - -# -# Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved. -# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. -# -# This code is free software; you can redistribute 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 4758537 4809833 8149599 -# @summary Test that javac and java find files in similar ways -# @author Martin Buchholz -# -# @run shell/timeout=600 MineField.sh - -# To run this test manually, simply do ./MineField.sh - -#---------------------------------------------------------------- -# The search order for classes used by both java and javac is: -# -# -Xbootclasspath/p: -# -endorseddirs or -Djava.endorsed.dirs= (search for jar/zip only) -# -bootclasspath or -Xbootclasspath: -# -Xbootclasspath/a: -# -extdirs or -Djava.ext.dirs= (search for jar/zip only) -# -classpath , -cp , env CLASSPATH= -# -# Peculiarities of the class file search: -# - Empty elements of the (user) classpath default to ".", -# while empty elements of other paths are ignored. -# - Only for the user classpath is an empty string value equivalent to "." -# - Specifying a bootclasspath on the command line obliterates any -# previous -Xbootclasspath/p: or -Xbootclasspath/a: command line flags. -# -# JDK 9 update: -# java: The java launcher does not support any of the following: -# * -Xbootclasspath/p: -Xbootclasspath: -# * -endorseddirs -Djava.endorsed.dirs -# * -extdirs -Djava.ext.dirs -# All test cases exercising these features have been removed. -# javac: The following features are only supported when compiling -# for older releases: -# * -Xbootclasspath/p: -Xbootclasspath: -bootclasspath -Xbootclasspath/a: -# * -endorseddirs -Djava.endorsed.dirs -# * -extdirs -Djava.ext.dirs -# All test cases exercising these features have been modified to -# use -source 8 -target 8. In addition, javac test cases involving -# use of the runtime properties java.endorsed.dirs and java.extdirs -# (by means of -J-Dname=value) have been removed. -# Although the primary purpose of the test cases in this file is to -# compare javac and java behavior, some tests remain for javac for -# which there is no java equivalent. However, the cases remain as useful -# test cases for javac handling of the paths involved. - -#---------------------------------------------------------------- - -. ${TESTSRC-.}/Util.sh - -set -u - -#---------------------------------------------------------------- -# Prepare the "Minefield" -#---------------------------------------------------------------- -Cleanup() { - Sys rm -rf GooSrc GooJar GooZip GooClass - Sys rm -rf BadSrc BadJar BadZip BadClass - Sys rm -rf OneDir *.class Main.java MANIFEST.MF - Sys rm -f java-lang.jar -} - -Cleanup -Sys mkdir GooSrc GooJar GooZip GooClass -Sys mkdir BadSrc BadJar BadZip BadClass - -echo 'public class Lib {public static void f(){}}' > Lib.java -Sys "$javac" ${TESTTOOLVMOPTS} Lib.java -Sys "$jar" cf GooJar/Lib.jar Lib.class -Sys "$jar" cf GooZip/Lib.zip Lib.class -Sys mv Lib.class GooClass/. -Sys mv Lib.java GooSrc/. -CheckFiles GooZip/Lib.zip GooJar/Lib.jar GooSrc/Lib.java - -echo 'public class Lib {/* Bad */}' > Lib.java -Sys "$javac" ${TESTTOOLVMOPTS} Lib.java -Sys "$jar" cf BadJar/Lib.jar Lib.class -Sys "$jar" cf BadZip/Lib.zip Lib.class -Sys mv Lib.class BadClass/. -Sys mv Lib.java BadSrc/. -CheckFiles BadZip/Lib.zip BadJar/Lib.jar BadSrc/Lib.java - -echo 'public class Main {public static void main(String[] a) {Lib.f();}}' > Main.java - -# Create a jar file that is good enough to put on the javac boot class path (i.e. contains java.lang.**) -if [ -r ${TESTJAVA}/lib/modules ]; then - Sys "$jimage" extract --dir modules ${TESTJAVA}/lib/modules - Sys "$jar" cf java-lang.jar -C modules/java.base java/lang - Sys rm -rf modules -elif [ -d ${TESTJAVA}/modules ]; then - Sys "$jar" cf java-lang.jar -C ${TESTJAVA}/modules/java.base java/lang -else - echo 'cannot create java-lang.jar' ; exit 1 -fi - -#---------------------------------------------------------------- -# Verify that javac class search order is the same as java's -#---------------------------------------------------------------- -Failure "$javac" -source 8 -target 8 ${TESTTOOLVMOPTS} \ - -Xbootclasspath/p:"GooClass" \ - -bootclasspath "java-lang.jar${PS}BadZip/Lib.zip" \ - Main.java -Success "$javac" -source 8 -target 8 ${TESTTOOLVMOPTS} \ - -Xbootclasspath/p:"BadClass${PS}GooClass" \ - -bootclasspath "java-lang.jar${PS}GooZip/Lib.zip${PS}BadClass" \ - Main.java -Success "$javac" -source 8 -target 8 ${TESTTOOLVMOPTS} \ - -Xbootclasspath/p:"BadJar/Lib.jar" \ - -Xbootclasspath:"java-lang.jar${PS}GooClass" \ - Main.java - -#---------------------------------------------------------------- -Failure "$javac" -source 8 -target 8 ${TESTTOOLVMOPTS} \ - -bootclasspath "java-lang.jar${PS}GooZip/Lib.zip" \ - -Xbootclasspath/p:"BadClass" \ - Main.java -Success "$javac" -source 8 -target 8 ${TESTTOOLVMOPTS} \ - -bootclasspath "java-lang.jar${PS}BadZip/Lib.zip" \ - -Xbootclasspath/p:"GooClass${PS}BadJar/Lib.jar" \ - Main.java - -#---------------------------------------------------------------- -Failure "$javac" -source 8 -target 8 ${TESTTOOLVMOPTS} \ - -Xbootclasspath/p:"BadClass" \ - -Xbootclasspath/a:"GooClass" \ - Main.java -Success "$javac" -source 8 -target 8 ${TESTTOOLVMOPTS} \ - -Xbootclasspath/p:"GooClass${PS}BadClass" \ - -Xbootclasspath/a:"BadClass" \ - Main.java -Success "$java" ${TESTVMOPTS} \ - -Xbootclasspath/a:"GooClass" \ - Main - -#---------------------------------------------------------------- -Failure "$javac" -source 8 -target 8 ${TESTTOOLVMOPTS} \ - -Xbootclasspath/p:"GooClass" \ - -Xbootclasspath:"BadClass${PS}java-lang.jar" \ - -Xbootclasspath/a:"GooClass" \ - Main.java -Success "$javac" -source 8 -target 8 ${TESTTOOLVMOPTS} \ - -Xbootclasspath/p:"BadClass" \ - -Xbootclasspath:"GooClass${PS}BadClass${PS}java-lang.jar" \ - -Xbootclasspath/a:"BadClass" \ - Main.java - -#---------------------------------------------------------------- -Success "$javac" -source 8 -target 8 ${TESTTOOLVMOPTS} \ - -endorseddirs "BadClass${PS}GooZip${PS}BadJar" \ - -Xbootclasspath:"BadClass${PS}java-lang.jar" \ - Main.java -Success "$javac" -source 8 -target 8 ${TESTTOOLVMOPTS} \ - -Djava.endorsed.dirs="BadClass${PS}GooZip${PS}BadJar" \ - -Xbootclasspath:"BadClass${PS}java-lang.jar" \ - Main.java - -#---------------------------------------------------------------- -Failure "$javac" -source 8 -target 8 ${TESTTOOLVMOPTS} \ - -Xbootclasspath/a:"BadClass" \ - -extdirs "GooZip" \ - Main.java -Success "$javac" -source 8 -target 8 ${TESTTOOLVMOPTS} \ - -Xbootclasspath/a:"GooClass${PS}BadClass" \ - -extdirs "BadZip" \ - Main.java - -#---------------------------------------------------------------- -Failure "$javac" -source 8 -target 8 ${TESTTOOLVMOPTS} \ - -extdirs "GooClass${PS}BadZip" \ - -cp "GooZip/Lib.zip" \ - Main.java -Success "$javac" -source 8 -target 8 ${TESTTOOLVMOPTS} \ - -extdirs "BadClass${PS}GooZip${PS}BadJar" \ - -cp "BadZip/Lib.zip" \ - Main.java -Success "$javac" -source 8 -target 8 ${TESTTOOLVMOPTS} \ - -Djava.ext.dirs="GooZip${PS}BadJar" \ - -classpath "BadZip/Lib.zip" \ - Main.java - -#---------------------------------------------------------------- -Failure "$javac" ${TESTTOOLVMOPTS} -classpath "BadClass${PS}GooClass" Main.java -Success "$javac" ${TESTTOOLVMOPTS} -classpath "GooClass${PS}BadClass" Main.java -Failure "$java" ${TESTVMOPTS} -classpath "BadClass${PS}GooClass${PS}." Main -Success "$java" ${TESTVMOPTS} -classpath "GooClass${PS}BadClass${PS}." Main - -Failure "$javac" ${TESTTOOLVMOPTS} -cp "BadJar/Lib.jar${PS}GooZip/Lib.zip" Main.java -Success "$javac" ${TESTTOOLVMOPTS} -cp "GooJar/Lib.jar${PS}BadZip/Lib.zip" Main.java -Failure "$java" ${TESTVMOPTS} -cp "BadJar/Lib.jar${PS}${PS}GooZip/Lib.zip" Main -Success "$java" ${TESTVMOPTS} -cp "GooJar/Lib.jar${PS}${PS}BadZip/Lib.zip" Main - -Failure env CLASSPATH="BadZip/Lib.zip${PS}GooJar/Lib.jar" "$javac" ${TESTTOOLVMOPTS} Main.java -Success env CLASSPATH="GooZip/Lib.zip${PS}BadJar/Lib.jar" "$javac" ${TESTTOOLVMOPTS} Main.java -Failure env CLASSPATH="${PS}BadZip/Lib.zip${PS}GooJar/Lib.jar" "$java" ${TESTVMOPTS} Main -Success env CLASSPATH="${PS}GooZip/Lib.zip${PS}BadJar/Lib.jar" "$java" ${TESTVMOPTS} Main - -#---------------------------------------------------------------- -# Check behavior of empty paths and empty path elements -#---------------------------------------------------------------- -In() { cd "$1"; shift; "$@"; cd ..; } - -In GooClass Failure "$javac" ${TESTTOOLVMOPTS} -cp ".." ../Main.java -In GooClass Failure "$java" ${TESTVMOPTS} -cp ".." Main - -# Unspecified classpath defaults to "." -Sys mkdir OneDir; Sys cp Main.java GooClass/Lib.class OneDir/. -In OneDir Success "$javac" ${TESTTOOLVMOPTS} Main.java -In OneDir Success "$java" ${TESTVMOPTS} Main - -# Empty classpath elements mean "." -In GooClass Success "$javac" ${TESTTOOLVMOPTS} -cp "${PS}.." ../Main.java -In GooClass Success "$java" ${TESTVMOPTS} -cp "${PS}.." Main - -In GooClass Success "$javac" ${TESTTOOLVMOPTS} -cp "..${PS}" ../Main.java -In GooClass Success "$java" ${TESTVMOPTS} -cp "..${PS}" Main - -In GooClass Success "$javac" ${TESTTOOLVMOPTS} -cp "..${PS}${PS}/xyzzy" ../Main.java -In GooClass Success "$java" ${TESTVMOPTS} -cp "..${PS}${PS}/xyzzy" Main - -# All other empty path elements are ignored. -In GooJar Failure "$javac" -source 8 -target 8 ${TESTTOOLVMOPTS} -extdirs "" -cp ".." ../Main.java - -In GooJar Failure "$javac" -source 8 -targt 8 ${TESTTOOLVMOPTS} -extdirs "${PS}" -cp ".." ../Main.java -In GooJar Failure "$javac" -source 8 -target 8 ${TESTTOOLVMOPTS} -Djava.ext.dirs="${PS}" -cp ".." ../Main.java - -In GooJar Success "$javac" -source 8 -target 8 ${TESTTOOLVMOPTS} -extdirs "." -cp ".." ../Main.java -In GooJar Success "$javac" -source 8 -target 8 ${TESTTOOLVMOPTS} -Djava.ext.dirs="." -cp ".." ../Main.java - -In GooJar Failure "$javac" -source 8 -target 8 ${TESTTOOLVMOPTS} -Djava.endorsed.dirs="" -cp ".." ../Main.java - -In GooJar Failure "$javac" -source 8 -target 8 ${TESTTOOLVMOPTS} -endorseddirs "${PS}" -cp ".." ../Main.java - -In GooJar Success "$javac" -source 8 -target 8 ${TESTTOOLVMOPTS} -Djava.endorsed.dirs="." -cp ".." ../Main.java - -In GooClass Failure "$javac" -source 8 -target 8 ${TESTTOOLVMOPTS} -Xbootclasspath/p: -cp ".." ../Main.java - -In GooClass Success "$javac" -source 8 -target 8 ${TESTTOOLVMOPTS} -Xbootclasspath/p:. -cp ".." ../Main.java - -In GooClass Failure "$javac" -source 8 -target 8 ${TESTTOOLVMOPTS} -Xbootclasspath:"../java-lang.jar" -cp ".." ../Main.java - -In GooClass Success "$javac" -source 8 -target 8 ${TESTTOOLVMOPTS} -Xbootclasspath:"../java-lang.jar${PS}." -cp ".." ../Main.java - -In GooClass Failure "$javac" -source 8 -target 8 ${TESTTOOLVMOPTS} -Xbootclasspath/a: -cp ".." ../Main.java -In GooClass Failure "$java" ${TESTVMOPTS} -Xbootclasspath/a: -cp ".." Main - -In GooClass Success "$javac" -source 8 -target 8 ${TESTTOOLVMOPTS} -Xbootclasspath/a:. -cp ".." ../Main.java -In GooClass Success "$java" ${TESTVMOPTS} -Xbootclasspath/a:. -cp ".." Main - -Cleanup - -Bottom Line diff --git a/test/langtools/tools/javac/Paths/Util.java b/test/langtools/tools/javac/Paths/Util.java new file mode 100644 index 00000000000..ea0d0adc98b --- /dev/null +++ b/test/langtools/tools/javac/Paths/Util.java @@ -0,0 +1,560 @@ +/* + * Copyright (c) 2014, 2022, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.io.File; +import java.io.IOException; +import java.io.PrintStream; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.nio.file.DirectoryStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; +import java.util.spi.ToolProvider; + +import toolbox.ToolBox; + +/** + * Utility methods for use by tests in the `Paths` directory. + */ +class Util { + + ToolBox tb = new ToolBox(); + PrintStream out = tb.out; + + Path javaHome = Path.of(System.getProperty("java.home")); + String PS = File.pathSeparator; + Path curDir = Path.of("."); + + static final String JAR = "jar"; + static final String JAVA = "java"; + static final String JAVAC = "javac"; + static final String JIMAGE = "jimage"; + + /** The number of test-case failures. */ + int failCount = 0; + /** The number of test-case passes. */ + int passCount = 0; + /** A map recording how often each tool is executed in a separate process. */ + Map execCounts = new TreeMap<>(); + /** A map recording how often each tool is invoked via its ToolProvider API. */ + Map toolCounts = new TreeMap<>(); + + /** + * Reports a summary of the overall test statistics, and throws an exception + * if any test cases failed. + * + * @throws Exception if any test cases failed + */ + void bottomLine() throws Exception { + out.println(); + out.println("-- Summary --"); + out.println("Passed: " + passCount); + out.println("Failed: " + failCount); + out.println("exec: " + execCounts); + out.println("tool: " + toolCounts); + + if (failCount > 0) { + throw new Exception(failCount + " tests failed"); + } + } + + /** + * The result of executing a tool, either in a separate process, or via its ToolProvider API. + * + * @param exitCode the exit code from the tool: 0 for success + * @param out the output from the tool + */ + record Result(int exitCode, String out) { } + + /** + * Executes a tool with given arguments and verifies that it passes. + * + * @param command the name of a JDK tool: java, javac or jar + * @param args a string containing whitespace separated arguments + * @throws Exception if there was an issue trying to execute the tool + * @see #passCount + * @see #failCount + * @see #splitArgs(String) + */ + void expectPass(String command, String args) throws Exception { + expectPass(null, null, command, splitArgs(args)); + } + + /** + * Executes a tool in a specific directory with given arguments and verifies that it passes. + * In order to set the directory, the tool will be executed in a separate process. + * + * @param dir the directory + * @param command the name of a JDK tool: java, javac or jar + * @param args a string containing whitespace separated arguments + * @throws Exception if there was an issue trying to execute the tool + * @see #passCount + * @see #failCount + * @see #splitArgs(String) + */ + void expectPass(Path dir, String command, String args) throws Exception { + expectPass(dir, null, command, splitArgs(args)); + } + + /** + * Executes a tool with additional env variables with given arguments and verifies that it passes. + * In order to set the env variables, the tool will be executed in a separate process. + * Note that any value of {@code CLASSPATH} inherited from this process will always be removed. + * + * @param env the additional env variables + * @param command the name of a JDK tool: java, javac or jar + * @param args a string containing whitespace separated arguments + * @throws Exception if there was an issue trying to execute the tool + * @see #passCount + * @see #failCount + * @see #splitArgs(String) + */ + void expectPass(Map env, String command, String args) throws Exception { + expectPass(null, env, command, splitArgs(args)); + } + + /** + * Executes a tool in a given directory with additional env variables with given arguments + * and verifies that it passes. + * In order to set any directory and env variables, the tool will be executed in a separate process. + * Note that any value of {@code CLASSPATH} inherited from this process will always be removed. + * + * @param dir the directory, or {@code null} + * @param env the additional env variables, or {@code null} + * @param command the name of a JDK tool: java, javac or jar + * @param args the arguments + * @throws Exception if there was an issue trying to execute the tool + * @see #passCount + * @see #failCount + */ + void expectPass(Path dir, Map env, String command, String... args) throws Exception { + Result result = switch (command) { + case JAR -> jar(args); + case JAVAC -> javac(dir, env, args); + case JAVA -> java(dir, env, args); + default -> throw new Exception("unknown command: " + command); + }; + + if (result.exitCode == 0) { + out.println("PASS: test passed as expected"); + passCount++; + } else { + out.println("FAIL: test failed unexpectedly"); + failCount++; + } + } + + /** + * Executes a tool with given arguments and verifies that it fails. + * + * @param command the name of a JDK tool: java, javac or jar + * @param args a string containing whitespace separated arguments + * @throws Exception if there was an issue trying to execute the tool + * @see #passCount + * @see #failCount + * @see #splitArgs(String) + */ + void expectFail(String command, String args) throws Exception { + expectFail(null, null, command, splitArgs(args)); + } + + /** + * Executes a tool in a specific directory with given arguments and verifies that it fails. + * In order to set the directory, the tool will be executed in a separate process. + * + * @param dir the directory + * @param command the name of a JDK tool: java, javac or jar + * @param args a string containing whitespace separated arguments + * @throws Exception if there was an issue trying to execute the tool + * @see #passCount + * @see #failCount + * @see #splitArgs(String) + */ + void expectFail(Path dir, String command, String args) throws Exception { + expectFail(dir, null, command, splitArgs(args)); + } + + /** + * Executes a tool with additional env variables with given arguments and verifies that it passes. + * In order to set the env variables, the tool will be executed in a separate process. + * Note that any value of {@code CLASSPATH} inherited from this process will always be removed. + * + * @param env the additional env variables + * @param command the name of a JDK tool: java, javac or jar + * @param args a string containing whitespace separated arguments + * @throws Exception if there was an issue trying to execute the tool + * @see #passCount + * @see #failCount + * @see #splitArgs(String) + */ + void expectFail(Map env, String command, String args) throws Exception { + expectFail(null, env, command, splitArgs(args)); + } + + /** + * Executes a tool in a given directory with additional env variables with given arguments + * and verifies that it passes. + * In order to set any directory and env variables, the tool will be executed in a separate process. + * Note that any value of {@code CLASSPATH} inherited from this process will always be removed. + * + * @param dir the directory, or {@code null} + * @param env the additional env variables, or {@code null} + * @param command the name of a JDK tool: java, javac or jar + * @param args the arguments + * @throws Exception if there was an issue trying to execute the tool + * @see #passCount + * @see #failCount + */ + void expectFail(Path dir, Map env, String command, String... args) throws Exception { + Result result = switch (command) { + case JAR -> jar(args); + case JAVAC -> javac(dir, env, args); + case JAVA -> java(dir, env, args); + default -> throw new Exception("unknown command: " + command); + }; + + if (result.exitCode == 0) { + out.println("FAIL: test passed unexpectedly"); + failCount++; + } else { + out.println("PASS: failed as expected"); + passCount++; + } + } + + /** + * Splits a string into a list of strings that were separated by whitespace. + * Leading and trailing whitespace is removed. + * The character sequence {@code ${PS}} is replaced by the platform path separator. + * Note, quotes are not supported, and so there is no support for embedded whitespace + * or empty strings in the output. + * + * @param args a string of tokens separated by whitespace + * @return an array of the tokens that were separated by whitespace + */ + String[] splitArgs(String args) { + return args.trim() + .replace("${PS}", PS) + .split("\\s+"); + } + + /** + * Executes {@code javac} using its ToolProvider API. + * + * @param args the arguments + * @return an object containing the output and exit code from the tool + * @throws Exception if there is an issue executing the tool + */ + Result javac(String... args) throws Exception { + return runTool(JAVAC, args); + } + + /** + * Executes {@code javac} in either a separate process or using its ToolProvider API. + * The ToolProvider API is used if the directory and env parameters are {@code null}, + * and if the arguments definitely do not use "classpath wildcards", which are + * only supported when the tool is invoked by the launcher. + * + * @param dir the directory, or {@code null} + * @param env any additional environment variables, or {@code null} + * @param args the arguments + * @return an object containing the output and exit code from the tool + * @throws Exception if there is an issue executing the tool + */ + Result javac(Path dir, Map env, String... args) throws Exception { + return (env != null || dir != null || hasWildcardClassPath(args)) + ? execTool(dir, env, JAVAC, args) + : runTool(JAVAC, args); + } + + /** + * {@return true if the arguments may contain a classpath option using a "classpath wildcard"} + * + * The result is {@code true} if there is any form of a classpath option whose value contains {@code *}. + * Note: this may include "false positives", where the {@code *} is not at the end of + * any element in the path, such as when the character is part of the filename. + * However, in context, the approximation is safe, and just means that we may sometimes + * execute javac in a separate process when it would be sufficient to use its ToolProvider API. + * + * A more refined implementation could split apart the path elements and looking for + * an element that is {@code *} or which ends in {@code *}. + * + * @param args the arguments to be checked + */ + private boolean hasWildcardClassPath(String... args) { + for (int i = 0; i < args.length; i++) { + String arg = args[i]; + switch (arg) { + case "-classpath", "--class-path", "-cp" -> { + if (i + 1 < args.length && args[i + 1].contains("*")) { + return true; + } + } + default -> { + if (arg.startsWith("--class-path=") && arg.contains("*")) { + return true; + } + } + } + } + return false; + } + + /** + * Executes {@code jar} using its ToolProvider API. + * + * @param args the arguments + * @return an object containing the output and exit code from the tool + * @throws Exception if there is an issue executing the tool + */ + Result jar(String... args) throws Exception { + return runTool(JAR, args); + } + + /** + * Executes {@code jimage} using its ToolProvider API. + * + * @param args the arguments + * @return an object containing the output and exit code from the tool + * @throws Exception if there is an issue executing the tool + */ + Result jimage(String... args) throws Exception { + return execTool(null, null, JIMAGE, args); + } + + /** + * Executes {@code java} in a separate process. + * + * @param dir the directory, or {@code null} + * @param env any additional environment variables, or {@code null} + * @param args the arguments + * @return an object containing the output and exit code from the launcher + * @throws Exception if there is an issue executing the tool + */ + Result java(Path dir, Map env, String... args) throws Exception { + return execTool(dir, env, JAVA, args); + } + + /** + * Runs a tool using its ToolProvider API. + * + * @param args the arguments + * @return an object containing the output and exit code from the launcher + * @throws Exception if there is an issue executing the tool + */ + Result runTool(String name, String... args) throws Exception { + out.println(name + ": " + String.join(" ", args)); + var tool = ToolProvider.findFirst(name) + .orElseThrow(() -> new Exception("cannot find " + name)); + try (StringWriter sw = new StringWriter(); + PrintWriter pw = new PrintWriter(sw)) { + int rc = tool.run(pw, pw, args); + pw.flush(); + String output = sw.toString(); + output.lines() + .forEach(l -> out.println(name + ": " + l)); + if (rc != 0) { + out.println(name + ": exit code " + rc); + } + toolCounts.put(name, toolCounts.computeIfAbsent(name, n -> 0) + 1); + return new Result(rc, output); + } + } + + /** + * Executes a tool in a separate process. + * + * Note that any value of {@code CLASSPATH} inherited from this process will always be removed. + * + * @param dir the directory, or {@code null} + * @param env any additional environment variables, or {@code null} + * @param args the arguments + * @return an object containing the output and exit code from the launcher + * @throws Exception if there is an issue executing the tool + */ + Result execTool(Path dir, Map env, String name, String... args) throws Exception { + out.print(name + ":"); + if (env != null) { + out.print(" " + env); + } + if (dir != null) { + out.print(" (" + dir + ")"); + } + out.println(" " + String.join(" ", args)); + + Path tool = javaHome.resolve("bin").resolve(name + (ToolBox.isWindows() ? ".exe" : "")); + if (!Files.exists(tool)) { + throw new Exception("cannot find " + name); + } + var cmd = new ArrayList(); + cmd.add(tool.toString()); + cmd.addAll(List.of(args)); + ProcessBuilder pb = new ProcessBuilder(cmd) + .redirectErrorStream(true); + pb.environment().remove("CLASSPATH"); // always remove default value set by jtreg + if (env != null) { + pb.environment().putAll(env); + } + if (dir != null) { + pb.directory(dir.toFile()); + } + Process p = pb.start(); + StringBuilder sb = new StringBuilder(); + try (var in = p.inputReader()) { + in.lines().forEach(l -> { + sb.append(l).append("\n"); + out.println(name + ": " + l); + }); + } + p.waitFor(); + int rc = p.exitValue(); + if (rc != 0) { + out.println(name + ": exit code " + rc); + } + execCounts.put(name, execCounts.computeIfAbsent(name, n -> 0) + 1); + return new Result(rc, sb.toString()); + } + + /** + * Checks that a series of files exist and are readable. + * + * @param paths the files + * @throws Exception if any of the files are not found or are not readable + */ + void checkFiles(String... paths) throws Exception { + for (String p : paths) { + Path path = Path.of(p); + if (!Files.isReadable(path) ) { + throw new Exception("file not found: " + path); + } + } + } + + /** + * List the files in a directory that match a "glob" pattern. + * + * @param dir the directory + * @param glob the pattern + * @return the list of files + * @throws IOException if there is a problem listing the contents of the directory + */ + List listFiles(Path dir, String glob) throws IOException { + var files = new ArrayList(); + try (DirectoryStream ds = Files.newDirectoryStream(dir, glob)) { + for (Path p : ds) { + files.add(p); + } + } + return files; + } + + /** + * Deletes a series of files. + * The files are deleted using {@link ToolBox#cleanDirectory(Path)} and + * {@code ToolBox#deleteFiles}, which together try hard to delete the files, + * even on Windows. + * + * @param paths the paths + * @throws IOException if there is a problem deleting any of the files + * @see #deleteFiles(List) + */ + void deleteFiles(String... paths) throws IOException { + deleteFiles(Arrays.stream(paths) + .map(Path::of) + .toList()); + } + + /** + * Deletes a series of files. + * The files are deleted using {@link ToolBox#cleanDirectory(Path)} and + * {@code ToolBox#deleteFiles}, which together try hard to delete the files, + * even on Windows. + * + * @param paths the paths + * @throws IOException if there is a problem deleting any of the files + */ + void deleteFiles(List paths) throws IOException { + for (Path path : paths) { + if (Files.exists(path)) { + if (Files.isDirectory(path)) { + tb.cleanDirectory(path); + } + tb.deleteFiles(path); + } + } + } + + /** + * Moves a series of files into a given directory. + * + * @param files the files + * @param dir the target directory + * @throws IOException if there is a problem moving any of the files + */ + void moveFiles(List files, Path dir) throws IOException { + for (Path p : files) { + tb.moveFile(p, dir); + } + } + + /** + * Moves a series of files into a given directory. + * + * @param files the files + * @param dir the target directory + * @throws IOException if there is a problem moving any of the files + */ + void moveFiles(List files, String dir) throws IOException { + for (String p : files) { + tb.moveFile(p, dir); + } + } + + /** + * {@return a map containing a setting for the {@code CLASSPATH} env variable} + * + * @param classpath the value for the env variable + */ + Map classpath(String classpath) { + return Map.of("CLASSPATH", classpath.replace("${PS}", PS)); + } + + /** + * Writes a file called {@code MANIFEST.MF} containing a given value for + * the {@code Class-Path} entry. + * + * @param path the value for the {@code Class-Path} entry + * @throws IOException if there is a problem writing the file + */ + void makeManifestWithClassPath(String path) throws IOException { + Files.writeString(Path.of("MANIFEST.MF"), + "Manifest-Version: 1.0\n" + + "Class-Path: " + path + "\n"); + } + +} diff --git a/test/langtools/tools/javac/Paths/Util.sh b/test/langtools/tools/javac/Paths/Util.sh deleted file mode 100644 index fa96732fea1..00000000000 --- a/test/langtools/tools/javac/Paths/Util.sh +++ /dev/null @@ -1,115 +0,0 @@ -# -# Copyright (c) 2003, 2022, Oracle and/or its affiliates. All rights reserved. -# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. -# -# This code is free software; you can redistribute 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. -# - -# Utilities for shell tests - -: ${TESTSRC=.} ${TESTCLASSES=.} - java="${TESTJAVA+${TESTJAVA}/bin/}java${EXE_SUFFIX}" - javac="${TESTJAVA+${TESTJAVA}/bin/}javac${EXE_SUFFIX}" - jar="${TESTJAVA+${TESTJAVA}/bin/}jar${EXE_SUFFIX}" -jimage="${TESTJAVA+${TESTJAVA}/bin/}jimage${EXE_SUFFIX}" - -case `uname -s` in - Windows*|CYGWIN*|MSYS*|MINGW*) - WindowsOnly() { "$@"; } - UnixOnly() { :; } - PS=";" ;; - *) - UnixOnly() { "$@"; } - WindowsOnly() { :; } - PS=":";; -esac - -failed="" -Fail() { echo "FAIL: $1"; failed="${failed}."; } - -Die() { printf "%s\n" "$*"; exit 1; } - -Sys() { - printf "%s\n" "$*"; "$@"; rc="$?"; - test "$rc" -eq 0 || Die "Command \"$*\" failed with exitValue $rc"; -} - -CheckFiles() { - for f in "$@"; do test -r "$f" || Die "File $f not found"; done -} - -Report() { - test "$#" != 2 && Die "Usage: Report success|failure rc" - - if test "$1" = "success" -a "$2" = 0; then - echo "PASS: succeeded as expected" - elif test "$1" = "failure" -a "$2" != 0; then - echo "PASS: failed as expected" - elif test "$1" = "success" -a "$2" != 0; then - Fail "test failed unexpectedly" - elif test "$1" = "failure" -a "$2" = 0; then - Fail "test succeeded unexpectedly" - else - Die "Usage: Report success|failure rc" - fi -} - -MkManifestWithClassPath() { - (echo "Manifest-Version: 1.0"; echo "Class-Path: $*") > MANIFEST.MF -} - -HorizontalRule() { - echo "-----------------------------------------------------------------" -} - -Test() { - HorizontalRule - expectedResult="$1"; shift - printf "%s\n" "$*" - "$@" - Report "$expectedResult" "$?" -} - -Failure() { Test failure "$@"; } -Success() { Test success "$@"; } - -Bottom() { - test "$#" = 1 -a "$1" = "Line" || Die "Usage: Bottom Line" - - if test -n "$failed"; then - count=`printf "%s" "$failed" | wc -c | tr -d ' '` - echo "FAIL: $count tests failed" - exit 1 - else - echo "PASS: all tests gave expected results" - exit 0 - fi -} - -BadJarFile() { - for jarfilename in "$@"; do pwd > "$jarfilename"; done -} - - -#---------------------------------------------------------------- -# Foil message localization -#---------------------------------------------------------------- -DiagnosticsInEnglishPlease() { - LANG="C" LC_ALL="C" LC_MESSAGES="C"; export LANG LC_ALL LC_MESSAGES -} diff --git a/test/langtools/tools/javac/Paths/WildcardMineField.java b/test/langtools/tools/javac/Paths/WildcardMineField.java new file mode 100644 index 00000000000..ad1362080b1 --- /dev/null +++ b/test/langtools/tools/javac/Paths/WildcardMineField.java @@ -0,0 +1,340 @@ +/* + * Copyright (c) 2005, 2022, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute 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 6268383 8172309 8293877 + * @summary Test classpath wildcards for javac and java -classpath option. + * @library /tools/lib + * @build toolbox.ToolBox Util WildcardMineField + * @run main WildcardMineField + */ + +/* + * Converted from wcMineField.sh, originally written by Martin Buchholz. + * + * For the last version of the original, wcMineField.sh, see + * https://git.openjdk.org/jdk/blob/jdk-19%2B36/test/langtools/tools/javac/Paths/wcMineField.sh + * + * This class primarily tests support for "classpath wildcards", which is a feature + * by which elements of a classpath option ending in {@code *} are expanded into + * the set of jar files found in the directory preceding the {@code *}. + * + * Note that this feature is only implemented in the launcher, even for javac, + * and so is only available when running javac via its launcher, in a separate process. + * + * Note that this feature does not affect the use of {@code *} elsewhere in any path, + * classpath or otherwise, and so this class also tests the use of {@code *} and other special + * characters (like {@code ,} and {@code ;}) in filenames. Some of these tests, + * labelled in the original code as "UnixOnly", do not apply to Windows. + * + * For information on the launcher support for the {@code -classpath} option, + * see the java man page. As of September 2022, there is no equivalent documentation + * for javac, except to say that the support is only in the native launcher for javac, + * and not in the main javac source code. + */ + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; + +import toolbox.ToolBox; + +public class WildcardMineField extends Util { + public static void main(String... args) throws Exception { + new WildcardMineField().run(args); + } + + void run(String... args) throws Exception { + setup(); + tests(); + cleanup(); + bottomLine(); + } + + void setup() throws Exception { + cleanup(); + tb.createDirectories("GooSrc", "GooJar", "GooZip", "GooClass", "GooJar/SubDir"); + tb.createDirectories("BadSrc", "BadJar", "BadZip", "BadClass"); + tb.createDirectories("SpeSrc", "SpeJar", "SpeZip", "SpeClass"); + tb.createDirectories("JarNClass", "StarJar", "MixJar"); + Files.writeString(Path.of("Lib.java"), "public class Lib {public static void f(){}}"); + Files.writeString(Path.of("Lib2.java"), "public class Lib2 {public static void g(){}}"); + Files.writeString(Path.of("Lib3.java"), "public class Lib3 {public static void h(){}}"); + javac("Lib.java", "Lib2.java", "Lib3.java"); + tb.copyFile("Lib.class", "JarNClass/."); + jar("cf", "GooJar/Lib.jar", "Lib.class"); + jar("cf", "GooJar/SubDir/Lib2.jar", "Lib2.class"); + jar("cf", "JarNClass/Lib.jar", "Lib.class"); + + jar("cf", "GooZip/Lib.zip", "Lib.class"); + tb.moveFile("Lib.class", "GooClass/."); + tb.moveFile("Lib2.class", "GooClass/."); + tb.moveFile("Lib3.class", "GooClass/."); + tb.moveFile("Lib.java", "GooSrc/."); + tb.moveFile("Lib2.java", "GooSrc/."); + tb.moveFile("Lib3.java", "GooSrc/."); + + checkFiles("GooZip/Lib.zip", "GooJar/Lib.jar", "GooSrc/Lib.java"); + checkFiles("GooSrc/Lib2.java", "GooSrc/Lib3.java", "GooJar/SubDir/Lib2.jar"); + + Files.writeString(Path.of("Spe1.java"), "public class Spe1 {public static void f(){}}"); + Files.writeString(Path.of("Spe2.java"), "public class Spe2 {public static void f(){}}"); + Files.writeString(Path.of("Spe3.java"), "public class Spe3 {public static void f(){}}"); + Files.writeString(Path.of("Spe4.java"), "public class Spe4 {public static void f(){}}"); + javac("Spe1.java", "Spe2.java", "Spe3.java", "Spe4.java"); + + if (!ToolBox.isWindows()) { + jar("cf", "SpeJar/Spe:Colon.jar", "Spe1.class"); + jar("cf", "SpeJar/Spe*wc.jar", "Spe4.class"); + checkFiles("SpeJar/Spe*wc.jar"); + + jar("cf", "StarJar/*jar.jar", "Spe2.class"); + jar("cf", "StarJar/jar*.jar", "Spe3.class"); + jar("cf", "StarJar/*jar*.jar", "Spe4.class"); + checkFiles("StarJar/*jar.jar", "StarJar/jar*.jar", "StarJar/*jar*.jar"); + } + + jar("cf", "SpeJar/Spe,Comma.jar", "Spe2.class"); + jar("cf", "SpeJar/Spe;Semi.jar", "Spe3.class"); + + jar("cf", "MixJar/mix.jAr", "Spe1.class"); + jar("cf", "MixJar/mix2.JAR", "Spe2.class"); + jar("cf", "MixJar/mix3.zip", "Spe3.class"); + jar("cf", "MixJar/.hiddenjar.jar", "Spe4.class"); + + moveFiles(listFiles(curDir, "Spe*.class"), Path.of("SpeClass/.")); + moveFiles(listFiles(curDir, "Spe*.java"), Path.of("SpeSrc/.")); + checkFiles("SpeJar/Spe,Comma.jar", "SpeJar/Spe;Semi.jar", "SpeSrc/Spe2.java", "SpeSrc/Spe3." + + "java", "SpeSrc/Spe4.java"); + checkFiles("MixJar/mix.jAr", "MixJar/mix2.JAR", "MixJar/mix3.zip", "MixJar/.hiddenjar.jar"); + + Files.writeString(Path.of("Main.java"), "public class Main {public static void main(String[] a) {Lib.f();}}"); + Files.writeString(Path.of("Main1.java"), "public class Main1 {public static void main(String[] a) {Lib2.g();}}"); + Files.writeString(Path.of("Main1b.java"), "public class Main1b {public static void main(String[] a) {Spe1.f();}}"); + Files.writeString(Path.of("Main2.java"), "public class Main2 {public static void main(String[] a) {Spe2.f();}}"); + Files.writeString(Path.of("Main3.java"), "public class Main3 {public static void main(String[] a) {Spe3.f();}}"); + Files.writeString(Path.of("Main4.java"), "public class Main4 {public static void main(String[] a) {Spe4.f();}}"); + Files.writeString(Path.of("Main5.java"), "public class Main5 {public static void main(String[] a) {Spe2.f(); Lib.f();}}"); + Files.writeString(Path.of("Main6.java"), "public class Main6 {public static void main(String[] a) {Lib3.h();}}"); + } + + void cleanup() throws IOException { + deleteFiles("GooSrc", "GooJar", "GooZip", "GooClass"); + deleteFiles("SpeSrc", "SpeJar", "SpeZip", "SpeClass"); + deleteFiles("BadSrc", "BadJar", "BadZip", "BadClass"); + deleteFiles("JarNClass", "StarJar", "MixJar", "StarDir"); + deleteFiles("OneDir", "MANIFEST.MF"); + deleteFiles(listFiles(curDir, "*.class")); + deleteFiles(listFiles(curDir, "Main*.java")); + } + + void tests() throws Exception { + if (!ToolBox.isWindows()) { + starDirTests(); + } + + /*---------------------------------------------------------------- + * Verify the basic jar file works + *----------------------------------------------------------------*/ + + // baseline test to verify it works. + expectPass(JAVAC, "-cp GooJar/Lib.jar Main.java"); + expectPass(JAVAC, "-classpath GooJar/Lib.jar Main.java"); + expectPass(JAVA, "-classpath GooJar/Lib.jar${PS}. Main"); + expectPass(JAVA, "-cp GooJar/Lib.jar${PS}. Main"); + + // basic test of one jar to be loaded + if (!ToolBox.isWindows()) { + expectPass(JAVAC, "-classpath GooJar/* Main.java"); + } + expectPass(JAVAC, "-classpath GooJar/*${PS}. Main.java"); + expectPass(JAVA, "-classpath GooJar/*${PS}. Main"); + + // in a subdir. First * should not load jars in subdirectories unless specified + expectFail(JAVAC, "-classpath GooJar/* Main1.java"); + expectFail(JAVAC, " -classpath GooJar/*${PS}. Main1.java"); + expectPass(JAVAC, "-cp GooJar/SubDir/* Main1.java"); + expectPass(JAVAC, "-classpath GooJar/SubDir/* Main1.java"); + expectPass(JAVAC, "--class-path GooJar/SubDir/* Main1.java"); + expectPass(JAVAC, "--class-path=GooJar/SubDir/* Main1.java"); + + // Same with launcher. Should not load jar in subdirectories unless specified + expectFail(JAVA, "-classpath GooJar/*${PS}. Main1"); + expectPass(JAVA, "-classpath GooJar/SubDir/*${PS}. Main1"); + expectPass(JAVA, "-cp GooJar/SubDir/*${PS}. Main1"); + + expectPass(classpath("GooJar/SubDir/*"), JAVAC, "Main1.java"); + expectPass(classpath("GooJar/SubDir/*${PS}."), JAVA, "Main1"); + + /*---------------------------------------------------------------- + * Verify the jar files in 2 directories + *----------------------------------------------------------------*/ + + expectPass(JAVAC, "-classpath GooJar/Lib.jar${PS}SpeJar/Spe,Comma.jar Main5.java"); + expectPass(JAVA, "-classpath GooJar/Lib.jar${PS}SpeJar/Spe,Comma.jar${PS}. Main5"); + + expectPass(JAVAC, "-classpath GooJar/*${PS}SpeJar/* Main5.java"); + expectPass(JAVA, "-classpath GooJar/*${PS}SpeJar/*${PS}. Main5"); + + /*---------------------------------------------------------------- + * Verify jar file and class file in same directory. + *----------------------------------------------------------------*/ + + expectPass(JAVAC, "-classpath JarNClass/*${PS} Main.java"); + expectPass(JAVA, "-classpath JarNClass/*${PS}. Main"); + + /*---------------------------------------------------------------- + * Verify these odd jar files work explicitly on classpath, kind of + * a baseline. Last one is also a test with * in a jar name. + *----------------------------------------------------------------*/ + + expectFail(JAVAC, "-classpath SpeJar/Spe:Colon.jar Main1.java"); + + expectPass(JAVAC, "-classpath SpeJar/Spe,Comma.jar Main2.java"); + expectPass(JAVA, "-classpath SpeJar/Spe,Comma.jar${PS}. Main2"); + + if (!ToolBox.isWindows()) { + expectPass(JAVAC, "-classpath SpeJar/Spe;Semi.jar Main3.java"); + expectPass(JAVA, "-classpath SpeJar/Spe;Semi.jar${PS}. Main3"); + + expectPass(JAVAC, "-classpath SpeJar/Spe*wc.jar Main4.java"); + expectPass(JAVA, "-classpath SpeJar/Spe*wc.jar${PS}. Main4"); + } + + if (!ToolBox.isWindows()) { + speJar(); + } + + if (!ToolBox.isWindows()) { + starJar(); + } + + /*---------------------------------------------------------------- + * Verify these jar files with varying extensions + *----------------------------------------------------------------*/ + + // Mixed case extensions should not be loaded. + expectFail(JAVAC, "-classpath MixJar/* Main1b.java"); + expectPass(JAVAC, "-classpath MixJar/mix.jAr Main1b.java"); + expectFail(JAVAC, "-classpath MixJar/* Main1b"); + + // upper case, .JAR, extension should be loaded + if (!ToolBox.isWindows()) { + expectPass(JAVAC, "-classpath MixJar/* Main2.java"); + } + expectPass(JAVAC, "-classpath .${PS}MixJar/* Main2.java"); + + expectPass(JAVA, "-classpath MixJar/*${PS}. Main2"); + + // zip extensions should not be loaded + expectFail(JAVAC, "-classpath MixJar/* Main3.java"); + expectPass(JAVAC, "-classpath MixJar/mix3.zip Main3.java"); + expectFail(JAVA, "-classpath MixJar/*${PS}. Main3"); + + // unix "hidden" file + if (!ToolBox.isWindows()) { + expectPass(JAVAC, "-classpath MixJar/* Main4.java"); + expectPass(JAVA, "-classpath MixJar/*${PS}. Main4"); + } + } + + void starDirTests() throws Exception { + out.println("Running tests with directory named \"*\""); + deleteFiles("./StarDir"); + tb.createDirectories("StarDir/*"); + tb.copyFile("GooClass/Lib2.class", "StarDir/*/Lib2.class"); + jar("cf", "StarDir/Lib3.jar", "-C", "GooClass", "Lib3.class"); + jar("cf", "StarDir/*/Lib.jar", "-C", "GooClass", "Lib.class"); + checkFiles("StarDir/*/Lib.jar", "StarDir/*/Lib2.class", "StarDir/Lib3.jar"); + tb.copyFile("Main6.java", "./StarDir/."); + tb.copyFile("Main.java", "./StarDir/*/."); + tb.copyFile("Main1.java", "./StarDir/*/."); + Path StarDir = Path.of("StarDir"); + expectFail(StarDir, JAVAC, "-classpath * Main6.java"); + expectFail(StarDir, JAVAC, "-classpath ./* Main6.java"); + deleteFiles(listFiles(StarDir, "Main6.*")); + Path StarDir_star = StarDir.resolve("*"); + expectPass(StarDir_star, JAVAC, "-classpath * Main.java"); + expectPass(StarDir_star, JAVA, "-classpath .${PS}* Main"); + expectPass(StarDir_star, JAVAC, "Main1.java"); + expectPass(StarDir_star, JAVA, "-classpath . Main1"); + + expectFail(JAVAC, "-classpath StarDir/* Main6.java"); + + expectPass(JAVAC, "-classpath StarDir/* Main1.java"); + expectPass(JAVA, "-classpath StarDir/*:. Main1"); + + expectPass(JAVAC, "-classpath StarDir/* Main1.java"); + expectPass(JAVA, "-classpath .${PS}StarDir/* Main1"); + + expectFail(JAVAC, "-classpath StarDir/\\*/* Main.java"); + expectPass(JAVAC, "-classpath StarDir/*/* Main.java"); + + expectPass(JAVA, "-classpath .${PS}StarDir/*/* Main"); + expectFail(JAVA, "-classpath .${PS}StarDir/\\*/* Main"); + + expectPass(JAVAC, "-classpath StarDir/Lib3.jar Main6.java"); + expectPass(JAVA, "-classpath .${PS}StarDir/Lib3.jar Main6"); + + expectPass(JAVAC, "-classpath StarDir/*/Lib.jar Main.java"); + expectPass(JAVA, "-classpath .${PS}StarDir/*/Lib.jar Main"); + } + + void speJar() throws Exception { + out.println("Running tests with jar file names containing special characters"); + + expectPass(JAVAC, "-classpath SpeJar/* Main2.java"); + expectPass(JAVA, "-classpath SpeJar/*${PS}. Main2"); + + expectPass(JAVAC, "-classpath SpeJar/* Main3.java"); + expectPass(JAVA, "-classpath SpeJar/*${PS}. Main3"); + + expectPass(JAVAC, "-classpath SpeJar/* Main4.java"); + expectPass(JAVA, "-classpath SpeJar/*${PS}. Main4"); + } + + /*---------------------------------------------------------------- + * Verify these jar files with asterisk in jar file name + *----------------------------------------------------------------*/ + void starJar() throws Exception { + out.println("Running tests with jar file names containing \"*\""); + expectPass(JAVAC, "-classpath StarJar/*jar.jar Main2.java"); + expectPass(JAVA, "-classpath StarJar/*jar.jar${PS}. Main2"); + + expectPass(JAVAC, "-classpath StarJar/jar*.jar Main3.java"); + expectPass(JAVA, "-classpath StarJar/jar*.jar${PS}. Main3"); + + expectPass(JAVAC, "-classpath StarJar/*jar*.jar Main4.java"); + expectPass(JAVA, "-classpath StarJar/*jar*.jar${PS}. Main4"); + + expectPass(JAVAC, "-classpath StarJar/* Main2.java"); + expectPass(JAVA, "-classpath StarJar/*${PS}. Main2"); + + expectPass(JAVAC, "-classpath StarJar/* Main3.java"); + expectPass(JAVA, "-classpath StarJar/*${PS}. Main3"); + + expectPass(JAVAC, "-classpath StarJar/* Main4.java"); + expectPass(JAVA, "-classpath StarJar/*${PS}. Main4"); + } +} diff --git a/test/langtools/tools/javac/Paths/wcMineField.sh b/test/langtools/tools/javac/Paths/wcMineField.sh deleted file mode 100644 index 235125ae254..00000000000 --- a/test/langtools/tools/javac/Paths/wcMineField.sh +++ /dev/null @@ -1,296 +0,0 @@ -#!/bin/sh - -# -# Copyright (c) 2005, 2015, Oracle and/or its affiliates. All rights reserved. -# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. -# -# This code is free software; you can redistribute it and/or modify it -# under the terms of the GNU General Public License version 2 only, as -# published by the Free Software Foundation. -# -# This code is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License -# version 2 for more details (a copy is included in the LICENSE file that -# accompanied this code). -# -# You should have received a copy of the GNU General Public License version -# 2 along with this work; if not, write to the Free Software Foundation, -# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA -# or visit www.oracle.com if you need additional information or have any -# questions. -# - -# -# @test -# @summary Test classpath wildcards for javac and java -classpath option. -# @bug 6268383 8172309 -# @run shell/timeout=600 wcMineField.sh - -# To run this test manually, simply do ./wcMineField.sh -#---------------------------------------------------------------- - -. ${TESTSRC-.}/Util.sh - -set -u - -#---------------------------------------------------------------- -# Note that, on Windows only, the launcher also includes another -# kind of command-line wildcard expansion, via setargv.obj -# http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vccelng/htm/progs_11.asp -# Therefore, on Windows, -classpath "foo/*" is treated differently -# from -classpath ".${PS}foo/*" -#---------------------------------------------------------------- - -#---------------------------------------------------------------- -# Prepare the "Minefield" -#---------------------------------------------------------------- -Cleanup() { - Sys rm -rf GooSrc GooJar GooZip GooClass - Sys rm -rf SpeSrc SpeJar SpeZip SpeClass - Sys rm -rf BadSrc BadJar BadZip BadClass - Sys rm -rf JarNClass StarJar MixJar StarDir - Sys rm -rf OneDir *.class Main*.java MANIFEST.MF -} - -Cleanup -Sys mkdir GooSrc GooJar GooZip GooClass GooJar/SubDir -Sys mkdir BadSrc BadJar BadZip BadClass -Sys mkdir SpeSrc SpeJar SpeZip SpeClass -Sys mkdir JarNClass StarJar MixJar -echo 'public class Lib {public static void f(){}}' > Lib.java -echo 'public class Lib2 {public static void g(){}}' > Lib2.java -echo 'public class Lib3 {public static void h(){}}' > Lib3.java -Sys "$javac" ${TESTTOOLVMOPTS} Lib.java Lib2.java Lib3.java -Sys cp Lib.class JarNClass/. -Sys "$jar" cf GooJar/Lib.jar Lib.class -Sys "$jar" cf GooJar/SubDir/Lib2.jar Lib2.class -Sys "$jar" cf JarNClass/Lib.jar Lib.class - -Sys "$jar" cf GooZip/Lib.zip Lib.class -Sys mv Lib.class GooClass/. -Sys mv Lib2.class GooClass/. -Sys mv Lib3.class GooClass/. -Sys mv Lib.java GooSrc/. -Sys mv Lib2.java GooSrc/. -Sys mv Lib3.java GooSrc -CheckFiles GooZip/Lib.zip GooJar/Lib.jar GooSrc/Lib.java -CheckFiles GooSrc/Lib2.java GooSrc/Lib3.java GooJar/SubDir/Lib2.jar - -echo 'public class Spe1 {public static void f(){}}' > Spe1.java -echo 'public class Spe2 {public static void f(){}}' > Spe2.java -echo 'public class Spe3 {public static void f(){}}' > Spe3.java -echo 'public class Spe4 {public static void f(){}}' > Spe4.java -Sys "$javac" ${TESTTOOLVMOPTS} Spe1.java -Sys "$javac" ${TESTTOOLVMOPTS} Spe2.java -Sys "$javac" ${TESTTOOLVMOPTS} Spe3.java -Sys "$javac" ${TESTTOOLVMOPTS} Spe4.java - -UnixOnly Sys "$jar" cf "SpeJar/Spe:Colon.jar" Spe1.class -UnixOnly Sys "$jar" cf "SpeJar/Spe*wc.jar" Spe4.class -UnixOnly CheckFiles "SpeJar/Spe*wc.jar" - -UnixOnly Sys "$jar" cf "StarJar/*jar.jar" Spe2.class -UnixOnly Sys "$jar" cf "StarJar/jar*.jar" Spe3.class -UnixOnly Sys "$jar" cf "StarJar/*jar*.jar" Spe4.class -UnixOnly CheckFiles "StarJar/*jar.jar" "StarJar/jar*.jar" "StarJar/*jar*.jar" - -Sys "$jar" cf "SpeJar/Spe,Comma.jar" Spe2.class -Sys "$jar" cf "SpeJar/Spe;Semi.jar" Spe3.class - -Sys "$jar" cf "MixJar/mix.jAr" Spe1.class -Sys "$jar" cf "MixJar/mix2.JAR" Spe2.class -Sys "$jar" cf "MixJar/mix3.zip" Spe3.class -Sys "$jar" cf "MixJar/.hiddenjar.jar" Spe4.class - -Sys mv Spe*.class SpeClass/. -Sys mv Spe*.java SpeSrc/. -CheckFiles "SpeJar/Spe,Comma.jar" "SpeJar/Spe;Semi.jar" "SpeSrc/Spe2.java" "SpeSrc/Spe3.java" "SpeSrc/Spe4.java" -CheckFiles "MixJar/mix.jAr" "MixJar/mix2.JAR" "MixJar/mix3.zip" "MixJar/.hiddenjar.jar" - -echo 'public class Main {public static void main(String[] a) {Lib.f();}}' > Main.java -echo 'public class Main1 {public static void main(String[] a) {Lib2.g();}}' > Main1.java -echo 'public class Main1b {public static void main(String[] a) {Spe1.f();}}' > Main1b.java -echo 'public class Main2 {public static void main(String[] a) {Spe2.f();}}' > Main2.java -echo 'public class Main3 {public static void main(String[] a) {Spe3.f();}}' > Main3.java -echo 'public class Main4 {public static void main(String[] a) {Spe4.f();}}' > Main4.java -echo 'public class Main5 {public static void main(String[] a) {Spe2.f(); Lib.f();}}' > Main5.java -echo 'public class Main6 {public static void main(String[] a) {Lib3.h();}}' > Main6.java - - -#---------------------------------------------------------------- -# Verify expected behaviour with directory named "*" -#---------------------------------------------------------------- -starDir() { - printf "Running tests with directory named \"*\"\n" - Sys rm -rf ./StarDir - Sys mkdir -p StarDir/"*" - Sys cp "GooClass/Lib2.class" "StarDir/*/Lib2.class" - Sys "$jar" cf "StarDir/Lib3.jar" -C GooClass "Lib3.class" - Sys "$jar" cf "StarDir/*/Lib.jar" -C GooClass "Lib.class" - CheckFiles "StarDir/*/Lib.jar" "StarDir/*/Lib2.class" "StarDir/Lib3.jar" - Sys cp Main6.java ./StarDir/. - Sys cp Main.java ./StarDir/"*"/. - Sys cp Main1.java ./StarDir/"*"/. - CPWC_DIR=`pwd` - Sys cd StarDir - Failure "$javac" ${TESTTOOLVMOPTS} -classpath "*" Main6.java - Failure "$javac" ${TESTTOOLVMOPTS} -classpath "./*" Main6.java - Sys rm -f Main6.* - Sys cd "*" - Success "$javac" ${TESTTOOLVMOPTS} -classpath "*" Main.java - Success "$java" ${TESTVMOPTS} -classpath .${PS}"*" Main - Success "$javac" ${TESTTOOLVMOPTS} Main1.java - Success "$java" ${TESTVMOPTS} -classpath "." Main1 - Sys cd $CPWC_DIR - - Failure "$javac" ${TESTTOOLVMOPTS} -classpath "StarDir/*" Main6.java - - Success "$javac" ${TESTTOOLVMOPTS} -classpath StarDir/\* Main1.java - Success "$java" ${TESTVMOPTS} -classpath StarDir/\*:. Main1 - - Success "$javac" ${TESTTOOLVMOPTS} -classpath "StarDir/*" Main1.java - Success "$java" ${TESTVMOPTS} -classpath ".${PS}StarDir/*" Main1 - - Failure "$javac" ${TESTTOOLVMOPTS} -classpath StarDir/"\*/*" Main.java - Success "$javac" ${TESTTOOLVMOPTS} -classpath StarDir/"*/*" Main.java - - Success "$java" ${TESTVMOPTS} -classpath .${PS}StarDir/"*/*" Main - Failure "$java" ${TESTVMOPTS} -classpath .${PS}StarDir/"\*/*" Main - - Success "$javac" ${TESTTOOLVMOPTS} -classpath "StarDir/Lib3.jar" Main6.java - Success "$java" ${TESTVMOPTS} -classpath ".${PS}StarDir/Lib3.jar" Main6 - - Success "$javac" ${TESTTOOLVMOPTS} -classpath StarDir/"*"/Lib.jar Main.java - Success "$java" ${TESTVMOPTS} -classpath .${PS}StarDir/"*"/Lib.jar Main -} -UnixOnly starDir - -#---------------------------------------------------------------- -# Verify the basic jar file works -#---------------------------------------------------------------- -#baseline test to verify it works. -Success "$javac" ${TESTTOOLVMOPTS} -cp "GooJar/Lib.jar" Main.java -Success "$javac" ${TESTTOOLVMOPTS} -classpath "GooJar/Lib.jar" Main.java -Success "$java" ${TESTVMOPTS} -classpath "GooJar/Lib.jar${PS}." Main -Success "$java" ${TESTVMOPTS} -cp "GooJar/Lib.jar${PS}." Main - -#basic test of one jar to be loaded -UnixOnly Success "$javac" ${TESTTOOLVMOPTS} -classpath "GooJar/*" Main.java - Success "$javac" ${TESTTOOLVMOPTS} -classpath "GooJar/*${PS}." Main.java -Success "$java" ${TESTVMOPTS} -classpath "GooJar/*${PS}." Main -#in a subdir. First * should not load jars in subdirectories unless specified -Failure "$javac" ${TESTTOOLVMOPTS} -classpath "GooJar/*" Main1.java -Failure "$javac" ${TESTTOOLVMOPTS} -classpath "GooJar/*${PS}." Main1.java -Success "$javac" ${TESTTOOLVMOPTS} -cp "GooJar/SubDir/*" Main1.java -Success "$javac" ${TESTTOOLVMOPTS} -classpath "GooJar/SubDir/*" Main1.java -Success "$javac" ${TESTTOOLVMOPTS} --class-path "GooJar/SubDir/*" Main1.java -Success "$javac" ${TESTTOOLVMOPTS} --class-path="GooJar/SubDir/*" Main1.java -#Same with launcher. Should not load jar in subdirectories unless specified -Failure "$java" ${TESTVMOPTS} -classpath "GooJar/*${PS}." Main1 -Success "$java" ${TESTVMOPTS} -classpath "GooJar/SubDir/*${PS}." Main1 -Success "$java" ${TESTVMOPTS} -cp "GooJar/SubDir/*${PS}." Main1 - -Success env CLASSPATH="GooJar/SubDir/*" "$javac" ${TESTTOOLVMOPTS} Main1.java -Success env CLASSPATH="GooJar/SubDir/*${PS}." "$java" ${TESTVMOPTS} Main1 -#---------------------------------------------------------------- -# Verify the jar files in 2 directories -#---------------------------------------------------------------- -Success "$javac" ${TESTTOOLVMOPTS} -classpath "GooJar/Lib.jar${PS}SpeJar/Spe,Comma.jar" Main5.java -Success "$java" ${TESTVMOPTS} -classpath "GooJar/Lib.jar${PS}SpeJar/Spe,Comma.jar${PS}." Main5 - -Success "$javac" ${TESTTOOLVMOPTS} -classpath "GooJar/*${PS}SpeJar/*" Main5.java -Success "$java" ${TESTVMOPTS} -classpath "GooJar/*${PS}SpeJar/*${PS}." Main5 - -#---------------------------------------------------------------- -# Verify jar file and class file in same directory. -#---------------------------------------------------------------- -Success "$javac" ${TESTTOOLVMOPTS} -classpath "JarNClass/*${PS}" Main.java -Success "$java" ${TESTVMOPTS} -classpath "JarNClass/*${PS}." Main - -#---------------------------------------------------------------- -# Verify these odd jar files work explicitly on classpath, kind of -# a baseline. Last one is also a test with * in a jar name. -#---------------------------------------------------------------- -Failure "$javac" ${TESTTOOLVMOPTS} -classpath "SpeJar/Spe:Colon.jar" Main1.java - -Success "$javac" ${TESTTOOLVMOPTS} -classpath "SpeJar/Spe,Comma.jar" Main2.java -Success "$java" ${TESTVMOPTS} -classpath "SpeJar/Spe,Comma.jar${PS}." Main2 - -UnixOnly Success "$javac" ${TESTTOOLVMOPTS} -classpath "SpeJar/Spe;Semi.jar" Main3.java -UnixOnly Success "$java" ${TESTVMOPTS} -classpath "SpeJar/Spe;Semi.jar${PS}." Main3 - -UnixOnly Success "$javac" ${TESTTOOLVMOPTS} -classpath "SpeJar/Spe*wc.jar" Main4.java -UnixOnly Success "$java" ${TESTVMOPTS} -classpath "SpeJar/Spe*wc.jar${PS}." Main4 -#---------------------------------------------------------------- -# Verify these odd jar files work with classpath wildcard. -#---------------------------------------------------------------- - -speJar() { - printf "Running tests with jar file names containing special characters\n" -# Failure "$javac" ${TESTTOOLVMOPTS} -classpath "SpeJar/*" Main1.java -# Success "$java" ${TESTVMOPTS} -classpath "SpeJar/*" Main1 - - Success "$javac" ${TESTTOOLVMOPTS} -classpath "SpeJar/*" Main2.java - Success "$java" ${TESTVMOPTS} -classpath "SpeJar/*${PS}." Main2 - - Success "$javac" ${TESTTOOLVMOPTS} -classpath "SpeJar/*" Main3.java - Success "$java" ${TESTVMOPTS} -classpath "SpeJar/*${PS}." Main3 - - Success "$javac" ${TESTTOOLVMOPTS} -classpath "SpeJar/*" Main4.java - Success "$java" ${TESTVMOPTS} -classpath "SpeJar/*${PS}." Main4 -} -UnixOnly speJar - -#---------------------------------------------------------------- -# Verify these jar files with asterisk in jar file name -#---------------------------------------------------------------- -starJar() { - printf "Running tests with jar file names containing \"*\"\n" - Success "$javac" ${TESTTOOLVMOPTS} -classpath "StarJar/*jar.jar" Main2.java - Success "$java" ${TESTVMOPTS} -classpath "StarJar/*jar.jar${PS}." Main2 - - Success "$javac" ${TESTTOOLVMOPTS} -classpath "StarJar/jar*.jar" Main3.java - Success "$java" ${TESTVMOPTS} -classpath "StarJar/jar*.jar${PS}." Main3 - - Success "$javac" ${TESTTOOLVMOPTS} -classpath "StarJar/*jar*.jar" Main4.java - Success "$java" ${TESTVMOPTS} -classpath "StarJar/*jar*.jar${PS}." Main4 - - Success "$javac" ${TESTTOOLVMOPTS} -classpath "StarJar/*" Main2.java - Success "$java" ${TESTVMOPTS} -classpath "StarJar/*${PS}." Main2 - - Success "$javac" ${TESTTOOLVMOPTS} -classpath "StarJar/*" Main3.java - Success "$java" ${TESTVMOPTS} -classpath "StarJar/*${PS}." Main3 - - Success "$javac" ${TESTTOOLVMOPTS} -classpath "StarJar/*" Main4.java - Success "$java" ${TESTVMOPTS} -classpath "StarJar/*${PS}." Main4 -} -UnixOnly starJar - -#---------------------------------------------------------------- -# Verify these jar files with varying extensions -#---------------------------------------------------------------- -# Mixed case extensions should not be loaded. -Failure "$javac" ${TESTTOOLVMOPTS} -classpath "MixJar/*" Main1b.java -Success "$javac" ${TESTTOOLVMOPTS} -classpath "MixJar/mix.jAr" Main1b.java -Failure "$javac" ${TESTTOOLVMOPTS} -classpath "MixJar/*" Main1b - -#upper case, .JAR, extension should be loaded -UnixOnly Success "$javac" ${TESTTOOLVMOPTS} -classpath "MixJar/*" Main2.java - Success "$javac" ${TESTTOOLVMOPTS} -classpath ".${PS}MixJar/*" Main2.java - -Success "$java" ${TESTVMOPTS} -classpath "MixJar/*${PS}." Main2 -# zip extensions should not be loaded -Failure "$javac" ${TESTTOOLVMOPTS} -classpath "MixJar/*" Main3.java -Success "$javac" ${TESTTOOLVMOPTS} -classpath "MixJar/mix3.zip" Main3.java -Failure "$java" ${TESTVMOPTS} -classpath "MixJar/*${PS}." Main3 -# unix "hidden" file -UnixOnly Success "$javac" ${TESTTOOLVMOPTS} -classpath "MixJar/*" Main4.java -UnixOnly Success "$java" ${TESTVMOPTS} -classpath "MixJar/*${PS}." Main4 - -Cleanup - -Bottom Line -#---------------------------------------------------------------- diff --git a/test/langtools/tools/javac/StringConcat/StringAppendEvaluatesInOrder.java b/test/langtools/tools/javac/StringConcat/StringAppendEvaluatesInOrder.java new file mode 100644 index 00000000000..b2bd47acde0 --- /dev/null +++ b/test/langtools/tools/javac/StringConcat/StringAppendEvaluatesInOrder.java @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2021, Google LLC. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute 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 8273914 + * @summary Indy string concat changes order of operations + * + * @clean * + * @compile -XDstringConcat=indy StringAppendEvaluatesInOrder.java + * @run main StringAppendEvaluatesInOrder + * + * @clean * + * @compile -XDstringConcat=indyWithConstants StringAppendEvaluatesInOrder.java + * @run main StringAppendEvaluatesInOrder + * + * @clean * + * @compile -XDstringConcat=inline StringAppendEvaluatesInOrder.java + * @run main StringAppendEvaluatesInOrder + */ + +public class StringAppendEvaluatesInOrder { + static String test() { + StringBuilder builder = new StringBuilder("foo"); + int i = 15; + return "Test: " + i + " " + (++i) + builder + builder.append("bar"); + } + + static String compoundAssignment() { + StringBuilder builder2 = new StringBuilder("foo"); + Object oo = builder2; + oo += "" + builder2.append("bar"); + return oo.toString(); + } + + public static void main(String[] args) throws Exception { + assertEquals(test(), "Test: 15 16foofoobar"); + assertEquals(compoundAssignment(), "foofoobar"); + } + + private static void assertEquals(String actual, String expected) { + if (!actual.equals(expected)) { + throw new AssertionError("expected: " + expected + ", actual: " + actual); + } + } +} diff --git a/test/langtools/tools/javac/StringConcat/WellKnownTypeSignatures.java b/test/langtools/tools/javac/StringConcat/WellKnownTypeSignatures.java new file mode 100644 index 00000000000..07cdeef4956 --- /dev/null +++ b/test/langtools/tools/javac/StringConcat/WellKnownTypeSignatures.java @@ -0,0 +1,119 @@ +/* + * Copyright (c) 2021, Google LLC. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import com.sun.tools.classfile.*; +import com.sun.tools.classfile.ConstantPool.*; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +/* + * @test + * @bug 8273914 + * @summary Indy string concat changes order of operations + * @modules jdk.jdeps/com.sun.tools.classfile + * + * @clean * + * @compile -XDstringConcat=indy WellKnownTypeSignatures.java + * @run main WellKnownTypeSignatures + * + * @clean * + * @compile -XDstringConcat=indyWithConstants WellKnownTypeSignatures.java + * @run main WellKnownTypeSignatures + */ + +public class WellKnownTypeSignatures { + static List actualTypes; + + static int idx = 0; + + static boolean z = true; + static char c = (char) 42; + static short s = (short) 42; + static byte b = (byte) 42; + static int i = 42; + static long l = 42L; + static float f = 42.0f; + static double d = 42.0; + + public static void main(String[] argv) throws Exception { + readIndyTypes(); + + test("" + WellKnownTypeSignatures.class, idx++, "(Ljava/lang/String;)Ljava/lang/String;"); + test("" + Boolean.valueOf(z), idx++, "(Ljava/lang/Boolean;)Ljava/lang/String;"); + test("" + Character.valueOf(c), idx++, "(Ljava/lang/Character;)Ljava/lang/String;"); + test("" + Byte.valueOf(b), idx++, "(Ljava/lang/Byte;)Ljava/lang/String;"); + test("" + Short.valueOf(s), idx++, "(Ljava/lang/Short;)Ljava/lang/String;"); + test("" + Integer.valueOf(i), idx++, "(Ljava/lang/Integer;)Ljava/lang/String;"); + test("" + Long.valueOf(l), idx++, "(Ljava/lang/Long;)Ljava/lang/String;"); + test("" + Double.valueOf(d), idx++, "(Ljava/lang/Double;)Ljava/lang/String;"); + test("" + Float.valueOf(f), idx++, "(Ljava/lang/Float;)Ljava/lang/String;"); + test("" + z, idx++, "(Z)Ljava/lang/String;"); + test("" + c, idx++, "(C)Ljava/lang/String;"); + test("" + b, idx++, "(B)Ljava/lang/String;"); + test("" + s, idx++, "(S)Ljava/lang/String;"); + test("" + i, idx++, "(I)Ljava/lang/String;"); + test("" + l, idx++, "(J)Ljava/lang/String;"); + test("" + d, idx++, "(D)Ljava/lang/String;"); + test("" + f, idx++, "(F)Ljava/lang/String;"); + } + + public static void test(String actual, int index, String expectedType) { + String actualType = actualTypes.get(index); + if (!actualType.equals(expectedType)) { + throw new IllegalStateException( + index + + " Unexpected type: expected = " + + expectedType + + ", actual = " + + actualType); + } + } + + public static void readIndyTypes() throws Exception { + actualTypes = new ArrayList(); + + ClassFile classFile = + ClassFile.read( + new File( + System.getProperty("test.classes", "."), + WellKnownTypeSignatures.class.getName() + ".class")); + ConstantPool constantPool = classFile.constant_pool; + + for (Method method : classFile.methods) { + if (method.getName(constantPool).equals("main")) { + Code_attribute code = (Code_attribute) method.attributes.get(Attribute.Code); + for (Instruction i : code.getInstructions()) { + if (i.getOpcode() == Opcode.INVOKEDYNAMIC) { + CONSTANT_InvokeDynamic_info indyInfo = + (CONSTANT_InvokeDynamic_info) + constantPool.get(i.getUnsignedShort(1)); + CONSTANT_NameAndType_info natInfo = indyInfo.getNameAndTypeInfo(); + actualTypes.add(natInfo.getType()); + } + } + } + } + } +} diff --git a/test/langtools/tools/javac/StringConcat/WellKnownTypes.java b/test/langtools/tools/javac/StringConcat/WellKnownTypes.java new file mode 100644 index 00000000000..39150cfc4da --- /dev/null +++ b/test/langtools/tools/javac/StringConcat/WellKnownTypes.java @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2021, Google LLC. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import com.sun.tools.classfile.*; +import com.sun.tools.classfile.ConstantPool.*; + +/* + * @test + * @bug 8273914 + * @summary Indy string concat changes order of operations + * @modules jdk.jdeps/com.sun.tools.classfile + * + * @compile -XDstringConcat=indy WellKnownTypes.java + * @run main WellKnownTypes + * + * @compile -XDstringConcat=indyWithConstants WellKnownTypes.java + * @run main WellKnownTypes + * + * @compile -XDstringConcat=inline WellKnownTypes.java + * @run main WellKnownTypes + */ + +public class WellKnownTypes { + static int idx = 0; + + static boolean z = true; + static char c = (char) 42; + static byte b = (byte) 43; + static short s = (short) 44; + static int i = 45; + static long l = 46L; + static float f = 47.0f; + static double d = 48.0; + + public static void main(String[] argv) throws Exception { + test("" + WellKnownTypes.class, idx++, "class WellKnownTypes"); + test("" + Boolean.valueOf(z), idx++, "true"); + test("" + Character.valueOf(c), idx++, "*"); + test("" + Byte.valueOf(b), idx++, "43"); + test("" + Short.valueOf(s), idx++, "44"); + test("" + Integer.valueOf(i), idx++, "45"); + test("" + Long.valueOf(l), idx++, "46"); + test("" + Float.valueOf(f), idx++, "47.0"); + test("" + Double.valueOf(d), idx++, "48.0"); + test("" + z, idx++, "true"); + test("" + c, idx++, "*"); + test("" + b, idx++, "43"); + test("" + s, idx++, "44"); + test("" + i, idx++, "45"); + test("" + l, idx++, "46"); + test("" + f, idx++, "47.0"); + test("" + d, idx++, "48.0"); + } + + public static void test(String actual, int index, String expected) { + if (!actual.equals(expected)) { + throw new IllegalStateException( + index + " Unexpected: expected = " + expected + ", actual = " + actual); + } + } +} diff --git a/test/langtools/tools/javac/StringConcat/access/Test.java b/test/langtools/tools/javac/StringConcat/access/Test.java index 72237e8b4ef..578bbddb118 100644 --- a/test/langtools/tools/javac/StringConcat/access/Test.java +++ b/test/langtools/tools/javac/StringConcat/access/Test.java @@ -56,109 +56,109 @@ public static void main(String[] argv) throws Exception { // ---------------------------------------------------------------------------- // public Private_PublicClass c1 = new Private_PublicClass(); - test("" + holder.c1, idx++, "(Lp1/PublicClass;)Ljava/lang/String;"); + test("" + holder.c1, idx++, "(Ljava/lang/String;)Ljava/lang/String;"); // public Private_PublicInterface c2 = new Private_PublicInterface(); - test("" + holder.c2, idx++, "(Ljava/lang/Object;)Ljava/lang/String;"); + test("" + holder.c2, idx++, "(Ljava/lang/String;)Ljava/lang/String;"); // public Private_PrivateInterface1 c3 = new Private_PrivateInterface1(); - test("" + holder.c3, idx++, "(Ljava/lang/Object;)Ljava/lang/String;"); + test("" + holder.c3, idx++, "(Ljava/lang/String;)Ljava/lang/String;"); // public Private_PrivateInterface2 c4 = new Private_PrivateInterface2(); - test("" + holder.c4, idx++, "(Ljava/lang/Object;)Ljava/lang/String;"); + test("" + holder.c4, idx++, "(Ljava/lang/String;)Ljava/lang/String;"); // public Public_PublicClass c5 = new Public_PublicClass(); - test("" + holder.c5, idx++, "(Lp1/Public_PublicClass;)Ljava/lang/String;"); + test("" + holder.c5, idx++, "(Ljava/lang/String;)Ljava/lang/String;"); // public Public_PublicInterface c6 = new Public_PublicInterface(); - test("" + holder.c6, idx++, "(Lp1/Public_PublicInterface;)Ljava/lang/String;"); + test("" + holder.c6, idx++, "(Ljava/lang/String;)Ljava/lang/String;"); // public Public_PrivateInterface1 c7 = new Public_PrivateInterface1(); - test("" + holder.c7, idx++, "(Lp1/Public_PrivateInterface1;)Ljava/lang/String;"); + test("" + holder.c7, idx++, "(Ljava/lang/String;)Ljava/lang/String;"); // public Public_PrivateInterface2 c8 = new Public_PrivateInterface2(); - test("" + holder.c8, idx++, "(Lp1/Public_PrivateInterface2;)Ljava/lang/String;"); + test("" + holder.c8, idx++, "(Ljava/lang/String;)Ljava/lang/String;"); // ---------------------------------------------------------------------------- // public Private_PublicClass[] ac1 = new Private_PublicClass[0]; - test("" + holder.ac1, idx++, "([Lp1/PublicClass;)Ljava/lang/String;"); + test("" + holder.ac1, idx++, "(Ljava/lang/String;)Ljava/lang/String;"); // public Private_PublicInterface[] ac2 = new Private_PublicInterface[0]; - test("" + holder.ac2, idx++, "([Ljava/lang/Object;)Ljava/lang/String;"); + test("" + holder.ac2, idx++, "(Ljava/lang/String;)Ljava/lang/String;"); // public Private_PrivateInterface1[] ac3 = new Private_PrivateInterface1[0]; - test("" + holder.ac3, idx++, "([Ljava/lang/Object;)Ljava/lang/String;"); + test("" + holder.ac3, idx++, "(Ljava/lang/String;)Ljava/lang/String;"); // public Private_PrivateInterface2[] ac4 = new Private_PrivateInterface2[0]; - test("" + holder.ac4, idx++, "([Ljava/lang/Object;)Ljava/lang/String;"); + test("" + holder.ac4, idx++, "(Ljava/lang/String;)Ljava/lang/String;"); // public Public_PublicClass[] ac5 = new Public_PublicClass[0]; - test("" + holder.ac5, idx++, "([Lp1/Public_PublicClass;)Ljava/lang/String;"); + test("" + holder.ac5, idx++, "(Ljava/lang/String;)Ljava/lang/String;"); // public Public_PublicInterface[] ac6 = new Public_PublicInterface[0]; - test("" + holder.ac6, idx++, "([Lp1/Public_PublicInterface;)Ljava/lang/String;"); + test("" + holder.ac6, idx++, "(Ljava/lang/String;)Ljava/lang/String;"); // public Public_PrivateInterface1[] ac7 = new Public_PrivateInterface1[0]; - test("" + holder.ac7, idx++, "([Lp1/Public_PrivateInterface1;)Ljava/lang/String;"); + test("" + holder.ac7, idx++, "(Ljava/lang/String;)Ljava/lang/String;"); // public Public_PrivateInterface2[] ac8 = new Public_PrivateInterface2[0]; - test("" + holder.ac8, idx++, "([Lp1/Public_PrivateInterface2;)Ljava/lang/String;"); + test("" + holder.ac8, idx++, "(Ljava/lang/String;)Ljava/lang/String;"); // ---------------------------------------------------------------------------- // public Private_PublicClass[][] aac1 = new Private_PublicClass[0][]; - test("" + holder.aac1, idx++, "([[Lp1/PublicClass;)Ljava/lang/String;"); + test("" + holder.aac1, idx++, "(Ljava/lang/String;)Ljava/lang/String;"); // public Private_PublicInterface[][] aac2 = new Private_PublicInterface[0][]; - test("" + holder.aac2, idx++, "([[Ljava/lang/Object;)Ljava/lang/String;"); + test("" + holder.aac2, idx++, "(Ljava/lang/String;)Ljava/lang/String;"); // public Private_PrivateInterface1[][] aac3 = new Private_PrivateInterface1[0][]; - test("" + holder.aac3, idx++, "([[Ljava/lang/Object;)Ljava/lang/String;"); + test("" + holder.aac3, idx++, "(Ljava/lang/String;)Ljava/lang/String;"); // public Private_PrivateInterface2[][] aac4 = new Private_PrivateInterface2[0][]; - test("" + holder.aac4, idx++, "([[Ljava/lang/Object;)Ljava/lang/String;"); + test("" + holder.aac4, idx++, "(Ljava/lang/String;)Ljava/lang/String;"); // public Public_PublicClass[][] aac5 = new Public_PublicClass[0][]; - test("" + holder.aac5, idx++, "([[Lp1/Public_PublicClass;)Ljava/lang/String;"); + test("" + holder.aac5, idx++, "(Ljava/lang/String;)Ljava/lang/String;"); // public Public_PublicInterface[][] aac6 = new Public_PublicInterface[0][]; - test("" + holder.aac6, idx++, "([[Lp1/Public_PublicInterface;)Ljava/lang/String;"); + test("" + holder.aac6, idx++, "(Ljava/lang/String;)Ljava/lang/String;"); // public Public_PrivateInterface1[][] aac7 = new Public_PrivateInterface1[0][]; - test("" + holder.aac7, idx++, "([[Lp1/Public_PrivateInterface1;)Ljava/lang/String;"); + test("" + holder.aac7, idx++, "(Ljava/lang/String;)Ljava/lang/String;"); // public Public_PrivateInterface2[][] aac8 = new Public_PrivateInterface2[0][]; - test("" + holder.aac8, idx++, "([[Lp1/Public_PrivateInterface2;)Ljava/lang/String;"); + test("" + holder.aac8, idx++, "(Ljava/lang/String;)Ljava/lang/String;"); // ---------------------------------------------------------------------------- // public PublicInterface i1 = new Private_PublicInterface(); - test("" + holder.i1, idx++, "(Lp1/PublicInterface;)Ljava/lang/String;"); + test("" + holder.i1, idx++, "(Ljava/lang/String;)Ljava/lang/String;"); // public PrivateInterface1 i2 = new Private_PrivateInterface1(); - test("" + holder.i2, idx++, "(Ljava/lang/Object;)Ljava/lang/String;"); + test("" + holder.i2, idx++, "(Ljava/lang/String;)Ljava/lang/String;"); // public PrivateInterface2 i3 = new Private_PrivateInterface2(); - test("" + holder.i3, idx++, "(Ljava/lang/Object;)Ljava/lang/String;"); + test("" + holder.i3, idx++, "(Ljava/lang/String;)Ljava/lang/String;"); // public PublicInterface[] ai1 = new Private_PublicInterface[0]; - test("" + holder.ai1, idx++, "([Lp1/PublicInterface;)Ljava/lang/String;"); + test("" + holder.ai1, idx++, "(Ljava/lang/String;)Ljava/lang/String;"); // public PrivateInterface1[] ai2 = new Private_PrivateInterface1[0]; - test("" + holder.ai2, idx++, "([Ljava/lang/Object;)Ljava/lang/String;"); + test("" + holder.ai2, idx++, "(Ljava/lang/String;)Ljava/lang/String;"); // public PrivateInterface2[] ai3 = new Private_PrivateInterface2[0]; - test("" + holder.ai3, idx++, "([Ljava/lang/Object;)Ljava/lang/String;"); + test("" + holder.ai3, idx++, "(Ljava/lang/String;)Ljava/lang/String;"); // public PublicInterface[][] aai1 = new Private_PublicInterface[0][]; - test("" + holder.aai1, idx++, "([[Lp1/PublicInterface;)Ljava/lang/String;"); + test("" + holder.aai1, idx++, "(Ljava/lang/String;)Ljava/lang/String;"); // public PrivateInterface1[][] aai2 = new Private_PrivateInterface1[0][]; - test("" + holder.aai2, idx++, "([[Ljava/lang/Object;)Ljava/lang/String;"); + test("" + holder.aai2, idx++, "(Ljava/lang/String;)Ljava/lang/String;"); // public PrivateInterface2[][] aai3 = new Private_PrivateInterface2[0][]; - test("" + holder.aai3, idx++, "([[Ljava/lang/Object;)Ljava/lang/String;"); + test("" + holder.aai3, idx++, "(Ljava/lang/String;)Ljava/lang/String;"); } diff --git a/test/langtools/tools/lib/toolbox/ToolBox.java b/test/langtools/tools/lib/toolbox/ToolBox.java index 9dbb26e1448..bc76a12cad0 100644 --- a/test/langtools/tools/lib/toolbox/ToolBox.java +++ b/test/langtools/tools/lib/toolbox/ToolBox.java @@ -245,7 +245,7 @@ public void copyFile(String from, String to) throws IOException { public void copyFile(Path from, Path to) throws IOException { if (Files.isDirectory(to)) { to = to.resolve(from.getFileName()); - } else { + } else if (to.getParent() != null) { Files.createDirectories(to.getParent()); } Files.copy(from, to, StandardCopyOption.REPLACE_EXISTING); diff --git a/test/lib-test/jdk/test/lib/process/ProcessToolsLastLineTest.java b/test/lib-test/jdk/test/lib/process/ProcessToolsLastLineTest.java new file mode 100644 index 00000000000..54b5a3bc220 --- /dev/null +++ b/test/lib-test/jdk/test/lib/process/ProcessToolsLastLineTest.java @@ -0,0 +1,70 @@ +/* + * Copyright (c) 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute 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 8303697 + * @summary Test verifies that ProcessTools.startProcess() print all lines even the last line doesn't end with '\n' + * @library /test/lib + * @run main ProcessToolsLastLineTest + */ + +import jdk.test.lib.process.ProcessTools; +import jdk.test.lib.Asserts; + +public class ProcessToolsLastLineTest { + + static void test(String output) throws Exception { + final StringBuffer sb = new StringBuffer(); + Process p = ProcessTools.startProcess("process", + ProcessTools.createLimitedTestJavaProcessBuilder(ProcessToolsLastLineTest.class.getName(), output), + line -> { sb.append(line);}); + p.waitFor(); + String expectedOutput = output.replace("\n", ""); + Asserts.assertEQ(sb.toString(), expectedOutput); + } + + public static void main(String[] args) throws Exception { + + // The line which exceeds internal StreamPumper buffer (256 bytes) + String VERY_LONG_LINE = "X".repeat(257); + if (args.length > 0) { + System.out.print(args[0]); + } else { + test("\n"); + test("\nARG1"); + test("\nARG1\n"); + test("ARG1\n"); + test("ARG1"); + test("ARG1\nARG2"); + test("ARG1\nARG2\n"); + test("\nARG1\nARG2\n"); + test("\nARG1\n" + VERY_LONG_LINE + "\nARG2\n"); + test("\nARG1\n" + VERY_LONG_LINE); + test("\nARG1\n" + VERY_LONG_LINE + VERY_LONG_LINE + VERY_LONG_LINE + "\nARG2\n"); + test("\nARG1\n" + VERY_LONG_LINE + VERY_LONG_LINE + VERY_LONG_LINE); + + } + + } +} diff --git a/test/lib-test/jdk/test/whitebox/vm_flags/BooleanTest.java b/test/lib-test/jdk/test/whitebox/vm_flags/BooleanTest.java index 59d69913881..8843e34ce45 100644 --- a/test/lib-test/jdk/test/whitebox/vm_flags/BooleanTest.java +++ b/test/lib-test/jdk/test/whitebox/vm_flags/BooleanTest.java @@ -69,7 +69,7 @@ public static void main(String[] args) throws Exception { } private static void testFunctional(boolean value) throws Exception { - ProcessBuilder pb = ProcessTools.createJavaProcessBuilder( + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( "-Xbootclasspath/a:.", "-XX:+UnlockDiagnosticVMOptions", "-XX:+WhiteBoxAPI", diff --git a/test/lib/jdk/test/lib/cds/CDSOptions.java b/test/lib/jdk/test/lib/cds/CDSOptions.java index 2fa949dc4cc..130b7b117dc 100644 --- a/test/lib/jdk/test/lib/cds/CDSOptions.java +++ b/test/lib/jdk/test/lib/cds/CDSOptions.java @@ -32,6 +32,8 @@ public class CDSOptions { public ArrayList prefix = new ArrayList(); public ArrayList suffix = new ArrayList(); public boolean useSystemArchive = false; + public String appJar; + public String appJarDir; // classes to be archived public String[] classList; @@ -100,4 +102,15 @@ public CDSOptions setClassList(ArrayList list) { return this; } + // AppCDS methods + public CDSOptions setAppJar(String appJar) { + this.appJar = appJar; + return this; + } + + public CDSOptions setAppJarDir(String appJarDir) { + this.appJarDir = appJarDir; + return this; + } + } diff --git a/test/lib/jdk/test/lib/cds/CDSTestUtils.java b/test/lib/jdk/test/lib/cds/CDSTestUtils.java index 18c1aaea924..d4ddfb90b9b 100644 --- a/test/lib/jdk/test/lib/cds/CDSTestUtils.java +++ b/test/lib/jdk/test/lib/cds/CDSTestUtils.java @@ -257,7 +257,7 @@ public static OutputAnalyzer createArchive(CDSOptions opts) for (String s : opts.suffix) cmd.add(s); String[] cmdLine = cmd.toArray(new String[cmd.size()]); - ProcessBuilder pb = ProcessTools.createTestJvm(cmdLine); + ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder(cmdLine); return executeAndLog(pb, "dump"); } @@ -430,7 +430,7 @@ public static OutputAnalyzer runWithArchive(CDSOptions opts) for (String s : opts.suffix) cmd.add(s); String[] cmdLine = cmd.toArray(new String[cmd.size()]); - ProcessBuilder pb = ProcessTools.createTestJvm(cmdLine); + ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder(cmdLine); return executeAndLog(pb, "exec"); } diff --git a/test/lib/jdk/test/lib/classloader/ClassUnloadCommon.java b/test/lib/jdk/test/lib/classloader/ClassUnloadCommon.java index 23e8fa62b53..ae8ae12cf97 100644 --- a/test/lib/jdk/test/lib/classloader/ClassUnloadCommon.java +++ b/test/lib/jdk/test/lib/classloader/ClassUnloadCommon.java @@ -23,12 +23,13 @@ /* - * To use ClassUnloadCommon from a sub-process, see hotspot/test/runtime/logging/ClassLoadUnloadTest.java + * To use ClassUnloadCommon from a sub-process, see test/hotspot/jtreg/runtime/logging/ClassLoadUnloadTest.java * for an example. */ package jdk.test.lib.classloader; +import jdk.test.whitebox.WhiteBox; import java.io.File; import java.net.MalformedURLException; @@ -62,8 +63,8 @@ private static void allocateMemory(int kilobytes) { } public static void triggerUnloading() { - allocateMemory(16 * 1024); // force young collection - System.gc(); + WhiteBox wb = WhiteBox.getWhiteBox(); + wb.fullGC(); // will do class unloading } /** diff --git a/test/lib/jdk/test/lib/cli/CommandLineOptionTest.java b/test/lib/jdk/test/lib/cli/CommandLineOptionTest.java index b3b1b8a7e2c..31cff4b8c25 100644 --- a/test/lib/jdk/test/lib/cli/CommandLineOptionTest.java +++ b/test/lib/jdk/test/lib/cli/CommandLineOptionTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -113,7 +113,7 @@ public static void verifyJVMStartup(String expectedMessages[], finalOptions.add("-version"); ProcessBuilder processBuilder - = ProcessTools.createJavaProcessBuilder(finalOptions.toArray( + = ProcessTools.createLimitedTestJavaProcessBuilder(finalOptions.toArray( new String[finalOptions.size()])); OutputAnalyzer outputAnalyzer = new OutputAnalyzer(processBuilder.start()); @@ -263,7 +263,7 @@ public static void verifyOptionValue(String optionName, Collections.addAll(vmOpts, additionalVMOpts); Collections.addAll(vmOpts, "-XX:+PrintFlagsFinal", "-version"); - ProcessBuilder processBuilder = ProcessTools.createJavaProcessBuilder( + ProcessBuilder processBuilder = ProcessTools.createLimitedTestJavaProcessBuilder( vmOpts.toArray(new String[vmOpts.size()])); OutputAnalyzer outputAnalyzer @@ -333,7 +333,7 @@ public static OutputAnalyzer startVMWithOptions(String[] optionNames, Collections.addAll(vmOpts, additionalVMOpts); Collections.addAll(vmOpts, "-version"); - ProcessBuilder processBuilder = ProcessTools.createJavaProcessBuilder( + ProcessBuilder processBuilder = ProcessTools.createLimitedTestJavaProcessBuilder( vmOpts.toArray(new String[vmOpts.size()])); return new OutputAnalyzer(processBuilder.start()); diff --git a/test/lib/jdk/test/lib/jfr/AppExecutorHelper.java b/test/lib/jdk/test/lib/jfr/AppExecutorHelper.java index 6768f4ed8f9..5268e05b688 100644 --- a/test/lib/jdk/test/lib/jfr/AppExecutorHelper.java +++ b/test/lib/jdk/test/lib/jfr/AppExecutorHelper.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -74,7 +74,7 @@ public static OutputAnalyzer executeAndRecord(String settings, String jfrFilenam Collections.addAll(arguments, classArguments); } - ProcessBuilder pb = ProcessTools.createTestJvm(arguments); + ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder(arguments); return ProcessTools.executeProcess(pb); } } diff --git a/test/lib/jdk/test/lib/process/OutputBuffer.java b/test/lib/jdk/test/lib/process/OutputBuffer.java index 3741ccbe2ff..fba2a5f6dcf 100644 --- a/test/lib/jdk/test/lib/process/OutputBuffer.java +++ b/test/lib/jdk/test/lib/process/OutputBuffer.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2023, Oracle and/or its affiliates. All rights reserved. * 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,7 @@ public String get() { private final StreamTask outTask; private final StreamTask errTask; private final Process p; + private volatile Integer exitValue; // null implies we don't yet know private final void logProgress(String state) { System.out.println("[" + Instant.now().toString() + "] " + state @@ -146,14 +147,17 @@ public String getStderr() { @Override public int getExitValue() { + if (exitValue != null) { + return exitValue; + } try { logProgress("Waiting for completion"); boolean aborted = true; try { - int result = p.waitFor(); + exitValue = p.waitFor(); logProgress("Waiting for completion finished"); aborted = false; - return result; + return exitValue; } finally { if (aborted) { logProgress("Waiting for completion FAILED"); diff --git a/test/lib/jdk/test/lib/process/ProcessTools.java b/test/lib/jdk/test/lib/process/ProcessTools.java index fdfb81d834d..439539e7009 100644 --- a/test/lib/jdk/test/lib/process/ProcessTools.java +++ b/test/lib/jdk/test/lib/process/ProcessTools.java @@ -370,17 +370,7 @@ public static long getProcessId() throws Exception { * @param command Arguments to pass to the java command. * @return The ProcessBuilder instance representing the java command. */ - public static ProcessBuilder createJavaProcessBuilder(List command) { - return createJavaProcessBuilder(command.toArray(String[]::new)); - } - - /** - * Create ProcessBuilder using the java launcher from the jdk to be tested. - * - * @param command Arguments to pass to the java command. - * @return The ProcessBuilder instance representing the java command. - */ - public static ProcessBuilder createJavaProcessBuilder(String... command) { + private static ProcessBuilder createJavaProcessBuilder(String... command) { String javapath = JDKToolFinder.getJDKTool("java"); ArrayList args = new ArrayList<>(); @@ -421,8 +411,8 @@ private static void printStack(Thread t, StackTraceElement[] stack) { * @param command Arguments to pass to the java command. * @return The ProcessBuilder instance representing the java command. */ - public static ProcessBuilder createTestJvm(List command) { - return createTestJvm(command.toArray(String[]::new)); + public static ProcessBuilder createTestJavaProcessBuilder(List command) { + return createTestJavaProcessBuilder(command.toArray(String[]::new)); } /** @@ -436,10 +426,54 @@ public static ProcessBuilder createTestJvm(List command) { * @param command Arguments to pass to the java command. * @return The ProcessBuilder instance representing the java command. */ - public static ProcessBuilder createTestJvm(String... command) { + public static ProcessBuilder createTestJavaProcessBuilder(String... command) { return createJavaProcessBuilder(Utils.prependTestJavaOpts(command)); } + /** + * Create ProcessBuilder using the java launcher from the jdk to + * be tested. + * + *

    Please observe that you likely should use + * createTestJavaProcessBuilder() instead of this method because + * createTestJavaProcessBuilder() will add JVM options from + * "test.vm.opts" and "test.java.opts" and this method will + * not do that. + * + *

    If you still chose to use + * createLimitedTestJavaProcessBuilder() you should probably use + * it in combination with @requires vm.flagless JTREG + * anotation as to not waste energy and test resources. + * + * @param command Arguments to pass to the java command. + * @return The ProcessBuilder instance representing the java command. + */ + public static ProcessBuilder createLimitedTestJavaProcessBuilder(List command) { + return createLimitedTestJavaProcessBuilder(command.toArray(String[]::new)); + } + + /** + * Create ProcessBuilder using the java launcher from the jdk to + * be tested. + * + *

    Please observe that you likely should use + * createTestJavaProcessBuilder() instead of this method because + * createTestJavaProcessBuilder() will add JVM options from + * "test.vm.opts" and "test.java.opts" and this method will + * not do that. + * + *

    If you still chose to use + * createLimitedTestJavaProcessBuilder() you should probably use + * it in combination with @requires vm.flagless JTREG + * anotation as to not waste energy and test resources. + * + * @param command Arguments to pass to the java command. + * @return The ProcessBuilder instance representing the java command. + */ + public static ProcessBuilder createLimitedTestJavaProcessBuilder(String... command) { + return createJavaProcessBuilder(command); + } + /** * Executes a test jvm process, waits for it to finish and returns the process output. * The default jvm options from jtreg, test.vm.opts and test.java.opts, are added. @@ -471,7 +505,7 @@ public static OutputAnalyzer executeTestJvm(List cmds) throws Exception * @return The output from the process. */ public static OutputAnalyzer executeTestJvm(String... cmds) throws Exception { - ProcessBuilder pb = createTestJvm(cmds); + ProcessBuilder pb = createTestJavaProcessBuilder(cmds); return executeProcess(pb); } diff --git a/test/lib/jdk/test/lib/process/StreamPumper.java b/test/lib/jdk/test/lib/process/StreamPumper.java index ad62f6c300a..63775f7d62c 100644 --- a/test/lib/jdk/test/lib/process/StreamPumper.java +++ b/test/lib/jdk/test/lib/process/StreamPumper.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -95,13 +95,15 @@ public StreamPumper(InputStream in, OutputStream out) { /** * Implements Thread.run(). Continuously read from {@code in} and write to - * {@code out} until {@code in} has reached end of stream. Abort on - * interruption. Abort on IOExceptions. + * {@code out} until {@code in} has reached end of stream. + * Additionally this method also splits the data read from the buffer into lines, + * and processes each line using linePumps. + * Abort on interruption. Abort on IOExceptions. */ @Override public void run() { - try (BufferedInputStream is = new BufferedInputStream(in)) { - ByteArrayOutputStream lineBos = new ByteArrayOutputStream(); + try (BufferedInputStream is = new BufferedInputStream(in); + ByteArrayOutputStream lineBos = new ByteArrayOutputStream()) { byte[] buf = new byte[BUF_SIZE]; int len = 0; int linelen = 0; @@ -133,6 +135,10 @@ public void run() { i++; } + // If no crlf was found, or there was additional data after the last crlf was found, then write the leftover data + // in lineBos. If there is more data to read it will be concatenated with the current data on the next iteration. + // If there is no more data, or no more crlf found, all the remaining data will be processed after the loop, as the + // final line. if (lastcrlf == -1) { lineBos.write(buf, 0, len); linelen += len; @@ -143,6 +149,12 @@ public void run() { } } + // If there was no terminating crlf the remaining data has been written to lineBos, + // but this final line of data now needs to be processed by the linePumper. + final String line = lineBos.toString(); + if (!line.isEmpty()) { + linePumps.forEach((lp) -> lp.processLine(line)); + } } catch (IOException e) { if (!e.getMessage().equalsIgnoreCase("stream closed")) { e.printStackTrace(); diff --git a/test/lib/jdk/test/lib/security/TestCertificate.java b/test/lib/jdk/test/lib/security/TestCertificate.java index 914247e23f8..83de3b16012 100644 --- a/test/lib/jdk/test/lib/security/TestCertificate.java +++ b/test/lib/jdk/test/lib/security/TestCertificate.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2023, Oracle and/or its affiliates. All rights reserved. * 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 @@ public enum TestCertificate { // Subject: CN=SSLCertificate, O=SomeCompany // Issuer: CN=Intermediate CA Cert, O=SomeCompany // Validity: Tue Aug 30 14:37:19 PDT 2016 to Wed Aug 30 14:37:19 PDT 2017 - ONE("1000", + ONE("10:00", "CN=SSLCertificate, O=SomeCompany", "CN=Intermediate CA Cert, O=SomeCompany", -1063259762, diff --git a/test/lib/jdk/test/lib/security/TestTLSHandshake.java b/test/lib/jdk/test/lib/security/TestTLSHandshake.java index 309a3f8ef2c..4d53513276e 100644 --- a/test/lib/jdk/test/lib/security/TestTLSHandshake.java +++ b/test/lib/jdk/test/lib/security/TestTLSHandshake.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2023, Oracle and/or its affiliates. All rights reserved. * 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,8 +35,8 @@ public final class TestTLSHandshake extends SSLSocketTest { "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384"; public static final long HASHCODE = -1057291798L; public static final long ANCHOR_HASHCODE = 1688661792L; - public static final String CERT_SERIAL = "edbec8f705af2514"; - public static final String ANCHOR_CERT_SERIAL = "8e191778b2f331be"; + public static final String CERT_SERIAL = "00:ed:be:c8:f7:05:af:25:14"; + public static final String ANCHOR_CERT_SERIAL = "8e:19:17:78:b2:f3:31:be"; public String protocolVersion; public String peerHost; diff --git a/test/lib/jdk/test/whitebox/WhiteBox.java b/test/lib/jdk/test/whitebox/WhiteBox.java index 5a0ab744ade..03db68e91d1 100644 --- a/test/lib/jdk/test/whitebox/WhiteBox.java +++ b/test/lib/jdk/test/whitebox/WhiteBox.java @@ -138,6 +138,12 @@ public int getConstantPoolCacheLength(Class aClass) { return getConstantPoolCacheLength0(aClass); } + private native Object[] getResolvedReferences0(Class aClass); + public Object[] getResolvedReferences(Class aClass) { + Objects.requireNonNull(aClass); + return getResolvedReferences0(aClass); + } + private native int remapInstructionOperandFromCPCache0(Class aClass, int index); public int remapInstructionOperandFromCPCache(Class aClass, int index) { Objects.requireNonNull(aClass); @@ -603,7 +609,6 @@ public Object getMethodOption(Executable method, String name) { public native boolean isJFRIncluded(); public native boolean isDTraceIncluded(); public native boolean canWriteJavaHeapArchive(); - public native Object getResolvedReferences(Class c); public native void linkClass(Class c); public native boolean areOpenArchiveHeapObjectsMapped();