From e2533553f6959a2a66e45d42649ce6272f702e4d Mon Sep 17 00:00:00 2001 From: James Cheng Date: Mon, 29 Jun 2015 00:10:01 -0700 Subject: [PATCH 01/43] 8073583: C2 support for CRC32C on SPARC Reviewed-by: jrose, kvn --- .../src/cpu/aarch64/vm/vm_version_aarch64.cpp | 6 + hotspot/src/cpu/ppc/vm/vm_version_ppc.cpp | 7 + hotspot/src/cpu/sparc/vm/assembler_sparc.hpp | 26 ++- .../src/cpu/sparc/vm/macroAssembler_sparc.cpp | 56 +++++ .../src/cpu/sparc/vm/macroAssembler_sparc.hpp | 14 +- .../src/cpu/sparc/vm/stubGenerator_sparc.cpp | 205 ++++++++++++++++ .../src/cpu/sparc/vm/stubRoutines_sparc.hpp | 4 +- hotspot/src/cpu/sparc/vm/vm_version_sparc.cpp | 20 +- hotspot/src/cpu/sparc/vm/vm_version_sparc.hpp | 7 +- hotspot/src/cpu/x86/vm/vm_version_x86.cpp | 6 + .../vm/vm_version_solaris_sparc.cpp | 7 +- hotspot/src/share/vm/classfile/vmSymbols.hpp | 6 + hotspot/src/share/vm/opto/escape.cpp | 1 + hotspot/src/share/vm/opto/library_call.cpp | 145 +++++++++++- hotspot/src/share/vm/opto/runtime.cpp | 23 ++ hotspot/src/share/vm/opto/runtime.hpp | 1 + hotspot/src/share/vm/runtime/globals.hpp | 3 + hotspot/src/share/vm/runtime/stubRoutines.cpp | 2 + hotspot/src/share/vm/runtime/stubRoutines.hpp | 4 + hotspot/src/share/vm/runtime/vmStructs.cpp | 1 + .../intrinsics/crc32c/TestCRC32C.java | 221 ++++++++++++++++++ 21 files changed, 746 insertions(+), 19 deletions(-) create mode 100644 hotspot/test/compiler/intrinsics/crc32c/TestCRC32C.java diff --git a/hotspot/src/cpu/aarch64/vm/vm_version_aarch64.cpp b/hotspot/src/cpu/aarch64/vm/vm_version_aarch64.cpp index 759a4172897..433145c4a61 100644 --- a/hotspot/src/cpu/aarch64/vm/vm_version_aarch64.cpp +++ b/hotspot/src/cpu/aarch64/vm/vm_version_aarch64.cpp @@ -199,6 +199,12 @@ void VM_Version::get_processor_features() { UseCRC32Intrinsics = true; } + if (UseCRC32CIntrinsics) { + if (!FLAG_IS_DEFAULT(UseCRC32CIntrinsics)) + warning("CRC32C intrinsics are not available on this CPU"); + FLAG_SET_DEFAULT(UseCRC32CIntrinsics, false); + } + if (auxv & (HWCAP_SHA1 | HWCAP_SHA2)) { if (FLAG_IS_DEFAULT(UseSHA)) { FLAG_SET_DEFAULT(UseSHA, true); diff --git a/hotspot/src/cpu/ppc/vm/vm_version_ppc.cpp b/hotspot/src/cpu/ppc/vm/vm_version_ppc.cpp index 8913546bd53..28d19fbe4e4 100644 --- a/hotspot/src/cpu/ppc/vm/vm_version_ppc.cpp +++ b/hotspot/src/cpu/ppc/vm/vm_version_ppc.cpp @@ -191,6 +191,13 @@ void VM_Version::initialize() { FLAG_SET_DEFAULT(UseSHA256Intrinsics, false); FLAG_SET_DEFAULT(UseSHA512Intrinsics, false); } + + if (UseCRC32CIntrinsics) { + if (!FLAG_IS_DEFAULT(UseCRC32CIntrinsics)) + warning("CRC32C intrinsics are not available on this CPU"); + FLAG_SET_DEFAULT(UseCRC32CIntrinsics, false); + } + // Adjust RTM (Restricted Transactional Memory) flags. if (!has_tcheck() && UseRTMLocking) { // Can't continue because UseRTMLocking affects UseBiasedLocking flag diff --git a/hotspot/src/cpu/sparc/vm/assembler_sparc.hpp b/hotspot/src/cpu/sparc/vm/assembler_sparc.hpp index 55f338754dd..42ed9b6b992 100644 --- a/hotspot/src/cpu/sparc/vm/assembler_sparc.hpp +++ b/hotspot/src/cpu/sparc/vm/assembler_sparc.hpp @@ -128,8 +128,11 @@ class Assembler : public AbstractAssembler { faligndata_op3 = 0x36, flog3_op3 = 0x36, edge_op3 = 0x36, + fzero_op3 = 0x36, fsrc_op3 = 0x36, + fnot_op3 = 0x36, xmulx_op3 = 0x36, + crc32c_op3 = 0x36, impdep2_op3 = 0x37, stpartialf_op3 = 0x37, jmpl_op3 = 0x38, @@ -231,7 +234,9 @@ class Assembler : public AbstractAssembler { sha1_opf = 0x141, sha256_opf = 0x142, - sha512_opf = 0x143 + sha512_opf = 0x143, + + crc32c_opf = 0x147 }; enum op5s { @@ -600,6 +605,11 @@ class Assembler : public AbstractAssembler { return x & ((1 << 10) - 1); } + // create a low12 __value__ (not a field) for a given a 32-bit constant + static int low12( int x ) { + return x & ((1 << 12) - 1); + } + // AES crypto instructions supported only on certain processors static void aes_only() { assert( VM_Version::has_aes(), "This instruction only works on SPARC with AES instructions support"); } @@ -608,6 +618,9 @@ class Assembler : public AbstractAssembler { static void sha256_only() { assert( VM_Version::has_sha256(), "This instruction only works on SPARC with SHA256"); } static void sha512_only() { assert( VM_Version::has_sha512(), "This instruction only works on SPARC with SHA512"); } + // CRC32C instruction supported only on certain processors + static void crc32c_only() { assert( VM_Version::has_crc32c(), "This instruction only works on SPARC with CRC32C"); } + // instruction only in VIS1 static void vis1_only() { assert( VM_Version::has_vis1(), "This instruction only works on SPARC with VIS1"); } @@ -1022,6 +1035,7 @@ public: void nop() { emit_int32( op(branch_op) | op2(sethi_op2) ); } + void sw_count() { emit_int32( op(branch_op) | op2(sethi_op2) | 0x3f0 ); } // pp 202 @@ -1198,8 +1212,14 @@ public: void faligndata( FloatRegister s1, FloatRegister s2, FloatRegister d ) { vis1_only(); emit_int32( op(arith_op) | fd(d, FloatRegisterImpl::D) | op3(faligndata_op3) | fs1(s1, FloatRegisterImpl::D) | opf(faligndata_opf) | fs2(s2, FloatRegisterImpl::D)); } + void fzero( FloatRegisterImpl::Width w, FloatRegister d ) { vis1_only(); emit_int32( op(arith_op) | fd(d, w) | op3(fzero_op3) | opf(0x62 - w)); } + void fsrc2( FloatRegisterImpl::Width w, FloatRegister s2, FloatRegister d ) { vis1_only(); emit_int32( op(arith_op) | fd(d, w) | op3(fsrc_op3) | opf(0x7A - w) | fs2(s2, w)); } + void fnot1( FloatRegisterImpl::Width w, FloatRegister s1, FloatRegister d ) { vis1_only(); emit_int32( op(arith_op) | fd(d, w) | op3(fnot_op3) | fs1(s1, w) | opf(0x6C - w)); } + + void fpmerge( FloatRegister s1, FloatRegister s2, FloatRegister d ) { vis1_only(); emit_int32( op(arith_op) | fd(d, FloatRegisterImpl::D) | op3(0x36) | fs1(s1, FloatRegisterImpl::S) | opf(0x4b) | fs2(s2, FloatRegisterImpl::S)); } + void stpartialf( Register s1, Register s2, FloatRegister d, int ia = -1 ) { vis1_only(); emit_int32( op(ldst_op) | fd(d, FloatRegisterImpl::D) | op3(stpartialf_op3) | rs1(s1) | imm_asi(ia) | rs2(s2)); } // VIS2 instructions @@ -1224,6 +1244,10 @@ public: void sha256() { sha256_only(); emit_int32( op(arith_op) | op3(sha_op3) | opf(sha256_opf)); } void sha512() { sha512_only(); emit_int32( op(arith_op) | op3(sha_op3) | opf(sha512_opf)); } + // CRC32C instruction + + void crc32c( FloatRegister s1, FloatRegister s2, FloatRegister d ) { crc32c_only(); emit_int32( op(arith_op) | fd(d, FloatRegisterImpl::D) | op3(crc32c_op3) | fs1(s1, FloatRegisterImpl::D) | opf(crc32c_opf) | fs2(s2, FloatRegisterImpl::D)); } + // Creation Assembler(CodeBuffer* code) : AbstractAssembler(code) { #ifdef CHECK_DELAY diff --git a/hotspot/src/cpu/sparc/vm/macroAssembler_sparc.cpp b/hotspot/src/cpu/sparc/vm/macroAssembler_sparc.cpp index d4507cf04b0..e9ce3f4ec0f 100644 --- a/hotspot/src/cpu/sparc/vm/macroAssembler_sparc.cpp +++ b/hotspot/src/cpu/sparc/vm/macroAssembler_sparc.cpp @@ -956,6 +956,7 @@ void MacroAssembler::set64(jlong value, Register d, Register tmp) { int hi = (int)(value >> 32); int lo = (int)(value & ~0); + int bits_33to2 = (int)((value >> 2) & ~0); // (Matcher::isSimpleConstant64 knows about the following optimizations.) if (Assembler::is_simm13(lo) && value == lo) { or3(G0, lo, d); @@ -964,6 +965,12 @@ void MacroAssembler::set64(jlong value, Register d, Register tmp) { if (low10(lo) != 0) or3(d, low10(lo), d); } + else if ((hi >> 2) == 0) { + Assembler::sethi(bits_33to2, d); // hardware version zero-extends to upper 32 + sllx(d, 2, d); + if (low12(lo) != 0) + or3(d, low12(lo), d); + } else if (hi == -1) { Assembler::sethi(~lo, d); // hardware version zero-extends to upper 32 xor3(d, low10(lo) ^ ~low10(~0), d); @@ -4351,3 +4358,52 @@ void MacroAssembler::bis_zeroing(Register to, Register count, Register temp, Lab cmp_and_brx_short(to, end, Assembler::lessUnsigned, Assembler::pt, small_loop); nop(); // Separate short branches } + +/** + * Update CRC-32[C] with a byte value according to constants in table + * + * @param [in,out]crc Register containing the crc. + * @param [in]val Register containing the byte to fold into the CRC. + * @param [in]table Register containing the table of crc constants. + * + * uint32_t crc; + * val = crc_table[(val ^ crc) & 0xFF]; + * crc = val ^ (crc >> 8); + */ +void MacroAssembler::update_byte_crc32(Register crc, Register val, Register table) { + xor3(val, crc, val); + and3(val, 0xFF, val); + sllx(val, 2, val); + lduw(table, val, val); + srlx(crc, 8, crc); + xor3(val, crc, crc); +} + +// Reverse byte order of lower 32 bits, assuming upper 32 bits all zeros +void MacroAssembler::reverse_bytes_32(Register src, Register dst, Register tmp) { + srlx(src, 24, dst); + + sllx(src, 32+8, tmp); + srlx(tmp, 32+24, tmp); + sllx(tmp, 8, tmp); + or3(dst, tmp, dst); + + sllx(src, 32+16, tmp); + srlx(tmp, 32+24, tmp); + sllx(tmp, 16, tmp); + or3(dst, tmp, dst); + + sllx(src, 32+24, tmp); + srlx(tmp, 32, tmp); + or3(dst, tmp, dst); +} + +void MacroAssembler::movitof_revbytes(Register src, FloatRegister dst, Register tmp1, Register tmp2) { + reverse_bytes_32(src, tmp1, tmp2); + movxtod(tmp1, dst); +} + +void MacroAssembler::movftoi_revbytes(FloatRegister src, Register dst, Register tmp1, Register tmp2) { + movdtox(src, tmp1); + reverse_bytes_32(tmp1, dst, tmp2); +} diff --git a/hotspot/src/cpu/sparc/vm/macroAssembler_sparc.hpp b/hotspot/src/cpu/sparc/vm/macroAssembler_sparc.hpp index 5fc0dd0632c..22f56b999bc 100644 --- a/hotspot/src/cpu/sparc/vm/macroAssembler_sparc.hpp +++ b/hotspot/src/cpu/sparc/vm/macroAssembler_sparc.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 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 @@ -903,6 +903,10 @@ public: inline void ldf(FloatRegisterImpl::Width w, Register s1, RegisterOrConstant s2, FloatRegister d); inline void ldf(FloatRegisterImpl::Width w, const Address& a, FloatRegister d, int offset = 0); + // little-endian + inline void ldxl(Register s1, Register s2, Register d) { ldxa(s1, s2, ASI_PRIMARY_LITTLE, d); } + inline void ldfl(FloatRegisterImpl::Width w, Register s1, Register s2, FloatRegister d) { ldfa(w, s1, s2, ASI_PRIMARY_LITTLE, d); } + // membar psuedo instruction. takes into account target memory model. inline void membar( Assembler::Membar_mask_bits const7a ); @@ -1436,6 +1440,14 @@ public: // Use BIS for zeroing void bis_zeroing(Register to, Register count, Register temp, Label& Ldone); + // Update CRC-32[C] with a byte value according to constants in table + void update_byte_crc32(Register crc, Register val, Register table); + + // Reverse byte order of lower 32 bits, assuming upper 32 bits all zeros + void reverse_bytes_32(Register src, Register dst, Register tmp); + void movitof_revbytes(Register src, FloatRegister dst, Register tmp1, Register tmp2); + void movftoi_revbytes(FloatRegister src, Register dst, Register tmp1, Register tmp2); + #undef VIRTUAL }; diff --git a/hotspot/src/cpu/sparc/vm/stubGenerator_sparc.cpp b/hotspot/src/cpu/sparc/vm/stubGenerator_sparc.cpp index 471bd65d269..f0bfa8de742 100644 --- a/hotspot/src/cpu/sparc/vm/stubGenerator_sparc.cpp +++ b/hotspot/src/cpu/sparc/vm/stubGenerator_sparc.cpp @@ -4910,6 +4910,206 @@ class StubGenerator: public StubCodeGenerator { return start; } +#define CHUNK_LEN 128 /* 128 x 8B = 1KB */ +#define CHUNK_K1 0x1307a0206 /* reverseBits(pow(x, CHUNK_LEN*8*8*3 - 32) mod P(x)) << 1 */ +#define CHUNK_K2 0x1a0f717c4 /* reverseBits(pow(x, CHUNK_LEN*8*8*2 - 32) mod P(x)) << 1 */ +#define CHUNK_K3 0x0170076fa /* reverseBits(pow(x, CHUNK_LEN*8*8*1 - 32) mod P(x)) << 1 */ + + /** + * Arguments: + * + * Inputs: + * O0 - int crc + * O1 - byte* buf + * O2 - int len + * O3 - int* table + * + * Output: + * O0 - int crc result + */ + address generate_updateBytesCRC32C() { + assert(UseCRC32CIntrinsics, "need CRC32C instruction"); + + __ align(CodeEntryAlignment); + StubCodeMark mark(this, "StubRoutines", "updateBytesCRC32C"); + address start = __ pc(); + + const Register crc = O0; // crc + const Register buf = O1; // source java byte array address + const Register len = O2; // number of bytes + const Register table = O3; // byteTable + + Label L_crc32c_head, L_crc32c_aligned; + Label L_crc32c_parallel, L_crc32c_parallel_loop; + Label L_crc32c_serial, L_crc32c_x32_loop, L_crc32c_x8, L_crc32c_x8_loop; + Label L_crc32c_done, L_crc32c_tail, L_crc32c_return; + + __ cmp_and_br_short(len, 0, Assembler::lessEqual, Assembler::pn, L_crc32c_return); + + // clear upper 32 bits of crc + __ clruwu(crc); + + __ and3(buf, 7, G4); + __ cmp_and_brx_short(G4, 0, Assembler::equal, Assembler::pt, L_crc32c_aligned); + + __ mov(8, G1); + __ sub(G1, G4, G4); + + // ------ process the misaligned head (7 bytes or less) ------ + __ BIND(L_crc32c_head); + + // crc = (crc >>> 8) ^ byteTable[(crc ^ b) & 0xFF]; + __ ldub(buf, 0, G1); + __ update_byte_crc32(crc, G1, table); + + __ inc(buf); + __ dec(len); + __ cmp_and_br_short(len, 0, Assembler::equal, Assembler::pn, L_crc32c_return); + __ dec(G4); + __ cmp_and_br_short(G4, 0, Assembler::greater, Assembler::pt, L_crc32c_head); + + // ------ process the 8-byte-aligned body ------ + __ BIND(L_crc32c_aligned); + __ nop(); + __ cmp_and_br_short(len, 8, Assembler::less, Assembler::pn, L_crc32c_tail); + + // reverse the byte order of lower 32 bits to big endian, and move to FP side + __ movitof_revbytes(crc, F0, G1, G3); + + __ set(CHUNK_LEN*8*4, G4); + __ cmp_and_br_short(len, G4, Assembler::less, Assembler::pt, L_crc32c_serial); + + // ------ process four 1KB chunks in parallel ------ + __ BIND(L_crc32c_parallel); + + __ fzero(FloatRegisterImpl::D, F2); + __ fzero(FloatRegisterImpl::D, F4); + __ fzero(FloatRegisterImpl::D, F6); + + __ mov(CHUNK_LEN - 1, G4); + __ BIND(L_crc32c_parallel_loop); + // schedule ldf's ahead of crc32c's to hide the load-use latency + __ ldf(FloatRegisterImpl::D, buf, 0, F8); + __ ldf(FloatRegisterImpl::D, buf, CHUNK_LEN*8, F10); + __ ldf(FloatRegisterImpl::D, buf, CHUNK_LEN*16, F12); + __ ldf(FloatRegisterImpl::D, buf, CHUNK_LEN*24, F14); + __ crc32c(F0, F8, F0); + __ crc32c(F2, F10, F2); + __ crc32c(F4, F12, F4); + __ crc32c(F6, F14, F6); + __ inc(buf, 8); + __ dec(G4); + __ cmp_and_br_short(G4, 0, Assembler::greater, Assembler::pt, L_crc32c_parallel_loop); + + __ ldf(FloatRegisterImpl::D, buf, 0, F8); + __ ldf(FloatRegisterImpl::D, buf, CHUNK_LEN*8, F10); + __ ldf(FloatRegisterImpl::D, buf, CHUNK_LEN*16, F12); + __ crc32c(F0, F8, F0); + __ crc32c(F2, F10, F2); + __ crc32c(F4, F12, F4); + + __ inc(buf, CHUNK_LEN*24); + __ ldfl(FloatRegisterImpl::D, buf, G0, F14); // load in little endian + __ inc(buf, 8); + + __ prefetch(buf, 0, Assembler::severalReads); + __ prefetch(buf, CHUNK_LEN*8, Assembler::severalReads); + __ prefetch(buf, CHUNK_LEN*16, Assembler::severalReads); + __ prefetch(buf, CHUNK_LEN*24, Assembler::severalReads); + + // move to INT side, and reverse the byte order of lower 32 bits to little endian + __ movftoi_revbytes(F0, O4, G1, G4); + __ movftoi_revbytes(F2, O5, G1, G4); + __ movftoi_revbytes(F4, G5, G1, G4); + + // combine the results of 4 chunks + __ set64(CHUNK_K1, G3, G1); + __ xmulx(O4, G3, O4); + __ set64(CHUNK_K2, G3, G1); + __ xmulx(O5, G3, O5); + __ set64(CHUNK_K3, G3, G1); + __ xmulx(G5, G3, G5); + + __ movdtox(F14, G4); + __ xor3(O4, O5, O5); + __ xor3(G5, O5, O5); + __ xor3(G4, O5, O5); + + // reverse the byte order to big endian, via stack, and move to FP side + __ add(SP, -8, G1); + __ srlx(G1, 3, G1); + __ sllx(G1, 3, G1); + __ stx(O5, G1, G0); + __ ldfl(FloatRegisterImpl::D, G1, G0, F2); // load in little endian + + __ crc32c(F6, F2, F0); + + __ set(CHUNK_LEN*8*4, G4); + __ sub(len, G4, len); + __ cmp_and_br_short(len, G4, Assembler::greaterEqual, Assembler::pt, L_crc32c_parallel); + __ nop(); + __ cmp_and_br_short(len, 0, Assembler::equal, Assembler::pt, L_crc32c_done); + + __ BIND(L_crc32c_serial); + + __ mov(32, G4); + __ cmp_and_br_short(len, G4, Assembler::less, Assembler::pn, L_crc32c_x8); + + // ------ process 32B chunks ------ + __ BIND(L_crc32c_x32_loop); + __ ldf(FloatRegisterImpl::D, buf, 0, F2); + __ inc(buf, 8); + __ crc32c(F0, F2, F0); + __ ldf(FloatRegisterImpl::D, buf, 0, F2); + __ inc(buf, 8); + __ crc32c(F0, F2, F0); + __ ldf(FloatRegisterImpl::D, buf, 0, F2); + __ inc(buf, 8); + __ crc32c(F0, F2, F0); + __ ldf(FloatRegisterImpl::D, buf, 0, F2); + __ inc(buf, 8); + __ crc32c(F0, F2, F0); + __ dec(len, 32); + __ cmp_and_br_short(len, G4, Assembler::greaterEqual, Assembler::pt, L_crc32c_x32_loop); + + __ BIND(L_crc32c_x8); + __ nop(); + __ cmp_and_br_short(len, 8, Assembler::less, Assembler::pt, L_crc32c_done); + + // ------ process 8B chunks ------ + __ BIND(L_crc32c_x8_loop); + __ ldf(FloatRegisterImpl::D, buf, 0, F2); + __ inc(buf, 8); + __ crc32c(F0, F2, F0); + __ dec(len, 8); + __ cmp_and_br_short(len, 8, Assembler::greaterEqual, Assembler::pt, L_crc32c_x8_loop); + + __ BIND(L_crc32c_done); + + // move to INT side, and reverse the byte order of lower 32 bits to little endian + __ movftoi_revbytes(F0, crc, G1, G3); + + __ cmp_and_br_short(len, 0, Assembler::equal, Assembler::pt, L_crc32c_return); + + // ------ process the misaligned tail (7 bytes or less) ------ + __ BIND(L_crc32c_tail); + + // crc = (crc >>> 8) ^ byteTable[(crc ^ b) & 0xFF]; + __ ldub(buf, 0, G1); + __ update_byte_crc32(crc, G1, table); + + __ inc(buf); + __ dec(len); + __ cmp_and_br_short(len, 0, Assembler::greater, Assembler::pt, L_crc32c_tail); + + __ BIND(L_crc32c_return); + __ nop(); + __ retl(); + __ delayed()->nop(); + + return start; + } + void generate_initial() { // Generates all stubs and initializes the entry points @@ -5001,6 +5201,11 @@ class StubGenerator: public StubCodeGenerator { StubRoutines::_sha512_implCompress = generate_sha512_implCompress(false, "sha512_implCompress"); StubRoutines::_sha512_implCompressMB = generate_sha512_implCompress(true, "sha512_implCompressMB"); } + + // generate CRC32C intrinsic code + if (UseCRC32CIntrinsics) { + StubRoutines::_updateBytesCRC32C = generate_updateBytesCRC32C(); + } } diff --git a/hotspot/src/cpu/sparc/vm/stubRoutines_sparc.hpp b/hotspot/src/cpu/sparc/vm/stubRoutines_sparc.hpp index f3b30e884c3..2eab8d202be 100644 --- a/hotspot/src/cpu/sparc/vm/stubRoutines_sparc.hpp +++ b/hotspot/src/cpu/sparc/vm/stubRoutines_sparc.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 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 @@ -41,7 +41,7 @@ static bool returns_to_call_stub(address return_pc) { enum /* platform_dependent_constants */ { // %%%%%%%% May be able to shrink this a lot code_size1 = 20000, // simply increase if too small (assembler will crash if too small) - code_size2 = 23000 // simply increase if too small (assembler will crash if too small) + code_size2 = 24000 // simply increase if too small (assembler will crash if too small) }; class Sparc { diff --git a/hotspot/src/cpu/sparc/vm/vm_version_sparc.cpp b/hotspot/src/cpu/sparc/vm/vm_version_sparc.cpp index a76f05e15f1..441b9e4eff6 100644 --- a/hotspot/src/cpu/sparc/vm/vm_version_sparc.cpp +++ b/hotspot/src/cpu/sparc/vm/vm_version_sparc.cpp @@ -230,7 +230,7 @@ void VM_Version::initialize() { assert((OptoLoopAlignment % relocInfo::addr_unit()) == 0, "alignment is not a multiple of NOP size"); char buf[512]; - jio_snprintf(buf, sizeof(buf), "%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s", + jio_snprintf(buf, sizeof(buf), "%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s", (has_v9() ? ", v9" : (has_v8() ? ", v8" : "")), (has_hardware_popc() ? ", popc" : ""), (has_vis1() ? ", vis1" : ""), @@ -242,6 +242,7 @@ void VM_Version::initialize() { (has_sha1() ? ", sha1" : ""), (has_sha256() ? ", sha256" : ""), (has_sha512() ? ", sha512" : ""), + (has_crc32c() ? ", crc32c" : ""), (is_ultra3() ? ", ultra3" : ""), (is_sun4v() ? ", sun4v" : ""), (is_niagara_plus() ? ", niagara_plus" : (is_niagara() ? ", niagara" : "")), @@ -363,6 +364,23 @@ void VM_Version::initialize() { } } + // SPARC T4 and above should have support for CRC32C instruction + if (has_crc32c()) { + if (UseVIS > 2) { // CRC32C intrinsics use VIS3 instructions + if (FLAG_IS_DEFAULT(UseCRC32CIntrinsics)) { + FLAG_SET_DEFAULT(UseCRC32CIntrinsics, true); + } + } else { + if (UseCRC32CIntrinsics) { + warning("SPARC CRC32C intrinsics require VIS3 instruction support. Intrinsics will be disabled."); + FLAG_SET_DEFAULT(UseCRC32CIntrinsics, false); + } + } + } else if (UseCRC32CIntrinsics) { + warning("CRC32C instruction is not available on this CPU"); + FLAG_SET_DEFAULT(UseCRC32CIntrinsics, false); + } + if (FLAG_IS_DEFAULT(ContendedPaddingWidth) && (cache_line_size > ContendedPaddingWidth)) ContendedPaddingWidth = cache_line_size; diff --git a/hotspot/src/cpu/sparc/vm/vm_version_sparc.hpp b/hotspot/src/cpu/sparc/vm/vm_version_sparc.hpp index 59969ed1089..d1c40e6488e 100644 --- a/hotspot/src/cpu/sparc/vm/vm_version_sparc.hpp +++ b/hotspot/src/cpu/sparc/vm/vm_version_sparc.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 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 @@ -53,7 +53,8 @@ protected: aes_instructions = 19, sha1_instruction = 20, sha256_instruction = 21, - sha512_instruction = 22 + sha512_instruction = 22, + crc32c_instruction = 23 }; enum Feature_Flag_Set { @@ -83,6 +84,7 @@ protected: sha1_instruction_m = 1 << sha1_instruction, sha256_instruction_m = 1 << sha256_instruction, sha512_instruction_m = 1 << sha512_instruction, + crc32c_instruction_m = 1 << crc32c_instruction, generic_v8_m = v8_instructions_m | hardware_mul32_m | hardware_div32_m | hardware_fsmuld_m, generic_v9_m = generic_v8_m | v9_instructions_m, @@ -141,6 +143,7 @@ public: static bool has_sha1() { return (_features & sha1_instruction_m) != 0; } static bool has_sha256() { return (_features & sha256_instruction_m) != 0; } static bool has_sha512() { return (_features & sha512_instruction_m) != 0; } + static bool has_crc32c() { return (_features & crc32c_instruction_m) != 0; } static bool supports_compare_and_exchange() { return has_v9(); } diff --git a/hotspot/src/cpu/x86/vm/vm_version_x86.cpp b/hotspot/src/cpu/x86/vm/vm_version_x86.cpp index cfa00dcb5c5..10a6a0c448d 100644 --- a/hotspot/src/cpu/x86/vm/vm_version_x86.cpp +++ b/hotspot/src/cpu/x86/vm/vm_version_x86.cpp @@ -699,6 +699,12 @@ void VM_Version::get_processor_features() { FLAG_SET_DEFAULT(UseSHA512Intrinsics, false); } + if (UseCRC32CIntrinsics) { + if (!FLAG_IS_DEFAULT(UseCRC32CIntrinsics)) + warning("CRC32C intrinsics are not available on this CPU"); + FLAG_SET_DEFAULT(UseCRC32CIntrinsics, false); + } + // Adjust RTM (Restricted Transactional Memory) flags if (!supports_rtm() && UseRTMLocking) { // Can't continue because UseRTMLocking affects UseBiasedLocking flag diff --git a/hotspot/src/os_cpu/solaris_sparc/vm/vm_version_solaris_sparc.cpp b/hotspot/src/os_cpu/solaris_sparc/vm/vm_version_solaris_sparc.cpp index 03b2d4b1b29..b7cafd4c618 100644 --- a/hotspot/src/os_cpu/solaris_sparc/vm/vm_version_solaris_sparc.cpp +++ b/hotspot/src/os_cpu/solaris_sparc/vm/vm_version_solaris_sparc.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2006, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2006, 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 @@ -363,6 +363,11 @@ int VM_Version::platform_features(int features) { #endif if (av & AV_SPARC_CBCOND) features |= cbcond_instructions_m; +#ifndef AV_SPARC_CRC32C +#define AV_SPARC_CRC32C 0x20000000 /* crc32c instruction supported */ +#endif + if (av & AV_SPARC_CRC32C) features |= crc32c_instruction_m; + #ifndef AV_SPARC_AES #define AV_SPARC_AES 0x00020000 /* aes instrs supported */ #endif diff --git a/hotspot/src/share/vm/classfile/vmSymbols.hpp b/hotspot/src/share/vm/classfile/vmSymbols.hpp index a6390215eac..0844489c00f 100644 --- a/hotspot/src/share/vm/classfile/vmSymbols.hpp +++ b/hotspot/src/share/vm/classfile/vmSymbols.hpp @@ -863,6 +863,12 @@ do_name( updateByteBuffer_name, "updateByteBuffer") \ do_signature(updateByteBuffer_signature, "(IJII)I") \ \ + /* support for java.util.zip.CRC32C */ \ + do_class(java_util_zip_CRC32C, "java/util/zip/CRC32C") \ + do_intrinsic(_updateBytesCRC32C, java_util_zip_CRC32C, updateBytes_name, updateBytes_signature, F_S) \ + do_intrinsic(_updateDirectByteBufferCRC32C, java_util_zip_CRC32C, updateDirectByteBuffer_name, updateByteBuffer_signature, F_S) \ + do_name( updateDirectByteBuffer_name, "updateDirectByteBuffer") \ + \ /* support for sun.misc.Unsafe */ \ do_class(sun_misc_Unsafe, "sun/misc/Unsafe") \ \ diff --git a/hotspot/src/share/vm/opto/escape.cpp b/hotspot/src/share/vm/opto/escape.cpp index 1d0f628892d..744952a1c10 100644 --- a/hotspot/src/share/vm/opto/escape.cpp +++ b/hotspot/src/share/vm/opto/escape.cpp @@ -962,6 +962,7 @@ void ConnectionGraph::process_call_arguments(CallNode *call) { (strcmp(call->as_CallLeaf()->_name, "g1_wb_pre") == 0 || strcmp(call->as_CallLeaf()->_name, "g1_wb_post") == 0 || strcmp(call->as_CallLeaf()->_name, "updateBytesCRC32") == 0 || + strcmp(call->as_CallLeaf()->_name, "updateBytesCRC32C") == 0 || strcmp(call->as_CallLeaf()->_name, "aescrypt_encryptBlock") == 0 || strcmp(call->as_CallLeaf()->_name, "aescrypt_decryptBlock") == 0 || strcmp(call->as_CallLeaf()->_name, "cipherBlockChaining_encryptAESCrypt") == 0 || diff --git a/hotspot/src/share/vm/opto/library_call.cpp b/hotspot/src/share/vm/opto/library_call.cpp index b4fd3aeba02..f87f52cfc29 100644 --- a/hotspot/src/share/vm/opto/library_call.cpp +++ b/hotspot/src/share/vm/opto/library_call.cpp @@ -197,7 +197,7 @@ class LibraryCallKit : public GraphKit { CallJavaNode* generate_method_call_virtual(vmIntrinsics::ID method_id) { return generate_method_call(method_id, true, false); } - Node * load_field_from_object(Node * fromObj, const char * fieldName, const char * fieldTypeString, bool is_exact, bool is_static); + Node * load_field_from_object(Node * fromObj, const char * fieldName, const char * fieldTypeString, bool is_exact, bool is_static, ciInstanceKlass * fromKls); Node* make_string_method_node(int opcode, Node* str1_start, Node* cnt1, Node* str2_start, Node* cnt2); Node* make_string_method_node(int opcode, Node* str1, Node* str2); @@ -291,6 +291,9 @@ class LibraryCallKit : public GraphKit { bool inline_updateCRC32(); bool inline_updateBytesCRC32(); bool inline_updateByteBufferCRC32(); + Node* get_table_from_crc32c_class(ciInstanceKlass *crc32c_class); + bool inline_updateBytesCRC32C(); + bool inline_updateDirectByteBufferCRC32C(); bool inline_multiplyToLen(); bool inline_squareToLen(); bool inline_mulAdd(); @@ -539,6 +542,11 @@ CallGenerator* Compile::make_vm_intrinsic(ciMethod* m, bool is_virtual) { if (!UseCRC32Intrinsics) return NULL; break; + case vmIntrinsics::_updateBytesCRC32C: + case vmIntrinsics::_updateDirectByteBufferCRC32C: + if (!UseCRC32CIntrinsics) return NULL; + break; + case vmIntrinsics::_incrementExactI: case vmIntrinsics::_addExactI: if (!Matcher::match_rule_supported(Op_OverflowAddI) || !UseMathExactIntrinsics) return NULL; @@ -947,6 +955,11 @@ bool LibraryCallKit::try_to_inline(int predicate) { case vmIntrinsics::_updateByteBufferCRC32: return inline_updateByteBufferCRC32(); + case vmIntrinsics::_updateBytesCRC32C: + return inline_updateBytesCRC32C(); + case vmIntrinsics::_updateDirectByteBufferCRC32C: + return inline_updateDirectByteBufferCRC32C(); + case vmIntrinsics::_profileBoolean: return inline_profileBoolean(); case vmIntrinsics::_isCompileConstant: @@ -5536,6 +5549,106 @@ bool LibraryCallKit::inline_updateByteBufferCRC32() { return true; } +//------------------------------get_table_from_crc32c_class----------------------- +Node * LibraryCallKit::get_table_from_crc32c_class(ciInstanceKlass *crc32c_class) { + Node* table = load_field_from_object(NULL, "byteTable", "[I", /*is_exact*/ false, /*is_static*/ true, crc32c_class); + assert (table != NULL, "wrong version of java.util.zip.CRC32C"); + + return table; +} + +//------------------------------inline_updateBytesCRC32C----------------------- +// +// Calculate CRC32C for byte[] array. +// int java.util.zip.CRC32C.updateBytes(int crc, byte[] buf, int off, int end) +// +bool LibraryCallKit::inline_updateBytesCRC32C() { + assert(UseCRC32CIntrinsics, "need CRC32C instruction support"); + assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters"); + assert(callee()->holder()->is_loaded(), "CRC32C class must be loaded"); + // no receiver since it is a static method + Node* crc = argument(0); // type: int + Node* src = argument(1); // type: oop + Node* offset = argument(2); // type: int + Node* end = argument(3); // type: int + + Node* length = _gvn.transform(new SubINode(end, offset)); + + const Type* src_type = src->Value(&_gvn); + const TypeAryPtr* top_src = src_type->isa_aryptr(); + if (top_src == NULL || top_src->klass() == NULL) { + // failed array check + return false; + } + + // Figure out the size and type of the elements we will be copying. + BasicType src_elem = src_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type(); + if (src_elem != T_BYTE) { + return false; + } + + // 'src_start' points to src array + scaled offset + Node* src_start = array_element_address(src, offset, src_elem); + + // static final int[] byteTable in class CRC32C + Node* table = get_table_from_crc32c_class(callee()->holder()); + Node* table_start = array_element_address(table, intcon(0), T_INT); + + // We assume that range check is done by caller. + // TODO: generate range check (offset+length < src.length) in debug VM. + + // Call the stub. + address stubAddr = StubRoutines::updateBytesCRC32C(); + const char *stubName = "updateBytesCRC32C"; + + Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesCRC32C_Type(), + stubAddr, stubName, TypePtr::BOTTOM, + crc, src_start, length, table_start); + Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms)); + set_result(result); + return true; +} + +//------------------------------inline_updateDirectByteBufferCRC32C----------------------- +// +// Calculate CRC32C for DirectByteBuffer. +// int java.util.zip.CRC32C.updateDirectByteBuffer(int crc, long buf, int off, int end) +// +bool LibraryCallKit::inline_updateDirectByteBufferCRC32C() { + assert(UseCRC32CIntrinsics, "need CRC32C instruction support"); + assert(callee()->signature()->size() == 5, "updateDirectByteBuffer has 4 parameters and one is long"); + assert(callee()->holder()->is_loaded(), "CRC32C class must be loaded"); + // no receiver since it is a static method + Node* crc = argument(0); // type: int + Node* src = argument(1); // type: long + Node* offset = argument(3); // type: int + Node* end = argument(4); // type: int + + Node* length = _gvn.transform(new SubINode(end, offset)); + + src = ConvL2X(src); // adjust Java long to machine word + Node* base = _gvn.transform(new CastX2PNode(src)); + offset = ConvI2X(offset); + + // 'src_start' points to src array + scaled offset + Node* src_start = basic_plus_adr(top(), base, offset); + + // static final int[] byteTable in class CRC32C + Node* table = get_table_from_crc32c_class(callee()->holder()); + Node* table_start = array_element_address(table, intcon(0), T_INT); + + // Call the stub. + address stubAddr = StubRoutines::updateBytesCRC32C(); + const char *stubName = "updateBytesCRC32C"; + + Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesCRC32C_Type(), + stubAddr, stubName, TypePtr::BOTTOM, + crc, src_start, length, table_start); + Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms)); + set_result(result); + return true; +} + //----------------------------inline_reference_get---------------------------- // public T java.lang.ref.Reference.get(); bool LibraryCallKit::inline_reference_get() { @@ -5571,18 +5684,28 @@ bool LibraryCallKit::inline_reference_get() { Node * LibraryCallKit::load_field_from_object(Node * fromObj, const char * fieldName, const char * fieldTypeString, - bool is_exact=true, bool is_static=false) { + bool is_exact=true, bool is_static=false, + ciInstanceKlass * fromKls=NULL) { + if (fromKls == NULL) { + const TypeInstPtr* tinst = _gvn.type(fromObj)->isa_instptr(); + assert(tinst != NULL, "obj is null"); + assert(tinst->klass()->is_loaded(), "obj is not loaded"); + assert(!is_exact || tinst->klass_is_exact(), "klass not exact"); + fromKls = tinst->klass()->as_instance_klass(); + } else { + assert(is_static, "only for static field access"); + } + ciField* field = fromKls->get_field_by_name(ciSymbol::make(fieldName), + ciSymbol::make(fieldTypeString), + is_static); - const TypeInstPtr* tinst = _gvn.type(fromObj)->isa_instptr(); - assert(tinst != NULL, "obj is null"); - assert(tinst->klass()->is_loaded(), "obj is not loaded"); - assert(!is_exact || tinst->klass_is_exact(), "klass not exact"); - - ciField* field = tinst->klass()->as_instance_klass()->get_field_by_name(ciSymbol::make(fieldName), - ciSymbol::make(fieldTypeString), - is_static); - if (field == NULL) return (Node *) NULL; assert (field != NULL, "undefined field"); + if (field == NULL) return (Node *) NULL; + + if (is_static) { + const TypeInstPtr* tip = TypeInstPtr::make(fromKls->java_mirror()); + fromObj = makecon(tip); + } // Next code copied from Parse::do_get_xxx(): diff --git a/hotspot/src/share/vm/opto/runtime.cpp b/hotspot/src/share/vm/opto/runtime.cpp index e0a4ee454a3..56bf22b964a 100644 --- a/hotspot/src/share/vm/opto/runtime.cpp +++ b/hotspot/src/share/vm/opto/runtime.cpp @@ -851,6 +851,29 @@ const TypeFunc* OptoRuntime::updateBytesCRC32_Type() { return TypeFunc::make(domain, range); } +/** + * int updateBytesCRC32C(int crc, byte* buf, int len, int* table) + */ +const TypeFunc* OptoRuntime::updateBytesCRC32C_Type() { + // create input type (domain) + int num_args = 4; + int argcnt = num_args; + const Type** fields = TypeTuple::fields(argcnt); + int argp = TypeFunc::Parms; + fields[argp++] = TypeInt::INT; // crc + fields[argp++] = TypePtr::NOTNULL; // buf + fields[argp++] = TypeInt::INT; // len + fields[argp++] = TypePtr::NOTNULL; // table + assert(argp == TypeFunc::Parms+argcnt, "correct decoding"); + const TypeTuple* domain = TypeTuple::make(TypeFunc::Parms+argcnt, fields); + + // result type needed + fields = TypeTuple::fields(1); + fields[TypeFunc::Parms+0] = TypeInt::INT; // crc result + const TypeTuple* range = TypeTuple::make(TypeFunc::Parms+1, fields); + return TypeFunc::make(domain, range); +} + // for cipherBlockChaining calls of aescrypt encrypt/decrypt, four pointers and a length, returning int const TypeFunc* OptoRuntime::cipherBlockChaining_aescrypt_Type() { // create input type (domain) diff --git a/hotspot/src/share/vm/opto/runtime.hpp b/hotspot/src/share/vm/opto/runtime.hpp index e412dbc82f8..424bf822b0d 100644 --- a/hotspot/src/share/vm/opto/runtime.hpp +++ b/hotspot/src/share/vm/opto/runtime.hpp @@ -319,6 +319,7 @@ private: static const TypeFunc* ghash_processBlocks_Type(); static const TypeFunc* updateBytesCRC32_Type(); + static const TypeFunc* updateBytesCRC32C_Type(); // leaf on stack replacement interpreter accessor types static const TypeFunc* osr_end_Type(); diff --git a/hotspot/src/share/vm/runtime/globals.hpp b/hotspot/src/share/vm/runtime/globals.hpp index 5bbefd9ecf2..be8b18e7ee5 100644 --- a/hotspot/src/share/vm/runtime/globals.hpp +++ b/hotspot/src/share/vm/runtime/globals.hpp @@ -848,6 +848,9 @@ public: product(bool, UseCRC32Intrinsics, false, \ "use intrinsics for java.util.zip.CRC32") \ \ + product(bool, UseCRC32CIntrinsics, false, \ + "use intrinsics for java.util.zip.CRC32C") \ + \ develop(bool, TraceCallFixup, false, \ "Trace all call fixups") \ \ diff --git a/hotspot/src/share/vm/runtime/stubRoutines.cpp b/hotspot/src/share/vm/runtime/stubRoutines.cpp index 7e2ff57ecd1..f920d130ea9 100644 --- a/hotspot/src/share/vm/runtime/stubRoutines.cpp +++ b/hotspot/src/share/vm/runtime/stubRoutines.cpp @@ -137,6 +137,8 @@ address StubRoutines::_sha512_implCompressMB = NULL; address StubRoutines::_updateBytesCRC32 = NULL; address StubRoutines::_crc_table_adr = NULL; +address StubRoutines::_updateBytesCRC32C = NULL; + address StubRoutines::_multiplyToLen = NULL; address StubRoutines::_squareToLen = NULL; address StubRoutines::_mulAdd = NULL; diff --git a/hotspot/src/share/vm/runtime/stubRoutines.hpp b/hotspot/src/share/vm/runtime/stubRoutines.hpp index 66723532ed6..22ad6c04d29 100644 --- a/hotspot/src/share/vm/runtime/stubRoutines.hpp +++ b/hotspot/src/share/vm/runtime/stubRoutines.hpp @@ -197,6 +197,8 @@ class StubRoutines: AllStatic { static address _updateBytesCRC32; static address _crc_table_adr; + static address _updateBytesCRC32C; + static address _multiplyToLen; static address _squareToLen; static address _mulAdd; @@ -359,6 +361,8 @@ class StubRoutines: AllStatic { static address updateBytesCRC32() { return _updateBytesCRC32; } static address crc_table_addr() { return _crc_table_adr; } + static address updateBytesCRC32C() { return _updateBytesCRC32C; } + static address multiplyToLen() {return _multiplyToLen; } static address squareToLen() {return _squareToLen; } static address mulAdd() {return _mulAdd; } diff --git a/hotspot/src/share/vm/runtime/vmStructs.cpp b/hotspot/src/share/vm/runtime/vmStructs.cpp index a2943c206b2..d0da0c6e05a 100644 --- a/hotspot/src/share/vm/runtime/vmStructs.cpp +++ b/hotspot/src/share/vm/runtime/vmStructs.cpp @@ -830,6 +830,7 @@ typedef CompactHashtable SymbolCompactHashTable; static_field(StubRoutines, _ghash_processBlocks, address) \ static_field(StubRoutines, _updateBytesCRC32, address) \ static_field(StubRoutines, _crc_table_adr, address) \ + static_field(StubRoutines, _updateBytesCRC32C, address) \ static_field(StubRoutines, _multiplyToLen, address) \ static_field(StubRoutines, _squareToLen, address) \ static_field(StubRoutines, _mulAdd, address) \ diff --git a/hotspot/test/compiler/intrinsics/crc32c/TestCRC32C.java b/hotspot/test/compiler/intrinsics/crc32c/TestCRC32C.java new file mode 100644 index 00000000000..676f541937c --- /dev/null +++ b/hotspot/test/compiler/intrinsics/crc32c/TestCRC32C.java @@ -0,0 +1,221 @@ +/* + * Copyright (c) 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 + * @bug 8073583 + * @summary C2 support for CRC32C on SPARC + * + * @run main/othervm/timeout=600 -Xbatch TestCRC32C -m + */ + +import java.nio.ByteBuffer; +import java.util.zip.Checksum; +import java.util.zip.CRC32C; + +public class TestCRC32C { + public static void main(String[] args) { + int offset = Integer.getInteger("offset", 0); + int msgSize = Integer.getInteger("msgSize", 512); + boolean multi = false; + int iters = 20000; + int warmupIters = 20000; + + if (args.length > 0) { + if (args[0].equals("-m")) { + multi = true; + } else { + iters = Integer.valueOf(args[0]); + } + if (args.length > 1) { + warmupIters = Integer.valueOf(args[1]); + } + } + + if (multi) { + test_multi(warmupIters); + return; + } + + System.out.println(" offset = " + offset); + System.out.println("msgSize = " + msgSize + " bytes"); + System.out.println(" iters = " + iters); + + byte[] b = initializedBytes(msgSize, offset); + + CRC32C crc0 = new CRC32C(); + CRC32C crc1 = new CRC32C(); + CRC32C crc2 = new CRC32C(); + + crc0.update(b, offset, msgSize); + + System.out.println("-------------------------------------------------------"); + + /* warm up */ + for (int i = 0; i < warmupIters; i++) { + crc1.reset(); + crc1.update(b, offset, msgSize); + } + + /* measure performance */ + long start = System.nanoTime(); + for (int i = 0; i < iters; i++) { + crc1.reset(); + crc1.update(b, offset, msgSize); + } + long end = System.nanoTime(); + double total = (double)(end - start)/1e9; // in seconds + double thruput = (double)msgSize*iters/1e6/total; // in MB/s + System.out.println("CRC32C.update(byte[]) runtime = " + total + " seconds"); + System.out.println("CRC32C.update(byte[]) throughput = " + thruput + " MB/s"); + + /* check correctness */ + for (int i = 0; i < iters; i++) { + crc1.reset(); + crc1.update(b, offset, msgSize); + if (!check(crc0, crc1)) break; + } + report("CRCs", crc0, crc1); + + System.out.println("-------------------------------------------------------"); + + ByteBuffer buf = ByteBuffer.allocateDirect(msgSize); + buf.put(b, offset, msgSize); + buf.flip(); + + /* warm up */ + for (int i = 0; i < warmupIters; i++) { + crc2.reset(); + crc2.update(buf); + buf.rewind(); + } + + /* measure performance */ + start = System.nanoTime(); + for (int i = 0; i < iters; i++) { + crc2.reset(); + crc2.update(buf); + buf.rewind(); + } + end = System.nanoTime(); + total = (double)(end - start)/1e9; // in seconds + thruput = (double)msgSize*iters/1e6/total; // in MB/s + System.out.println("CRC32C.update(ByteBuffer) runtime = " + total + " seconds"); + System.out.println("CRC32C.update(ByteBuffer) throughput = " + thruput + " MB/s"); + + /* check correctness */ + for (int i = 0; i < iters; i++) { + crc2.reset(); + crc2.update(buf); + buf.rewind(); + if (!check(crc0, crc2)) break; + } + report("CRCs", crc0, crc2); + + System.out.println("-------------------------------------------------------"); + } + + private static void report(String s, Checksum crc0, Checksum crc1) { + System.out.printf("%s: crc0 = %08x, crc1 = %08x\n", + s, crc0.getValue(), crc1.getValue()); + } + + private static boolean check(Checksum crc0, Checksum crc1) { + if (crc0.getValue() != crc1.getValue()) { + System.err.printf("ERROR: crc0 = %08x, crc1 = %08x\n", + crc0.getValue(), crc1.getValue()); + return false; + } + return true; + } + + private static byte[] initializedBytes(int M, int offset) { + byte[] bytes = new byte[M + offset]; + for (int i = 0; i < offset; i++) { + bytes[i] = (byte) i; + } + for (int i = offset; i < bytes.length; i++) { + bytes[i] = (byte) (i - offset); + } + return bytes; + } + + private static void test_multi(int iters) { + int len1 = 8; // the 8B/iteration loop + int len2 = 32; // the 32B/iteration loop + int len3 = 4096; // the 4KB/iteration loop + + byte[] b = initializedBytes(len3*16, 0); + int[] offsets = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 16, 32, 64, 128, 256, 512 }; + int[] sizes = { 0, 1, 2, 3, 4, 5, 6, 7, + len1, len1+1, len1+2, len1+3, len1+4, len1+5, len1+6, len1+7, + len1*2, len1*2+1, len1*2+3, len1*2+5, len1*2+7, + len2, len2+1, len2+3, len2+5, len2+7, + len2*2, len2*4, len2*8, len2*16, len2*32, len2*64, + len3, len3+1, len3+3, len3+5, len3+7, + len3*2, len3*4, len3*8, + len1+len2, len1+len2+1, len1+len2+3, len1+len2+5, len1+len2+7, + len1+len3, len1+len3+1, len1+len3+3, len1+len3+5, len1+len3+7, + len2+len3, len2+len3+1, len2+len3+3, len2+len3+5, len2+len3+7, + len1+len2+len3, len1+len2+len3+1, len1+len2+len3+3, + len1+len2+len3+5, len1+len2+len3+7, + (len1+len2+len3)*2, (len1+len2+len3)*2+1, (len1+len2+len3)*2+3, + (len1+len2+len3)*2+5, (len1+len2+len3)*2+7, + (len1+len2+len3)*3, (len1+len2+len3)*3-1, (len1+len2+len3)*3-3, + (len1+len2+len3)*3-5, (len1+len2+len3)*3-7 }; + CRC32C[] crc0 = new CRC32C[offsets.length*sizes.length]; + CRC32C[] crc1 = new CRC32C[offsets.length*sizes.length]; + int i, j, k; + + System.out.printf("testing %d cases ...\n", offsets.length*sizes.length); + + /* set the result from interpreter as reference */ + for (i = 0; i < offsets.length; i++) { + for (j = 0; j < sizes.length; j++) { + crc0[i*sizes.length + j] = new CRC32C(); + crc1[i*sizes.length + j] = new CRC32C(); + crc0[i*sizes.length + j].update(b, offsets[i], sizes[j]); + } + } + + /* warm up the JIT compiler and get result */ + for (k = 0; k < iters; k++) { + for (i = 0; i < offsets.length; i++) { + for (j = 0; j < sizes.length; j++) { + crc1[i*sizes.length + j].reset(); + crc1[i*sizes.length + j].update(b, offsets[i], sizes[j]); + } + } + } + + /* check correctness */ + for (i = 0; i < offsets.length; i++) { + for (j = 0; j < sizes.length; j++) { + if (!check(crc0[i*sizes.length + j], crc1[i*sizes.length + j])) { + System.out.printf("offsets[%d] = %d", i, offsets[i]); + System.out.printf("\tsizes[%d] = %d\n", j, sizes[j]); + } + } + } + } +} From 38d2a4cc99f30e13946c0eafd487b9c14de7a102 Mon Sep 17 00:00:00 2001 From: Ed Nevill Date: Thu, 25 Jun 2015 08:52:12 +0000 Subject: [PATCH 02/43] 8086087: aarch64: add support for 64 bit vectors Support 64 bit vectors Reviewed-by: kvn, aph --- hotspot/src/cpu/aarch64/vm/aarch64.ad | 815 ++++++++++++++++++++++++-- 1 file changed, 774 insertions(+), 41 deletions(-) diff --git a/hotspot/src/cpu/aarch64/vm/aarch64.ad b/hotspot/src/cpu/aarch64/vm/aarch64.ad index f555721eaa1..02fe907021b 100644 --- a/hotspot/src/cpu/aarch64/vm/aarch64.ad +++ b/hotspot/src/cpu/aarch64/vm/aarch64.ad @@ -865,6 +865,42 @@ reg_class double_reg( V31, V31_H ); +// Class for all 64bit vector registers +reg_class vectord_reg( + V0, V0_H, + V1, V1_H, + V2, V2_H, + V3, V3_H, + V4, V4_H, + V5, V5_H, + V6, V6_H, + V7, V7_H, + V8, V8_H, + V9, V9_H, + V10, V10_H, + V11, V11_H, + V12, V12_H, + V13, V13_H, + V14, V14_H, + V15, V15_H, + V16, V16_H, + V17, V17_H, + V18, V18_H, + V19, V19_H, + V20, V20_H, + V21, V21_H, + V22, V22_H, + V23, V23_H, + V24, V24_H, + V25, V25_H, + V26, V26_H, + V27, V27_H, + V28, V28_H, + V29, V29_H, + V30, V30_H, + V31, V31_H +); + // Class for all 128bit vector registers reg_class vectorx_reg( V0, V0_H, V0_J, V0_K, @@ -2133,40 +2169,48 @@ uint MachSpillCopyNode::implementation(CodeBuffer *cbuf, PhaseRegAlloc *ra_, boo if (bottom_type()->isa_vect() != NULL) { uint len = 4; + uint ireg = ideal_reg(); + assert(ireg == Op_VecD || ireg == Op_VecX, "must be 64 bit or 128 bit vector"); if (cbuf) { MacroAssembler _masm(cbuf); - uint ireg = ideal_reg(); assert((src_lo_rc != rc_int && dst_lo_rc != rc_int), "sanity"); - assert(ireg == Op_VecX, "sanity"); if (src_lo_rc == rc_stack && dst_lo_rc == rc_stack) { // stack->stack int src_offset = ra_->reg2offset(src_lo); int dst_offset = ra_->reg2offset(dst_lo); assert((src_offset & 7) && (dst_offset & 7), "unaligned stack offset"); len = 8; - if (src_offset < 512) { - __ ldp(rscratch1, rscratch2, Address(sp, src_offset)); - } else { + if (ireg == Op_VecD) { __ ldr(rscratch1, Address(sp, src_offset)); - __ ldr(rscratch2, Address(sp, src_offset+4)); - len += 4; - } - if (dst_offset < 512) { - __ stp(rscratch1, rscratch2, Address(sp, dst_offset)); - } else { __ str(rscratch1, Address(sp, dst_offset)); - __ str(rscratch2, Address(sp, dst_offset+4)); - len += 4; + } else { + if (src_offset < 512) { + __ ldp(rscratch1, rscratch2, Address(sp, src_offset)); + } else { + __ ldr(rscratch1, Address(sp, src_offset)); + __ ldr(rscratch2, Address(sp, src_offset+4)); + len += 4; + } + if (dst_offset < 512) { + __ stp(rscratch1, rscratch2, Address(sp, dst_offset)); + } else { + __ str(rscratch1, Address(sp, dst_offset)); + __ str(rscratch2, Address(sp, dst_offset+4)); + len += 4; + } } } else if (src_lo_rc == rc_float && dst_lo_rc == rc_float) { - __ orr(as_FloatRegister(Matcher::_regEncode[dst_lo]), __ T16B, + __ orr(as_FloatRegister(Matcher::_regEncode[dst_lo]), + ireg == Op_VecD ? __ T8B : __ T16B, as_FloatRegister(Matcher::_regEncode[src_lo]), as_FloatRegister(Matcher::_regEncode[src_lo])); } else if (src_lo_rc == rc_float && dst_lo_rc == rc_stack) { - __ str(as_FloatRegister(Matcher::_regEncode[src_lo]), __ Q, + __ str(as_FloatRegister(Matcher::_regEncode[src_lo]), + ireg == Op_VecD ? __ D : __ Q, Address(sp, ra_->reg2offset(dst_lo))); } else if (src_lo_rc == rc_stack && dst_lo_rc == rc_float) { - __ ldr(as_FloatRegister(Matcher::_regEncode[dst_lo]), __ Q, + __ ldr(as_FloatRegister(Matcher::_regEncode[dst_lo]), + ireg == Op_VecD ? __ D : __ Q, Address(sp, ra_->reg2offset(src_lo))); } else { ShouldNotReachHere(); @@ -2176,17 +2220,22 @@ uint MachSpillCopyNode::implementation(CodeBuffer *cbuf, PhaseRegAlloc *ra_, boo // stack->stack int src_offset = ra_->reg2offset(src_lo); int dst_offset = ra_->reg2offset(dst_lo); - if (src_offset < 512) { - st->print("ldp rscratch1, rscratch2, [sp, #%d]", src_offset); - } else { + if (ireg == Op_VecD) { st->print("ldr rscratch1, [sp, #%d]", src_offset); - st->print("\nldr rscratch2, [sp, #%d]", src_offset+4); - } - if (dst_offset < 512) { - st->print("\nstp rscratch1, rscratch2, [sp, #%d]", dst_offset); + st->print("str rscratch1, [sp, #%d]", dst_offset); } else { - st->print("\nstr rscratch1, [sp, #%d]", dst_offset); - st->print("\nstr rscratch2, [sp, #%d]", dst_offset+4); + if (src_offset < 512) { + st->print("ldp rscratch1, rscratch2, [sp, #%d]", src_offset); + } else { + st->print("ldr rscratch1, [sp, #%d]", src_offset); + st->print("\nldr rscratch2, [sp, #%d]", src_offset+4); + } + if (dst_offset < 512) { + st->print("\nstp rscratch1, rscratch2, [sp, #%d]", dst_offset); + } else { + st->print("\nstr rscratch1, [sp, #%d]", dst_offset); + st->print("\nstr rscratch2, [sp, #%d]", dst_offset+4); + } } st->print("\t# vector spill, stack to stack"); } else if (src_lo_rc == rc_float && dst_lo_rc == rc_float) { @@ -2638,17 +2687,22 @@ const int Matcher::max_vector_size(const BasicType bt) { return vector_width_in_bytes(bt)/type2aelembytes(bt); } const int Matcher::min_vector_size(const BasicType bt) { - //return (type2aelembytes(bt) == 1) ? 4 : 2; - // For the moment, only support 1 vector size, 128 bits - return max_vector_size(bt); +// For the moment limit the vector size to 8 bytes + int size = 8 / type2aelembytes(bt); + if (size < 2) size = 2; + return size; } // Vector ideal reg. const int Matcher::vector_ideal_reg(int len) { - return Op_VecX; + switch(len) { + case 8: return Op_VecD; + case 16: return Op_VecX; + } + ShouldNotReachHere(); + return 0; } -// Only lowest bits of xmm reg are used for vector shift count. const int Matcher::vector_shift_count_ideal_reg(int size) { return Op_VecX; } @@ -2660,9 +2714,7 @@ const bool Matcher::pass_original_key_for_aes() { // x86 supports misaligned vectors store/load. const bool Matcher::misaligned_vectors_ok() { - // TODO fixme - // return !AlignVector; // can be changed by flag - return false; + return !AlignVector; // can be changed by flag } // false => size gets scaled to BytesPerLong, ok. @@ -3073,13 +3125,13 @@ encode %{ as_Register($mem$$base), $mem$$index, $mem$$scale, $mem$$disp); %} - enc_class aarch64_enc_ldrvS(vecX dst, memory mem) %{ + enc_class aarch64_enc_ldrvS(vecD dst, memory mem) %{ FloatRegister dst_reg = as_FloatRegister($dst$$reg); loadStore(MacroAssembler(&cbuf), &MacroAssembler::ldr, dst_reg, MacroAssembler::S, $mem->opcode(), as_Register($mem$$base), $mem$$index, $mem$$scale, $mem$$disp); %} - enc_class aarch64_enc_ldrvD(vecX dst, memory mem) %{ + enc_class aarch64_enc_ldrvD(vecD dst, memory mem) %{ FloatRegister dst_reg = as_FloatRegister($dst$$reg); loadStore(MacroAssembler(&cbuf), &MacroAssembler::ldr, dst_reg, MacroAssembler::D, $mem->opcode(), as_Register($mem$$base), $mem$$index, $mem$$scale, $mem$$disp); @@ -3159,13 +3211,13 @@ encode %{ as_Register($mem$$base), $mem$$index, $mem$$scale, $mem$$disp); %} - enc_class aarch64_enc_strvS(vecX src, memory mem) %{ + enc_class aarch64_enc_strvS(vecD src, memory mem) %{ FloatRegister src_reg = as_FloatRegister($src$$reg); loadStore(MacroAssembler(&cbuf), &MacroAssembler::str, src_reg, MacroAssembler::S, $mem->opcode(), as_Register($mem$$base), $mem$$index, $mem$$scale, $mem$$disp); %} - enc_class aarch64_enc_strvD(vecX src, memory mem) %{ + enc_class aarch64_enc_strvD(vecD src, memory mem) %{ FloatRegister src_reg = as_FloatRegister($src$$reg); loadStore(MacroAssembler(&cbuf), &MacroAssembler::str, src_reg, MacroAssembler::D, $mem->opcode(), as_Register($mem$$base), $mem$$index, $mem$$scale, $mem$$disp); @@ -5187,6 +5239,16 @@ operand vRegD() interface(REG_INTER); %} +operand vecD() +%{ + constraint(ALLOC_IN_RC(vectord_reg)); + match(VecD); + + op_cost(0); + format %{ %} + interface(REG_INTER); +%} + operand vecX() %{ constraint(ALLOC_IN_RC(vectorx_reg)); @@ -13194,7 +13256,7 @@ instruct tlsLoadP(thread_RegP dst) // ====================VECTOR INSTRUCTIONS===================================== // Load vector (32 bits) -instruct loadV4(vecX dst, vmem mem) +instruct loadV4(vecD dst, vmem mem) %{ predicate(n->as_LoadVector()->memory_size() == 4); match(Set dst (LoadVector mem)); @@ -13205,7 +13267,7 @@ instruct loadV4(vecX dst, vmem mem) %} // Load vector (64 bits) -instruct loadV8(vecX dst, vmem mem) +instruct loadV8(vecD dst, vmem mem) %{ predicate(n->as_LoadVector()->memory_size() == 8); match(Set dst (LoadVector mem)); @@ -13227,7 +13289,7 @@ instruct loadV16(vecX dst, vmem mem) %} // Store Vector (32 bits) -instruct storeV4(vecX src, vmem mem) +instruct storeV4(vecD src, vmem mem) %{ predicate(n->as_StoreVector()->memory_size() == 4); match(Set mem (StoreVector mem src)); @@ -13238,7 +13300,7 @@ instruct storeV4(vecX src, vmem mem) %} // Store Vector (64 bits) -instruct storeV8(vecX src, vmem mem) +instruct storeV8(vecD src, vmem mem) %{ predicate(n->as_StoreVector()->memory_size() == 8); match(Set mem (StoreVector mem src)); @@ -13259,8 +13321,22 @@ instruct storeV16(vecX src, vmem mem) ins_pipe(pipe_class_memory); %} +instruct replicate8B(vecD dst, iRegIorL2I src) +%{ + predicate(n->as_Vector()->length() == 4 || + n->as_Vector()->length() == 8); + match(Set dst (ReplicateB src)); + ins_cost(INSN_COST); + format %{ "dup $dst, $src\t# vector (8B)" %} + ins_encode %{ + __ dup(as_FloatRegister($dst$$reg), __ T8B, as_Register($src$$reg)); + %} + ins_pipe(pipe_class_default); +%} + instruct replicate16B(vecX dst, iRegIorL2I src) %{ + predicate(n->as_Vector()->length() == 16); match(Set dst (ReplicateB src)); ins_cost(INSN_COST); format %{ "dup $dst, $src\t# vector (16B)" %} @@ -13270,8 +13346,22 @@ instruct replicate16B(vecX dst, iRegIorL2I src) ins_pipe(pipe_class_default); %} +instruct replicate8B_imm(vecD dst, immI con) +%{ + predicate(n->as_Vector()->length() == 4 || + n->as_Vector()->length() == 8); + match(Set dst (ReplicateB con)); + ins_cost(INSN_COST); + format %{ "movi $dst, $con\t# vector(8B)" %} + ins_encode %{ + __ mov(as_FloatRegister($dst$$reg), __ T8B, $con$$constant & 0xff); + %} + ins_pipe(pipe_class_default); +%} + instruct replicate16B_imm(vecX dst, immI con) %{ + predicate(n->as_Vector()->length() == 16); match(Set dst (ReplicateB con)); ins_cost(INSN_COST); format %{ "movi $dst, $con\t# vector(16B)" %} @@ -13281,8 +13371,22 @@ instruct replicate16B_imm(vecX dst, immI con) ins_pipe(pipe_class_default); %} +instruct replicate4S(vecD dst, iRegIorL2I src) +%{ + predicate(n->as_Vector()->length() == 2 || + n->as_Vector()->length() == 4); + match(Set dst (ReplicateS src)); + ins_cost(INSN_COST); + format %{ "dup $dst, $src\t# vector (4S)" %} + ins_encode %{ + __ dup(as_FloatRegister($dst$$reg), __ T4H, as_Register($src$$reg)); + %} + ins_pipe(pipe_class_default); +%} + instruct replicate8S(vecX dst, iRegIorL2I src) %{ + predicate(n->as_Vector()->length() == 8); match(Set dst (ReplicateS src)); ins_cost(INSN_COST); format %{ "dup $dst, $src\t# vector (8S)" %} @@ -13292,8 +13396,22 @@ instruct replicate8S(vecX dst, iRegIorL2I src) ins_pipe(pipe_class_default); %} +instruct replicate4S_imm(vecD dst, immI con) +%{ + predicate(n->as_Vector()->length() == 2 || + n->as_Vector()->length() == 4); + match(Set dst (ReplicateS con)); + ins_cost(INSN_COST); + format %{ "movi $dst, $con\t# vector(4H)" %} + ins_encode %{ + __ mov(as_FloatRegister($dst$$reg), __ T4H, $con$$constant & 0xffff); + %} + ins_pipe(pipe_class_default); +%} + instruct replicate8S_imm(vecX dst, immI con) %{ + predicate(n->as_Vector()->length() == 8); match(Set dst (ReplicateS con)); ins_cost(INSN_COST); format %{ "movi $dst, $con\t# vector(8H)" %} @@ -13303,8 +13421,21 @@ instruct replicate8S_imm(vecX dst, immI con) ins_pipe(pipe_class_default); %} +instruct replicate2I(vecD dst, iRegIorL2I src) +%{ + predicate(n->as_Vector()->length() == 2); + match(Set dst (ReplicateI src)); + ins_cost(INSN_COST); + format %{ "dup $dst, $src\t# vector (2I)" %} + ins_encode %{ + __ dup(as_FloatRegister($dst$$reg), __ T2S, as_Register($src$$reg)); + %} + ins_pipe(pipe_class_default); +%} + instruct replicate4I(vecX dst, iRegIorL2I src) %{ + predicate(n->as_Vector()->length() == 4); match(Set dst (ReplicateI src)); ins_cost(INSN_COST); format %{ "dup $dst, $src\t# vector (4I)" %} @@ -13314,8 +13445,21 @@ instruct replicate4I(vecX dst, iRegIorL2I src) ins_pipe(pipe_class_default); %} +instruct replicate2I_imm(vecD dst, immI con) +%{ + predicate(n->as_Vector()->length() == 2); + match(Set dst (ReplicateI con)); + ins_cost(INSN_COST); + format %{ "movi $dst, $con\t# vector(2I)" %} + ins_encode %{ + __ mov(as_FloatRegister($dst$$reg), __ T2S, $con$$constant); + %} + ins_pipe(pipe_class_default); +%} + instruct replicate4I_imm(vecX dst, immI con) %{ + predicate(n->as_Vector()->length() == 4); match(Set dst (ReplicateI con)); ins_cost(INSN_COST); format %{ "movi $dst, $con\t# vector(4I)" %} @@ -13327,6 +13471,7 @@ instruct replicate4I_imm(vecX dst, immI con) instruct replicate2L(vecX dst, iRegL src) %{ + predicate(n->as_Vector()->length() == 2); match(Set dst (ReplicateL src)); ins_cost(INSN_COST); format %{ "dup $dst, $src\t# vector (2L)" %} @@ -13338,6 +13483,7 @@ instruct replicate2L(vecX dst, iRegL src) instruct replicate2L_zero(vecX dst, immI0 zero) %{ + predicate(n->as_Vector()->length() == 2); match(Set dst (ReplicateI zero)); ins_cost(INSN_COST); format %{ "movi $dst, $zero\t# vector(4I)" %} @@ -13349,8 +13495,22 @@ instruct replicate2L_zero(vecX dst, immI0 zero) ins_pipe(pipe_class_default); %} +instruct replicate2F(vecD dst, vRegF src) +%{ + predicate(n->as_Vector()->length() == 2); + match(Set dst (ReplicateF src)); + ins_cost(INSN_COST); + format %{ "dup $dst, $src\t# vector (2F)" %} + ins_encode %{ + __ dup(as_FloatRegister($dst$$reg), __ T2S, + as_FloatRegister($src$$reg)); + %} + ins_pipe(pipe_class_default); +%} + instruct replicate4F(vecX dst, vRegF src) %{ + predicate(n->as_Vector()->length() == 4); match(Set dst (ReplicateF src)); ins_cost(INSN_COST); format %{ "dup $dst, $src\t# vector (4F)" %} @@ -13363,6 +13523,7 @@ instruct replicate4F(vecX dst, vRegF src) instruct replicate2D(vecX dst, vRegD src) %{ + predicate(n->as_Vector()->length() == 2); match(Set dst (ReplicateD src)); ins_cost(INSN_COST); format %{ "dup $dst, $src\t# vector (2D)" %} @@ -13375,6 +13536,25 @@ instruct replicate2D(vecX dst, vRegD src) // ====================REDUCTION ARITHMETIC==================================== +instruct reduce_add2I(iRegINoSp dst, iRegIorL2I src1, vecD src2, iRegI tmp, iRegI tmp2) +%{ + match(Set dst (AddReductionVI src1 src2)); + ins_cost(INSN_COST); + effect(TEMP tmp, TEMP tmp2); + format %{ "umov $tmp, $src2, S, 0\n\t" + "umov $tmp2, $src2, S, 1\n\t" + "addw $dst, $src1, $tmp\n\t" + "addw $dst, $dst, $tmp2\t add reduction2i" + %} + ins_encode %{ + __ umov($tmp$$Register, as_FloatRegister($src2$$reg), __ S, 0); + __ umov($tmp2$$Register, as_FloatRegister($src2$$reg), __ S, 1); + __ addw($dst$$Register, $src1$$Register, $tmp$$Register); + __ addw($dst$$Register, $dst$$Register, $tmp2$$Register); + %} + ins_pipe(pipe_class_default); +%} + instruct reduce_add4I(iRegINoSp dst, iRegIorL2I src1, vecX src2, vecX tmp, iRegI tmp2) %{ match(Set dst (AddReductionVI src1 src2)); @@ -13393,6 +13573,25 @@ instruct reduce_add4I(iRegINoSp dst, iRegIorL2I src1, vecX src2, vecX tmp, iRegI ins_pipe(pipe_class_default); %} +instruct reduce_mul2I(iRegINoSp dst, iRegIorL2I src1, vecD src2, iRegI tmp) +%{ + match(Set dst (MulReductionVI src1 src2)); + ins_cost(INSN_COST); + effect(TEMP tmp, TEMP dst); + format %{ "umov $tmp, $src2, S, 0\n\t" + "mul $dst, $tmp, $src1\n\t" + "umov $tmp, $src2, S, 1\n\t" + "mul $dst, $tmp, $dst\t mul reduction2i\n\t" + %} + ins_encode %{ + __ umov($tmp$$Register, as_FloatRegister($src2$$reg), __ S, 0); + __ mul($dst$$Register, $tmp$$Register, $src1$$Register); + __ umov($tmp$$Register, as_FloatRegister($src2$$reg), __ S, 1); + __ mul($dst$$Register, $tmp$$Register, $dst$$Register); + %} + ins_pipe(pipe_class_default); +%} + instruct reduce_mul4I(iRegINoSp dst, iRegIorL2I src1, vecX src2, vecX tmp, iRegI tmp2) %{ match(Set dst (MulReductionVI src1 src2)); @@ -13418,6 +13617,26 @@ instruct reduce_mul4I(iRegINoSp dst, iRegIorL2I src1, vecX src2, vecX tmp, iRegI ins_pipe(pipe_class_default); %} +instruct reduce_add2F(vRegF dst, vRegF src1, vecD src2, vecD tmp) +%{ + match(Set dst (AddReductionVF src1 src2)); + ins_cost(INSN_COST); + effect(TEMP tmp, TEMP dst); + format %{ "fadds $dst, $src1, $src2\n\t" + "ins $tmp, S, $src2, 0, 1\n\t" + "fadds $dst, $dst, $tmp\t add reduction2f" + %} + ins_encode %{ + __ fadds(as_FloatRegister($dst$$reg), + as_FloatRegister($src1$$reg), as_FloatRegister($src2$$reg)); + __ ins(as_FloatRegister($tmp$$reg), __ S, + as_FloatRegister($src2$$reg), 0, 1); + __ fadds(as_FloatRegister($dst$$reg), + as_FloatRegister($dst$$reg), as_FloatRegister($tmp$$reg)); + %} + ins_pipe(pipe_class_default); +%} + instruct reduce_add4F(vRegF dst, vRegF src1, vecX src2, vecX tmp) %{ match(Set dst (AddReductionVF src1 src2)); @@ -13450,6 +13669,26 @@ instruct reduce_add4F(vRegF dst, vRegF src1, vecX src2, vecX tmp) ins_pipe(pipe_class_default); %} +instruct reduce_mul2F(vRegF dst, vRegF src1, vecD src2, vecD tmp) +%{ + match(Set dst (MulReductionVF src1 src2)); + ins_cost(INSN_COST); + effect(TEMP tmp, TEMP dst); + format %{ "fmuls $dst, $src1, $src2\n\t" + "ins $tmp, S, $src2, 0, 1\n\t" + "fmuls $dst, $dst, $tmp\t add reduction4f" + %} + ins_encode %{ + __ fmuls(as_FloatRegister($dst$$reg), + as_FloatRegister($src1$$reg), as_FloatRegister($src2$$reg)); + __ ins(as_FloatRegister($tmp$$reg), __ S, + as_FloatRegister($src2$$reg), 0, 1); + __ fmuls(as_FloatRegister($dst$$reg), + as_FloatRegister($dst$$reg), as_FloatRegister($tmp$$reg)); + %} + ins_pipe(pipe_class_default); +%} + instruct reduce_mul4F(vRegF dst, vRegF src1, vecX src2, vecX tmp) %{ match(Set dst (MulReductionVF src1 src2)); @@ -13526,8 +13765,24 @@ instruct reduce_mul2D(vRegD dst, vRegD src1, vecX src2, vecX tmp) // --------------------------------- ADD -------------------------------------- +instruct vadd8B(vecD dst, vecD src1, vecD src2) +%{ + predicate(n->as_Vector()->length() == 4 || + n->as_Vector()->length() == 8); + match(Set dst (AddVB src1 src2)); + ins_cost(INSN_COST); + format %{ "addv $dst,$src1,$src2\t# vector (8B)" %} + ins_encode %{ + __ addv(as_FloatRegister($dst$$reg), __ T8B, + as_FloatRegister($src1$$reg), + as_FloatRegister($src2$$reg)); + %} + ins_pipe(pipe_class_default); +%} + instruct vadd16B(vecX dst, vecX src1, vecX src2) %{ + predicate(n->as_Vector()->length() == 16); match(Set dst (AddVB src1 src2)); ins_cost(INSN_COST); format %{ "addv $dst,$src1,$src2\t# vector (16B)" %} @@ -13539,8 +13794,24 @@ instruct vadd16B(vecX dst, vecX src1, vecX src2) ins_pipe(pipe_class_default); %} +instruct vadd4S(vecD dst, vecD src1, vecD src2) +%{ + predicate(n->as_Vector()->length() == 2 || + n->as_Vector()->length() == 4); + match(Set dst (AddVS src1 src2)); + ins_cost(INSN_COST); + format %{ "addv $dst,$src1,$src2\t# vector (4H)" %} + ins_encode %{ + __ addv(as_FloatRegister($dst$$reg), __ T4H, + as_FloatRegister($src1$$reg), + as_FloatRegister($src2$$reg)); + %} + ins_pipe(pipe_class_default); +%} + instruct vadd8S(vecX dst, vecX src1, vecX src2) %{ + predicate(n->as_Vector()->length() == 8); match(Set dst (AddVS src1 src2)); ins_cost(INSN_COST); format %{ "addv $dst,$src1,$src2\t# vector (8H)" %} @@ -13552,8 +13823,23 @@ instruct vadd8S(vecX dst, vecX src1, vecX src2) ins_pipe(pipe_class_default); %} +instruct vadd2I(vecD dst, vecD src1, vecD src2) +%{ + predicate(n->as_Vector()->length() == 2); + match(Set dst (AddVI src1 src2)); + ins_cost(INSN_COST); + format %{ "addv $dst,$src1,$src2\t# vector (2S)" %} + ins_encode %{ + __ addv(as_FloatRegister($dst$$reg), __ T2S, + as_FloatRegister($src1$$reg), + as_FloatRegister($src2$$reg)); + %} + ins_pipe(pipe_class_default); +%} + instruct vadd4I(vecX dst, vecX src1, vecX src2) %{ + predicate(n->as_Vector()->length() == 4); match(Set dst (AddVI src1 src2)); ins_cost(INSN_COST); format %{ "addv $dst,$src1,$src2\t# vector (4S)" %} @@ -13567,6 +13853,7 @@ instruct vadd4I(vecX dst, vecX src1, vecX src2) instruct vadd2L(vecX dst, vecX src1, vecX src2) %{ + predicate(n->as_Vector()->length() == 2); match(Set dst (AddVL src1 src2)); ins_cost(INSN_COST); format %{ "addv $dst,$src1,$src2\t# vector (2L)" %} @@ -13578,8 +13865,23 @@ instruct vadd2L(vecX dst, vecX src1, vecX src2) ins_pipe(pipe_class_default); %} +instruct vadd2F(vecD dst, vecD src1, vecD src2) +%{ + predicate(n->as_Vector()->length() == 2); + match(Set dst (AddVF src1 src2)); + ins_cost(INSN_COST); + format %{ "fadd $dst,$src1,$src2\t# vector (2S)" %} + ins_encode %{ + __ fadd(as_FloatRegister($dst$$reg), __ T2S, + as_FloatRegister($src1$$reg), + as_FloatRegister($src2$$reg)); + %} + ins_pipe(pipe_class_default); +%} + instruct vadd4F(vecX dst, vecX src1, vecX src2) %{ + predicate(n->as_Vector()->length() == 4); match(Set dst (AddVF src1 src2)); ins_cost(INSN_COST); format %{ "fadd $dst,$src1,$src2\t# vector (4S)" %} @@ -13606,8 +13908,24 @@ instruct vadd2D(vecX dst, vecX src1, vecX src2) // --------------------------------- SUB -------------------------------------- +instruct vsub8B(vecD dst, vecD src1, vecD src2) +%{ + predicate(n->as_Vector()->length() == 4 || + n->as_Vector()->length() == 8); + match(Set dst (SubVB src1 src2)); + ins_cost(INSN_COST); + format %{ "subv $dst,$src1,$src2\t# vector (8B)" %} + ins_encode %{ + __ subv(as_FloatRegister($dst$$reg), __ T8B, + as_FloatRegister($src1$$reg), + as_FloatRegister($src2$$reg)); + %} + ins_pipe(pipe_class_default); +%} + instruct vsub16B(vecX dst, vecX src1, vecX src2) %{ + predicate(n->as_Vector()->length() == 16); match(Set dst (SubVB src1 src2)); ins_cost(INSN_COST); format %{ "subv $dst,$src1,$src2\t# vector (16B)" %} @@ -13619,8 +13937,24 @@ instruct vsub16B(vecX dst, vecX src1, vecX src2) ins_pipe(pipe_class_default); %} +instruct vsub4S(vecD dst, vecD src1, vecD src2) +%{ + predicate(n->as_Vector()->length() == 2 || + n->as_Vector()->length() == 4); + match(Set dst (SubVS src1 src2)); + ins_cost(INSN_COST); + format %{ "subv $dst,$src1,$src2\t# vector (4H)" %} + ins_encode %{ + __ subv(as_FloatRegister($dst$$reg), __ T4H, + as_FloatRegister($src1$$reg), + as_FloatRegister($src2$$reg)); + %} + ins_pipe(pipe_class_default); +%} + instruct vsub8S(vecX dst, vecX src1, vecX src2) %{ + predicate(n->as_Vector()->length() == 8); match(Set dst (SubVS src1 src2)); ins_cost(INSN_COST); format %{ "subv $dst,$src1,$src2\t# vector (8H)" %} @@ -13632,8 +13966,23 @@ instruct vsub8S(vecX dst, vecX src1, vecX src2) ins_pipe(pipe_class_default); %} +instruct vsub2I(vecD dst, vecD src1, vecD src2) +%{ + predicate(n->as_Vector()->length() == 2); + match(Set dst (SubVI src1 src2)); + ins_cost(INSN_COST); + format %{ "subv $dst,$src1,$src2\t# vector (2S)" %} + ins_encode %{ + __ subv(as_FloatRegister($dst$$reg), __ T2S, + as_FloatRegister($src1$$reg), + as_FloatRegister($src2$$reg)); + %} + ins_pipe(pipe_class_default); +%} + instruct vsub4I(vecX dst, vecX src1, vecX src2) %{ + predicate(n->as_Vector()->length() == 4); match(Set dst (SubVI src1 src2)); ins_cost(INSN_COST); format %{ "subv $dst,$src1,$src2\t# vector (4S)" %} @@ -13647,6 +13996,7 @@ instruct vsub4I(vecX dst, vecX src1, vecX src2) instruct vsub2L(vecX dst, vecX src1, vecX src2) %{ + predicate(n->as_Vector()->length() == 2); match(Set dst (SubVL src1 src2)); ins_cost(INSN_COST); format %{ "subv $dst,$src1,$src2\t# vector (2L)" %} @@ -13658,8 +14008,23 @@ instruct vsub2L(vecX dst, vecX src1, vecX src2) ins_pipe(pipe_class_default); %} +instruct vsub2F(vecD dst, vecD src1, vecD src2) +%{ + predicate(n->as_Vector()->length() == 2); + match(Set dst (AddVF src1 src2)); + ins_cost(INSN_COST); + format %{ "fsub $dst,$src1,$src2\t# vector (2S)" %} + ins_encode %{ + __ fsub(as_FloatRegister($dst$$reg), __ T2S, + as_FloatRegister($src1$$reg), + as_FloatRegister($src2$$reg)); + %} + ins_pipe(pipe_class_default); +%} + instruct vsub4F(vecX dst, vecX src1, vecX src2) %{ + predicate(n->as_Vector()->length() == 4); match(Set dst (SubVF src1 src2)); ins_cost(INSN_COST); format %{ "fsub $dst,$src1,$src2\t# vector (4S)" %} @@ -13673,6 +14038,7 @@ instruct vsub4F(vecX dst, vecX src1, vecX src2) instruct vsub2D(vecX dst, vecX src1, vecX src2) %{ + predicate(n->as_Vector()->length() == 2); match(Set dst (SubVD src1 src2)); ins_cost(INSN_COST); format %{ "fsub $dst,$src1,$src2\t# vector (2D)" %} @@ -13686,8 +14052,24 @@ instruct vsub2D(vecX dst, vecX src1, vecX src2) // --------------------------------- MUL -------------------------------------- +instruct vmul4S(vecD dst, vecD src1, vecD src2) +%{ + predicate(n->as_Vector()->length() == 2 || + n->as_Vector()->length() == 4); + match(Set dst (MulVS src1 src2)); + ins_cost(INSN_COST); + format %{ "mulv $dst,$src1,$src2\t# vector (4H)" %} + ins_encode %{ + __ mulv(as_FloatRegister($dst$$reg), __ T4H, + as_FloatRegister($src1$$reg), + as_FloatRegister($src2$$reg)); + %} + ins_pipe(pipe_class_default); +%} + instruct vmul8S(vecX dst, vecX src1, vecX src2) %{ + predicate(n->as_Vector()->length() == 8); match(Set dst (MulVS src1 src2)); ins_cost(INSN_COST); format %{ "mulv $dst,$src1,$src2\t# vector (8H)" %} @@ -13699,8 +14081,23 @@ instruct vmul8S(vecX dst, vecX src1, vecX src2) ins_pipe(pipe_class_default); %} +instruct vmul2I(vecD dst, vecD src1, vecD src2) +%{ + predicate(n->as_Vector()->length() == 2); + match(Set dst (MulVI src1 src2)); + ins_cost(INSN_COST); + format %{ "mulv $dst,$src1,$src2\t# vector (2S)" %} + ins_encode %{ + __ mulv(as_FloatRegister($dst$$reg), __ T2S, + as_FloatRegister($src1$$reg), + as_FloatRegister($src2$$reg)); + %} + ins_pipe(pipe_class_default); +%} + instruct vmul4I(vecX dst, vecX src1, vecX src2) %{ + predicate(n->as_Vector()->length() == 4); match(Set dst (MulVI src1 src2)); ins_cost(INSN_COST); format %{ "mulv $dst,$src1,$src2\t# vector (4S)" %} @@ -13712,8 +14109,23 @@ instruct vmul4I(vecX dst, vecX src1, vecX src2) ins_pipe(pipe_class_default); %} +instruct vmul2F(vecD dst, vecD src1, vecD src2) +%{ + predicate(n->as_Vector()->length() == 2); + match(Set dst (MulVF src1 src2)); + ins_cost(INSN_COST); + format %{ "fmul $dst,$src1,$src2\t# vector (2S)" %} + ins_encode %{ + __ fmul(as_FloatRegister($dst$$reg), __ T2S, + as_FloatRegister($src1$$reg), + as_FloatRegister($src2$$reg)); + %} + ins_pipe(pipe_class_default); +%} + instruct vmul4F(vecX dst, vecX src1, vecX src2) %{ + predicate(n->as_Vector()->length() == 4); match(Set dst (MulVF src1 src2)); ins_cost(INSN_COST); format %{ "fmul $dst,$src1,$src2\t# vector (4S)" %} @@ -13727,6 +14139,7 @@ instruct vmul4F(vecX dst, vecX src1, vecX src2) instruct vmul2D(vecX dst, vecX src1, vecX src2) %{ + predicate(n->as_Vector()->length() == 2); match(Set dst (MulVD src1 src2)); ins_cost(INSN_COST); format %{ "fmul $dst,$src1,$src2\t# vector (2D)" %} @@ -13740,8 +14153,23 @@ instruct vmul2D(vecX dst, vecX src1, vecX src2) // --------------------------------- DIV -------------------------------------- +instruct vdiv2F(vecD dst, vecD src1, vecD src2) +%{ + predicate(n->as_Vector()->length() == 2); + match(Set dst (DivVF src1 src2)); + ins_cost(INSN_COST); + format %{ "fdiv $dst,$src1,$src2\t# vector (2S)" %} + ins_encode %{ + __ fdiv(as_FloatRegister($dst$$reg), __ T2S, + as_FloatRegister($src1$$reg), + as_FloatRegister($src2$$reg)); + %} + ins_pipe(pipe_class_default); +%} + instruct vdiv4F(vecX dst, vecX src1, vecX src2) %{ + predicate(n->as_Vector()->length() == 4); match(Set dst (DivVF src1 src2)); ins_cost(INSN_COST); format %{ "fdiv $dst,$src1,$src2\t# vector (4S)" %} @@ -13755,6 +14183,7 @@ instruct vdiv4F(vecX dst, vecX src1, vecX src2) instruct vdiv2D(vecX dst, vecX src1, vecX src2) %{ + predicate(n->as_Vector()->length() == 2); match(Set dst (DivVD src1 src2)); ins_cost(INSN_COST); format %{ "fdiv $dst,$src1,$src2\t# vector (2D)" %} @@ -13768,8 +14197,24 @@ instruct vdiv2D(vecX dst, vecX src1, vecX src2) // --------------------------------- AND -------------------------------------- +instruct vand8B(vecD dst, vecD src1, vecD src2) +%{ + predicate(n->as_Vector()->length_in_bytes() == 4 || + n->as_Vector()->length_in_bytes() == 8); + match(Set dst (AndV src1 src2)); + ins_cost(INSN_COST); + format %{ "and $dst,$src1,$src2\t# vector (8B)" %} + ins_encode %{ + __ andr(as_FloatRegister($dst$$reg), __ T8B, + as_FloatRegister($src1$$reg), + as_FloatRegister($src2$$reg)); + %} + ins_pipe(pipe_class_default); +%} + instruct vand16B(vecX dst, vecX src1, vecX src2) %{ + predicate(n->as_Vector()->length_in_bytes() == 16); match(Set dst (AndV src1 src2)); ins_cost(INSN_COST); format %{ "and $dst,$src1,$src2\t# vector (16B)" %} @@ -13783,8 +14228,24 @@ instruct vand16B(vecX dst, vecX src1, vecX src2) // --------------------------------- OR --------------------------------------- +instruct vor8B(vecD dst, vecD src1, vecD src2) +%{ + predicate(n->as_Vector()->length_in_bytes() == 4 || + n->as_Vector()->length_in_bytes() == 8); + match(Set dst (OrV src1 src2)); + ins_cost(INSN_COST); + format %{ "and $dst,$src1,$src2\t# vector (8B)" %} + ins_encode %{ + __ orr(as_FloatRegister($dst$$reg), __ T8B, + as_FloatRegister($src1$$reg), + as_FloatRegister($src2$$reg)); + %} + ins_pipe(pipe_class_default); +%} + instruct vor16B(vecX dst, vecX src1, vecX src2) %{ + predicate(n->as_Vector()->length_in_bytes() == 16); match(Set dst (OrV src1 src2)); ins_cost(INSN_COST); format %{ "orr $dst,$src1,$src2\t# vector (16B)" %} @@ -13798,8 +14259,24 @@ instruct vor16B(vecX dst, vecX src1, vecX src2) // --------------------------------- XOR -------------------------------------- +instruct vxor8B(vecD dst, vecD src1, vecD src2) +%{ + predicate(n->as_Vector()->length_in_bytes() == 4 || + n->as_Vector()->length_in_bytes() == 8); + match(Set dst (XorV src1 src2)); + ins_cost(INSN_COST); + format %{ "xor $dst,$src1,$src2\t# vector (8B)" %} + ins_encode %{ + __ eor(as_FloatRegister($dst$$reg), __ T8B, + as_FloatRegister($src1$$reg), + as_FloatRegister($src2$$reg)); + %} + ins_pipe(pipe_class_default); +%} + instruct vxor16B(vecX dst, vecX src1, vecX src2) %{ + predicate(n->as_Vector()->length_in_bytes() == 16); match(Set dst (XorV src1 src2)); ins_cost(INSN_COST); format %{ "xor $dst,$src1,$src2\t# vector (16B)" %} @@ -13833,7 +14310,23 @@ instruct vshiftcntR(vecX dst, iRegIorL2I cnt) %{ ins_pipe(pipe_class_default); %} +instruct vsll8B(vecD dst, vecD src, vecX shift) %{ + predicate(n->as_Vector()->length() == 4 || + n->as_Vector()->length() == 8); + match(Set dst (LShiftVB src shift)); + match(Set dst (RShiftVB src shift)); + ins_cost(INSN_COST); + format %{ "sshl $dst,$src,$shift\t# vector (8B)" %} + ins_encode %{ + __ sshl(as_FloatRegister($dst$$reg), __ T8B, + as_FloatRegister($src$$reg), + as_FloatRegister($shift$$reg)); + %} + ins_pipe(pipe_class_default); +%} + instruct vsll16B(vecX dst, vecX src, vecX shift) %{ + predicate(n->as_Vector()->length() == 16); match(Set dst (LShiftVB src shift)); match(Set dst (RShiftVB src shift)); ins_cost(INSN_COST); @@ -13846,7 +14339,22 @@ instruct vsll16B(vecX dst, vecX src, vecX shift) %{ ins_pipe(pipe_class_default); %} +instruct vsrl8B(vecD dst, vecD src, vecX shift) %{ + predicate(n->as_Vector()->length() == 4 || + n->as_Vector()->length() == 8); + match(Set dst (URShiftVB src shift)); + ins_cost(INSN_COST); + format %{ "ushl $dst,$src,$shift\t# vector (8B)" %} + ins_encode %{ + __ ushl(as_FloatRegister($dst$$reg), __ T8B, + as_FloatRegister($src$$reg), + as_FloatRegister($shift$$reg)); + %} + ins_pipe(pipe_class_default); +%} + instruct vsrl16B(vecX dst, vecX src, vecX shift) %{ + predicate(n->as_Vector()->length() == 16); match(Set dst (URShiftVB src shift)); ins_cost(INSN_COST); format %{ "ushl $dst,$src,$shift\t# vector (16B)" %} @@ -13858,7 +14366,28 @@ instruct vsrl16B(vecX dst, vecX src, vecX shift) %{ ins_pipe(pipe_class_default); %} +instruct vsll8B_imm(vecD dst, vecD src, immI shift) %{ + predicate(n->as_Vector()->length() == 4 || + n->as_Vector()->length() == 8); + match(Set dst (LShiftVB src shift)); + ins_cost(INSN_COST); + format %{ "shl $dst, $src, $shift\t# vector (8B)" %} + ins_encode %{ + int sh = (int)$shift$$constant & 31; + if (sh >= 8) { + __ eor(as_FloatRegister($dst$$reg), __ T8B, + as_FloatRegister($src$$reg), + as_FloatRegister($src$$reg)); + } else { + __ shl(as_FloatRegister($dst$$reg), __ T8B, + as_FloatRegister($src$$reg), sh); + } + %} + ins_pipe(pipe_class_default); +%} + instruct vsll16B_imm(vecX dst, vecX src, immI shift) %{ + predicate(n->as_Vector()->length() == 16); match(Set dst (LShiftVB src shift)); ins_cost(INSN_COST); format %{ "shl $dst, $src, $shift\t# vector (16B)" %} @@ -13876,7 +14405,24 @@ instruct vsll16B_imm(vecX dst, vecX src, immI shift) %{ ins_pipe(pipe_class_default); %} +instruct vsra8B_imm(vecD dst, vecD src, immI shift) %{ + predicate(n->as_Vector()->length() == 4 || + n->as_Vector()->length() == 8); + match(Set dst (RShiftVB src shift)); + ins_cost(INSN_COST); + format %{ "sshr $dst, $src, $shift\t# vector (8B)" %} + ins_encode %{ + int sh = (int)$shift$$constant & 31; + if (sh >= 8) sh = 7; + sh = -sh & 7; + __ sshr(as_FloatRegister($dst$$reg), __ T8B, + as_FloatRegister($src$$reg), sh); + %} + ins_pipe(pipe_class_default); +%} + instruct vsra16B_imm(vecX dst, vecX src, immI shift) %{ + predicate(n->as_Vector()->length() == 16); match(Set dst (RShiftVB src shift)); ins_cost(INSN_COST); format %{ "sshr $dst, $src, $shift\t# vector (16B)" %} @@ -13890,7 +14436,28 @@ instruct vsra16B_imm(vecX dst, vecX src, immI shift) %{ ins_pipe(pipe_class_default); %} +instruct vsrl8B_imm(vecD dst, vecD src, immI shift) %{ + predicate(n->as_Vector()->length() == 4 || + n->as_Vector()->length() == 8); + match(Set dst (URShiftVB src shift)); + ins_cost(INSN_COST); + format %{ "ushr $dst, $src, $shift\t# vector (8B)" %} + ins_encode %{ + int sh = (int)$shift$$constant & 31; + if (sh >= 8) { + __ eor(as_FloatRegister($dst$$reg), __ T8B, + as_FloatRegister($src$$reg), + as_FloatRegister($src$$reg)); + } else { + __ ushr(as_FloatRegister($dst$$reg), __ T8B, + as_FloatRegister($src$$reg), -sh & 7); + } + %} + ins_pipe(pipe_class_default); +%} + instruct vsrl16B_imm(vecX dst, vecX src, immI shift) %{ + predicate(n->as_Vector()->length() == 16); match(Set dst (URShiftVB src shift)); ins_cost(INSN_COST); format %{ "ushr $dst, $src, $shift\t# vector (16B)" %} @@ -13908,7 +14475,23 @@ instruct vsrl16B_imm(vecX dst, vecX src, immI shift) %{ ins_pipe(pipe_class_default); %} +instruct vsll4S(vecD dst, vecD src, vecX shift) %{ + predicate(n->as_Vector()->length() == 2 || + n->as_Vector()->length() == 4); + match(Set dst (LShiftVS src shift)); + match(Set dst (RShiftVS src shift)); + ins_cost(INSN_COST); + format %{ "sshl $dst,$src,$shift\t# vector (4H)" %} + ins_encode %{ + __ sshl(as_FloatRegister($dst$$reg), __ T4H, + as_FloatRegister($src$$reg), + as_FloatRegister($shift$$reg)); + %} + ins_pipe(pipe_class_default); +%} + instruct vsll8S(vecX dst, vecX src, vecX shift) %{ + predicate(n->as_Vector()->length() == 8); match(Set dst (LShiftVS src shift)); match(Set dst (RShiftVS src shift)); ins_cost(INSN_COST); @@ -13921,7 +14504,22 @@ instruct vsll8S(vecX dst, vecX src, vecX shift) %{ ins_pipe(pipe_class_default); %} +instruct vsrl4S(vecD dst, vecD src, vecX shift) %{ + predicate(n->as_Vector()->length() == 2 || + n->as_Vector()->length() == 4); + match(Set dst (URShiftVS src shift)); + ins_cost(INSN_COST); + format %{ "ushl $dst,$src,$shift\t# vector (4H)" %} + ins_encode %{ + __ ushl(as_FloatRegister($dst$$reg), __ T4H, + as_FloatRegister($src$$reg), + as_FloatRegister($shift$$reg)); + %} + ins_pipe(pipe_class_default); +%} + instruct vsrl8S(vecX dst, vecX src, vecX shift) %{ + predicate(n->as_Vector()->length() == 8); match(Set dst (URShiftVS src shift)); ins_cost(INSN_COST); format %{ "ushl $dst,$src,$shift\t# vector (8H)" %} @@ -13933,7 +14531,28 @@ instruct vsrl8S(vecX dst, vecX src, vecX shift) %{ ins_pipe(pipe_class_default); %} +instruct vsll4S_imm(vecD dst, vecD src, immI shift) %{ + predicate(n->as_Vector()->length() == 2 || + n->as_Vector()->length() == 4); + match(Set dst (LShiftVS src shift)); + ins_cost(INSN_COST); + format %{ "shl $dst, $src, $shift\t# vector (4H)" %} + ins_encode %{ + int sh = (int)$shift$$constant & 31; + if (sh >= 16) { + __ eor(as_FloatRegister($dst$$reg), __ T8B, + as_FloatRegister($src$$reg), + as_FloatRegister($src$$reg)); + } else { + __ shl(as_FloatRegister($dst$$reg), __ T4H, + as_FloatRegister($src$$reg), sh); + } + %} + ins_pipe(pipe_class_default); +%} + instruct vsll8S_imm(vecX dst, vecX src, immI shift) %{ + predicate(n->as_Vector()->length() == 8); match(Set dst (LShiftVS src shift)); ins_cost(INSN_COST); format %{ "shl $dst, $src, $shift\t# vector (8H)" %} @@ -13951,7 +14570,24 @@ instruct vsll8S_imm(vecX dst, vecX src, immI shift) %{ ins_pipe(pipe_class_default); %} +instruct vsra4S_imm(vecD dst, vecD src, immI shift) %{ + predicate(n->as_Vector()->length() == 2 || + n->as_Vector()->length() == 4); + match(Set dst (RShiftVS src shift)); + ins_cost(INSN_COST); + format %{ "sshr $dst, $src, $shift\t# vector (4H)" %} + ins_encode %{ + int sh = (int)$shift$$constant & 31; + if (sh >= 16) sh = 15; + sh = -sh & 15; + __ sshr(as_FloatRegister($dst$$reg), __ T4H, + as_FloatRegister($src$$reg), sh); + %} + ins_pipe(pipe_class_default); +%} + instruct vsra8S_imm(vecX dst, vecX src, immI shift) %{ + predicate(n->as_Vector()->length() == 8); match(Set dst (RShiftVS src shift)); ins_cost(INSN_COST); format %{ "sshr $dst, $src, $shift\t# vector (8H)" %} @@ -13965,7 +14601,28 @@ instruct vsra8S_imm(vecX dst, vecX src, immI shift) %{ ins_pipe(pipe_class_default); %} +instruct vsrl4S_imm(vecD dst, vecD src, immI shift) %{ + predicate(n->as_Vector()->length() == 2 || + n->as_Vector()->length() == 4); + match(Set dst (URShiftVS src shift)); + ins_cost(INSN_COST); + format %{ "ushr $dst, $src, $shift\t# vector (4H)" %} + ins_encode %{ + int sh = (int)$shift$$constant & 31; + if (sh >= 16) { + __ eor(as_FloatRegister($dst$$reg), __ T8B, + as_FloatRegister($src$$reg), + as_FloatRegister($src$$reg)); + } else { + __ ushr(as_FloatRegister($dst$$reg), __ T4H, + as_FloatRegister($src$$reg), -sh & 15); + } + %} + ins_pipe(pipe_class_default); +%} + instruct vsrl8S_imm(vecX dst, vecX src, immI shift) %{ + predicate(n->as_Vector()->length() == 8); match(Set dst (URShiftVS src shift)); ins_cost(INSN_COST); format %{ "ushr $dst, $src, $shift\t# vector (8H)" %} @@ -13983,7 +14640,22 @@ instruct vsrl8S_imm(vecX dst, vecX src, immI shift) %{ ins_pipe(pipe_class_default); %} +instruct vsll2I(vecD dst, vecD src, vecX shift) %{ + predicate(n->as_Vector()->length() == 2); + match(Set dst (LShiftVI src shift)); + match(Set dst (RShiftVI src shift)); + ins_cost(INSN_COST); + format %{ "sshl $dst,$src,$shift\t# vector (2S)" %} + ins_encode %{ + __ sshl(as_FloatRegister($dst$$reg), __ T2S, + as_FloatRegister($src$$reg), + as_FloatRegister($shift$$reg)); + %} + ins_pipe(pipe_class_default); +%} + instruct vsll4I(vecX dst, vecX src, vecX shift) %{ + predicate(n->as_Vector()->length() == 4); match(Set dst (LShiftVI src shift)); match(Set dst (RShiftVI src shift)); ins_cost(INSN_COST); @@ -13996,7 +14668,21 @@ instruct vsll4I(vecX dst, vecX src, vecX shift) %{ ins_pipe(pipe_class_default); %} +instruct vsrl2I(vecD dst, vecD src, vecX shift) %{ + predicate(n->as_Vector()->length() == 2); + match(Set dst (URShiftVI src shift)); + ins_cost(INSN_COST); + format %{ "ushl $dst,$src,$shift\t# vector (2S)" %} + ins_encode %{ + __ ushl(as_FloatRegister($dst$$reg), __ T2S, + as_FloatRegister($src$$reg), + as_FloatRegister($shift$$reg)); + %} + ins_pipe(pipe_class_default); +%} + instruct vsrl4I(vecX dst, vecX src, vecX shift) %{ + predicate(n->as_Vector()->length() == 4); match(Set dst (URShiftVI src shift)); ins_cost(INSN_COST); format %{ "ushl $dst,$src,$shift\t# vector (4S)" %} @@ -14008,7 +14694,21 @@ instruct vsrl4I(vecX dst, vecX src, vecX shift) %{ ins_pipe(pipe_class_default); %} +instruct vsll2I_imm(vecD dst, vecD src, immI shift) %{ + predicate(n->as_Vector()->length() == 2); + match(Set dst (LShiftVI src shift)); + ins_cost(INSN_COST); + format %{ "shl $dst, $src, $shift\t# vector (2S)" %} + ins_encode %{ + __ shl(as_FloatRegister($dst$$reg), __ T2S, + as_FloatRegister($src$$reg), + (int)$shift$$constant & 31); + %} + ins_pipe(pipe_class_default); +%} + instruct vsll4I_imm(vecX dst, vecX src, immI shift) %{ + predicate(n->as_Vector()->length() == 4); match(Set dst (LShiftVI src shift)); ins_cost(INSN_COST); format %{ "shl $dst, $src, $shift\t# vector (4S)" %} @@ -14020,7 +14720,21 @@ instruct vsll4I_imm(vecX dst, vecX src, immI shift) %{ ins_pipe(pipe_class_default); %} +instruct vsra2I_imm(vecD dst, vecD src, immI shift) %{ + predicate(n->as_Vector()->length() == 2); + match(Set dst (RShiftVI src shift)); + ins_cost(INSN_COST); + format %{ "sshr $dst, $src, $shift\t# vector (2S)" %} + ins_encode %{ + __ sshr(as_FloatRegister($dst$$reg), __ T2S, + as_FloatRegister($src$$reg), + -(int)$shift$$constant & 31); + %} + ins_pipe(pipe_class_default); +%} + instruct vsra4I_imm(vecX dst, vecX src, immI shift) %{ + predicate(n->as_Vector()->length() == 4); match(Set dst (RShiftVI src shift)); ins_cost(INSN_COST); format %{ "sshr $dst, $src, $shift\t# vector (4S)" %} @@ -14032,7 +14746,21 @@ instruct vsra4I_imm(vecX dst, vecX src, immI shift) %{ ins_pipe(pipe_class_default); %} +instruct vsrl2I_imm(vecD dst, vecD src, immI shift) %{ + predicate(n->as_Vector()->length() == 2); + match(Set dst (URShiftVI src shift)); + ins_cost(INSN_COST); + format %{ "ushr $dst, $src, $shift\t# vector (2S)" %} + ins_encode %{ + __ ushr(as_FloatRegister($dst$$reg), __ T2S, + as_FloatRegister($src$$reg), + -(int)$shift$$constant & 31); + %} + ins_pipe(pipe_class_default); +%} + instruct vsrl4I_imm(vecX dst, vecX src, immI shift) %{ + predicate(n->as_Vector()->length() == 4); match(Set dst (URShiftVI src shift)); ins_cost(INSN_COST); format %{ "ushr $dst, $src, $shift\t# vector (4S)" %} @@ -14045,6 +14773,7 @@ instruct vsrl4I_imm(vecX dst, vecX src, immI shift) %{ %} instruct vsll2L(vecX dst, vecX src, vecX shift) %{ + predicate(n->as_Vector()->length() == 2); match(Set dst (LShiftVL src shift)); match(Set dst (RShiftVL src shift)); ins_cost(INSN_COST); @@ -14058,6 +14787,7 @@ instruct vsll2L(vecX dst, vecX src, vecX shift) %{ %} instruct vsrl2L(vecX dst, vecX src, vecX shift) %{ + predicate(n->as_Vector()->length() == 2); match(Set dst (URShiftVL src shift)); ins_cost(INSN_COST); format %{ "ushl $dst,$src,$shift\t# vector (2D)" %} @@ -14070,6 +14800,7 @@ instruct vsrl2L(vecX dst, vecX src, vecX shift) %{ %} instruct vsll2L_imm(vecX dst, vecX src, immI shift) %{ + predicate(n->as_Vector()->length() == 2); match(Set dst (LShiftVL src shift)); ins_cost(INSN_COST); format %{ "shl $dst, $src, $shift\t# vector (2D)" %} @@ -14082,6 +14813,7 @@ instruct vsll2L_imm(vecX dst, vecX src, immI shift) %{ %} instruct vsra2L_imm(vecX dst, vecX src, immI shift) %{ + predicate(n->as_Vector()->length() == 2); match(Set dst (RShiftVL src shift)); ins_cost(INSN_COST); format %{ "sshr $dst, $src, $shift\t# vector (2D)" %} @@ -14094,6 +14826,7 @@ instruct vsra2L_imm(vecX dst, vecX src, immI shift) %{ %} instruct vsrl2L_imm(vecX dst, vecX src, immI shift) %{ + predicate(n->as_Vector()->length() == 2); match(Set dst (URShiftVL src shift)); ins_cost(INSN_COST); format %{ "ushr $dst, $src, $shift\t# vector (2D)" %} From 1b1d8f21cb5141f4446d0535a17547028c978c6e Mon Sep 17 00:00:00 2001 From: Alexander Alexeev Date: Thu, 25 Jun 2015 13:41:29 +0000 Subject: [PATCH 03/43] 8129426: aarch64: add support for PopCount in C2 Add support for PopCount using SIMD cnt and addv inst Reviewed-by: kvn, aph --- hotspot/src/cpu/aarch64/vm/aarch64.ad | 90 +++++++++++++++++++ .../src/cpu/aarch64/vm/assembler_aarch64.hpp | 3 + .../cpu/aarch64/vm/macroAssembler_aarch64.hpp | 1 + .../src/cpu/aarch64/vm/vm_version_aarch64.cpp | 4 + 4 files changed, 98 insertions(+) diff --git a/hotspot/src/cpu/aarch64/vm/aarch64.ad b/hotspot/src/cpu/aarch64/vm/aarch64.ad index 02fe907021b..0fe321509f5 100644 --- a/hotspot/src/cpu/aarch64/vm/aarch64.ad +++ b/hotspot/src/cpu/aarch64/vm/aarch64.ad @@ -7464,6 +7464,96 @@ instruct countTrailingZerosL(iRegINoSp dst, iRegL src) %{ ins_pipe(ialu_reg); %} +//---------- Population Count Instructions ------------------------------------- +// + +instruct popCountI(iRegINoSp dst, iRegIorL2I src, vRegF tmp) %{ + predicate(UsePopCountInstruction); + match(Set dst (PopCountI src)); + effect(TEMP tmp); + ins_cost(INSN_COST * 13); + + format %{ "movw $src, $src\n\t" + "mov $tmp, $src\t# vector (1D)\n\t" + "cnt $tmp, $tmp\t# vector (8B)\n\t" + "addv $tmp, $tmp\t# vector (8B)\n\t" + "mov $dst, $tmp\t# vector (1D)" %} + ins_encode %{ + __ movw($src$$Register, $src$$Register); // ensure top 32 bits 0 + __ mov($tmp$$FloatRegister, __ T1D, 0, $src$$Register); + __ cnt($tmp$$FloatRegister, __ T8B, $tmp$$FloatRegister); + __ addv($tmp$$FloatRegister, __ T8B, $tmp$$FloatRegister); + __ mov($dst$$Register, $tmp$$FloatRegister, __ T1D, 0); + %} + + ins_pipe(pipe_class_default); +%} + +instruct popCountI_mem(iRegINoSp dst, memory mem, vRegF tmp) %{ + predicate(UsePopCountInstruction); + match(Set dst (PopCountI (LoadI mem))); + effect(TEMP tmp); + ins_cost(INSN_COST * 13); + + format %{ "ldrs $tmp, $mem\n\t" + "cnt $tmp, $tmp\t# vector (8B)\n\t" + "addv $tmp, $tmp\t# vector (8B)\n\t" + "mov $dst, $tmp\t# vector (1D)" %} + ins_encode %{ + FloatRegister tmp_reg = as_FloatRegister($tmp$$reg); + loadStore(MacroAssembler(&cbuf), &MacroAssembler::ldrs, tmp_reg, $mem->opcode(), + as_Register($mem$$base), $mem$$index, $mem$$scale, $mem$$disp); + __ cnt($tmp$$FloatRegister, __ T8B, $tmp$$FloatRegister); + __ addv($tmp$$FloatRegister, __ T8B, $tmp$$FloatRegister); + __ mov($dst$$Register, $tmp$$FloatRegister, __ T1D, 0); + %} + + ins_pipe(pipe_class_default); +%} + +// Note: Long.bitCount(long) returns an int. +instruct popCountL(iRegINoSp dst, iRegL src, vRegD tmp) %{ + predicate(UsePopCountInstruction); + match(Set dst (PopCountL src)); + effect(TEMP tmp); + ins_cost(INSN_COST * 13); + + format %{ "mov $tmp, $src\t# vector (1D)\n\t" + "cnt $tmp, $tmp\t# vector (8B)\n\t" + "addv $tmp, $tmp\t# vector (8B)\n\t" + "mov $dst, $tmp\t# vector (1D)" %} + ins_encode %{ + __ mov($tmp$$FloatRegister, __ T1D, 0, $src$$Register); + __ cnt($tmp$$FloatRegister, __ T8B, $tmp$$FloatRegister); + __ addv($tmp$$FloatRegister, __ T8B, $tmp$$FloatRegister); + __ mov($dst$$Register, $tmp$$FloatRegister, __ T1D, 0); + %} + + ins_pipe(pipe_class_default); +%} + +instruct popCountL_mem(iRegINoSp dst, memory mem, vRegD tmp) %{ + predicate(UsePopCountInstruction); + match(Set dst (PopCountL (LoadL mem))); + effect(TEMP tmp); + ins_cost(INSN_COST * 13); + + format %{ "ldrd $tmp, $mem\n\t" + "cnt $tmp, $tmp\t# vector (8B)\n\t" + "addv $tmp, $tmp\t# vector (8B)\n\t" + "mov $dst, $tmp\t# vector (1D)" %} + ins_encode %{ + FloatRegister tmp_reg = as_FloatRegister($tmp$$reg); + loadStore(MacroAssembler(&cbuf), &MacroAssembler::ldrd, tmp_reg, $mem->opcode(), + as_Register($mem$$base), $mem$$index, $mem$$scale, $mem$$disp); + __ cnt($tmp$$FloatRegister, __ T8B, $tmp$$FloatRegister); + __ addv($tmp$$FloatRegister, __ T8B, $tmp$$FloatRegister); + __ mov($dst$$Register, $tmp$$FloatRegister, __ T1D, 0); + %} + + ins_pipe(pipe_class_default); +%} + // ============================================================================ // MemBar Instruction diff --git a/hotspot/src/cpu/aarch64/vm/assembler_aarch64.hpp b/hotspot/src/cpu/aarch64/vm/assembler_aarch64.hpp index 1de8ed8f1fb..85752e738c2 100644 --- a/hotspot/src/cpu/aarch64/vm/assembler_aarch64.hpp +++ b/hotspot/src/cpu/aarch64/vm/assembler_aarch64.hpp @@ -2055,6 +2055,9 @@ public: INSN(negr, 1, 0b100000101110); INSN(notr, 1, 0b100000010110); INSN(addv, 0, 0b110001101110); + INSN(cls, 0, 0b100000010010); + INSN(clz, 1, 0b100000010010); + INSN(cnt, 0, 0b100000010110); #undef INSN diff --git a/hotspot/src/cpu/aarch64/vm/macroAssembler_aarch64.hpp b/hotspot/src/cpu/aarch64/vm/macroAssembler_aarch64.hpp index 99187783be7..8a8c58e3955 100644 --- a/hotspot/src/cpu/aarch64/vm/macroAssembler_aarch64.hpp +++ b/hotspot/src/cpu/aarch64/vm/macroAssembler_aarch64.hpp @@ -36,6 +36,7 @@ class MacroAssembler: public Assembler { friend class LIR_Assembler; + public: using Assembler::mov; using Assembler::movi; diff --git a/hotspot/src/cpu/aarch64/vm/vm_version_aarch64.cpp b/hotspot/src/cpu/aarch64/vm/vm_version_aarch64.cpp index 433145c4a61..cf76c0d1f07 100644 --- a/hotspot/src/cpu/aarch64/vm/vm_version_aarch64.cpp +++ b/hotspot/src/cpu/aarch64/vm/vm_version_aarch64.cpp @@ -257,6 +257,10 @@ void VM_Version::get_processor_features() { UseBarriersForVolatile = (_cpuFeatures & CPU_DMB_ATOMICS) != 0; } + if (FLAG_IS_DEFAULT(UsePopCountInstruction)) { + UsePopCountInstruction = true; + } + #ifdef COMPILER2 if (FLAG_IS_DEFAULT(OptoScheduling)) { OptoScheduling = true; From 0141308dfa939264b454c35594783b2a64199699 Mon Sep 17 00:00:00 2001 From: Sergei Kovalev Date: Wed, 17 Jun 2015 16:22:38 +0300 Subject: [PATCH 04/43] 8067163: Several JT_HS tests fails due to ClassNotFoundException on compacts Reviewed-by: dholmes, vlivanov --- hotspot/test/TEST.groups | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/hotspot/test/TEST.groups b/hotspot/test/TEST.groups index fa23c56f20b..6d77765c2b1 100644 --- a/hotspot/test/TEST.groups +++ b/hotspot/test/TEST.groups @@ -147,12 +147,16 @@ needs_compact3 = \ gc/survivorAlignment \ gc/TestGCLogRotationViaJcmd.java \ runtime/InternalApi/ThreadCpuTimesDeadlock.java \ + runtime/NMT/JcmdSummaryDiff.java \ + runtime/RedefineTests/RedefineAnnotations.java serviceability/sa/jmap-hashcode/Test8028623.java \ serviceability/threads/TestFalseDeadLock.java \ compiler/codecache/jmx \ compiler/jsr292/RedefineMethodUsedByMultipleMethodHandles.java \ compiler/rangechecks/TestRangeCheckSmearing.java \ - serviceability/dcmd + compiler/whitebox/DeoptimizeMultipleOSRTest.java \ + serviceability/dcmd \ + testlibrary_tests/whitebox/vm_flags # Compact 2 adds full VM tests compact2 = \ From 10ca8052a11e3b6c8d72ceb7181719b1db804c96 Mon Sep 17 00:00:00 2001 From: Vladimir Ivanov Date: Mon, 15 Jun 2015 15:27:04 +0300 Subject: [PATCH 05/43] 8087218: Constant fold loads from final instance fields in VM anonymous classes Reviewed-by: jrose, rbackman --- hotspot/src/share/vm/ci/ciField.cpp | 4 ++++ hotspot/src/share/vm/ci/ciInstanceKlass.cpp | 2 ++ hotspot/src/share/vm/ci/ciInstanceKlass.hpp | 5 +++++ 3 files changed, 11 insertions(+) diff --git a/hotspot/src/share/vm/ci/ciField.cpp b/hotspot/src/share/vm/ci/ciField.cpp index 9fe63de27bf..78be2023ce8 100644 --- a/hotspot/src/share/vm/ci/ciField.cpp +++ b/hotspot/src/share/vm/ci/ciField.cpp @@ -186,6 +186,10 @@ static bool trust_final_non_static_fields(ciInstanceKlass* holder) { // Even if general trusting is disabled, trust system-built closures in these packages. if (holder->is_in_package("java/lang/invoke") || holder->is_in_package("sun/invoke")) return true; + // Trust VM anonymous classes. They are private API (sun.misc.Unsafe) and can't be serialized, + // so there is no hacking of finals going on with them. + if (holder->is_anonymous()) + return true; return TrustFinalNonStaticFields; } diff --git a/hotspot/src/share/vm/ci/ciInstanceKlass.cpp b/hotspot/src/share/vm/ci/ciInstanceKlass.cpp index ec97e100d48..cfbc7b8c65f 100644 --- a/hotspot/src/share/vm/ci/ciInstanceKlass.cpp +++ b/hotspot/src/share/vm/ci/ciInstanceKlass.cpp @@ -58,6 +58,7 @@ ciInstanceKlass::ciInstanceKlass(KlassHandle h_k) : _nonstatic_field_size = ik->nonstatic_field_size(); _has_nonstatic_fields = ik->has_nonstatic_fields(); _has_default_methods = ik->has_default_methods(); + _is_anonymous = ik->is_anonymous(); _nonstatic_fields = NULL; // initialized lazily by compute_nonstatic_fields: _has_injected_fields = -1; _implementor = NULL; // we will fill these lazily @@ -101,6 +102,7 @@ ciInstanceKlass::ciInstanceKlass(ciSymbol* name, _has_nonstatic_fields = false; _nonstatic_fields = NULL; _has_injected_fields = -1; + _is_anonymous = false; _loader = loader; _protection_domain = protection_domain; _is_shared = false; diff --git a/hotspot/src/share/vm/ci/ciInstanceKlass.hpp b/hotspot/src/share/vm/ci/ciInstanceKlass.hpp index df9ed0f7fe9..080acd380e1 100644 --- a/hotspot/src/share/vm/ci/ciInstanceKlass.hpp +++ b/hotspot/src/share/vm/ci/ciInstanceKlass.hpp @@ -53,6 +53,7 @@ private: bool _has_subklass; bool _has_nonstatic_fields; bool _has_default_methods; + bool _is_anonymous; ciFlags _flags; jint _nonstatic_field_size; @@ -179,6 +180,10 @@ public: return _has_default_methods; } + bool is_anonymous() { + return _is_anonymous; + } + ciInstanceKlass* get_canonical_holder(int offset); ciField* get_field_by_offset(int field_offset, bool is_static); ciField* get_field_by_name(ciSymbol* name, ciSymbol* signature, bool is_static); From 21ed89bc5dbafc4083f541fcf00470a139f089ce Mon Sep 17 00:00:00 2001 From: Roger Riggs Date: Tue, 7 Jul 2015 16:54:52 -0400 Subject: [PATCH 06/43] 8085980: java/lang/ProcessHandle/TreeTest.java: AssertionError: Wrong number of spawned children expected [1] but found [2] Modify to expect only the spawned children; enhance debug output Reviewed-by: darcy --- .../java/lang/ProcessHandle/TreeTest.java | 68 +++++++++---------- 1 file changed, 34 insertions(+), 34 deletions(-) diff --git a/jdk/test/java/lang/ProcessHandle/TreeTest.java b/jdk/test/java/lang/ProcessHandle/TreeTest.java index 5a7928216fd..6926e155f2b 100644 --- a/jdk/test/java/lang/ProcessHandle/TreeTest.java +++ b/jdk/test/java/lang/ProcessHandle/TreeTest.java @@ -75,10 +75,12 @@ public class TreeTest extends ProcessUtil { spawned.add(JavaChild.spawnJavaChild("pid", "stdin")); } - List subprocesses = getChildren(self); - subprocesses.forEach(ProcessUtil::printProcess); - count = subprocesses.size(); - Assert.assertEquals(count, MAXCHILDREN, "Wrong number of spawned children"); + // Verify spawned Process is in list of children + final List initialChildren = getChildren(self); + spawned.stream() + .map(Process::toHandle) + .filter(p -> !initialChildren.contains(p)) + .forEach(p -> Assert.fail("Spawned process missing from children: " + p)); // Send exit command to each spawned Process spawned.forEach(p -> { @@ -102,20 +104,25 @@ public class TreeTest extends ProcessUtil { }); // Verify that ProcessHandle.isAlive sees each of them as not alive - for (ProcessHandle ph : subprocesses) { + for (Process p : spawned) { + ProcessHandle ph = p.toHandle(); Assert.assertFalse(ph.isAlive(), "ProcessHandle.isAlive for exited process: " + ph); } - // Verify no current children are visible - count = getChildren(self).size(); - Assert.assertEquals(count, 0, "Children destroyed, should be zero"); + // Verify spawned processes are not visible as children + final List afterChildren = getChildren(self); + spawned.stream() + .map(Process::toHandle) + .filter(p -> afterChildren.contains(p)) + .forEach(p -> Assert.fail("Spawned process missing from children: " + p)); } catch (IOException ioe) { Assert.fail("unable to spawn process", ioe); } finally { // Cleanup any left over processes - spawned.stream().map(Process::toHandle) + spawned.stream() + .map(Process::toHandle) .filter(ProcessHandle::isAlive) .forEach(ph -> printDeep(ph, "test1 cleanup: ")); destroyProcessTree(ProcessHandle.current()); @@ -127,7 +134,6 @@ public class TreeTest extends ProcessUtil { */ @Test public static void test2() { - ProcessHandle p1Handle = null; try { ProcessHandle self = ProcessHandle.current(); List initialChildren = getChildren(self); @@ -138,7 +144,7 @@ public class TreeTest extends ProcessUtil { } JavaChild p1 = JavaChild.spawnJavaChild("stdin"); - p1Handle = p1.toHandle(); + ProcessHandle p1Handle = p1.toHandle(); printf(" p1 pid: %d%n", p1.getPid()); int spawnNew = 3; @@ -187,9 +193,6 @@ public class TreeTest extends ProcessUtil { throw new RuntimeException(t); } finally { // Cleanup any left over processes - if (p1Handle.isAlive()) { - printDeep(p1Handle, "test2 cleanup: "); - } destroyProcessTree(ProcessHandle.current()); } } @@ -205,7 +208,10 @@ public class TreeTest extends ProcessUtil { JavaChild p1 = JavaChild.spawnJavaChild("stdin"); ProcessHandle p1Handle = p1.toHandle(); printf(" p1: %s%n", p1.getPid()); - long count = getChildren(self).size(); + + List subprocesses = getChildren(self); + subprocesses.forEach(ProcessUtil::printProcess); + long count = subprocesses.size(); Assert.assertEquals(count, 1, "Wrong number of spawned children"); int newChildren = 3; @@ -213,7 +219,7 @@ public class TreeTest extends ProcessUtil { p1.sendAction("spawn", newChildren, "stdin"); // Wait for the new processes and save the list - List subprocesses = waitForAllChildren(p1Handle, newChildren); + subprocesses = waitForAllChildren(p1Handle, newChildren); printDeep(p1Handle, "allChildren"); Assert.assertEquals(subprocesses.size(), newChildren, "Wrong number of children"); @@ -249,6 +255,9 @@ public class TreeTest extends ProcessUtil { Assert.fail("Spawn of subprocess failed", ioe); } catch (InterruptedException inte) { Assert.fail("InterruptedException", inte); + } finally { + // Cleanup any left over processes + destroyProcessTree(ProcessHandle.current()); } } @@ -299,16 +308,15 @@ public class TreeTest extends ProcessUtil { } /** - * A test for scale; launch a large number (39) of subprocesses. + * A test for scale; launch a large number (14) of subprocesses. */ @Test public static void test5() { int factor = 2; - ProcessHandle p1Handle = null; Instant start = Instant.now(); try { JavaChild p1 = JavaChild.spawnJavaChild("stdin"); - p1Handle = p1.toHandle(); + ProcessHandle p1Handle = p1.toHandle(); printf("Spawning %d x %d x %d processes, pid: %d%n", factor, factor, factor, p1.getPid()); @@ -325,18 +333,14 @@ public class TreeTest extends ProcessUtil { int newChildren = factor * (1 + factor * (1 + factor)); List children = ProcessUtil.waitForAllChildren(p1Handle, newChildren); - Assert.assertEquals(p1.children() - .filter(ProcessUtil::isNotWindowsConsole) - .count(), factor, "expected direct children"); - Assert.assertEquals(p1.allChildren() - .filter(ProcessUtil::isNotWindowsConsole) - .count(), - factor * factor * factor + factor * factor + factor, - "expected all children"); + Assert.assertEquals(getChildren(p1Handle).size(), + factor, "expected direct children"); + long count = getAllChildren(p1Handle).size(); + long totalChildren = factor * factor * factor + factor * factor + factor; + Assert.assertTrue(count >= totalChildren, + "expected at least " + totalChildren + ", actual: " + count); - List subprocesses = p1.allChildren() - .filter(ProcessUtil::isNotWindowsConsole) - .collect(Collectors.toList()); + List subprocesses = getAllChildren(p1Handle); printf(" allChildren: %s%n", subprocesses.stream().map(p -> p.getPid()) .collect(Collectors.toList())); @@ -347,10 +351,6 @@ public class TreeTest extends ProcessUtil { Assert.fail("Unexpected Exception", ex); } finally { printf("Duration: %s%n", Duration.between(start, Instant.now())); - // Cleanup any left over processes - if (p1Handle.isAlive()) { - printDeep(p1Handle, "test5 cleanup: "); - } destroyProcessTree(ProcessHandle.current()); } } From 4b7514c9fd9c5710e92d89eb1dc72906046e98bf Mon Sep 17 00:00:00 2001 From: Roger Riggs Date: Tue, 7 Jul 2015 21:25:05 -0400 Subject: [PATCH 07/43] 8085981: java/lang/ProcessHandle/OnExitTest.java: AssertionError: Child onExit not called A race condition caused an erroneous fault Reviewed-by: darcy --- .../java/lang/ProcessHandle/OnExitTest.java | 22 +++++++++++-------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/jdk/test/java/lang/ProcessHandle/OnExitTest.java b/jdk/test/java/lang/ProcessHandle/OnExitTest.java index 1043c55bba2..e2700945a8b 100644 --- a/jdk/test/java/lang/ProcessHandle/OnExitTest.java +++ b/jdk/test/java/lang/ProcessHandle/OnExitTest.java @@ -123,16 +123,17 @@ public class OnExitTest extends ProcessUtil { children = getAllChildren(procHandle); - ArrayBlockingQueue completions = new ArrayBlockingQueue<>(expected + 1); + ConcurrentHashMap> completions = + new ConcurrentHashMap<>(); Instant startTime = Instant.now(); // Create a future for each of the 9 children processes.forEach( (p, parent) -> { - p.onExit().whenComplete((ph, ex) -> { + CompletableFuture cf = p.onExit().whenComplete((ph, ex) -> { Duration elapsed = Duration.between(startTime, Instant.now()); - completions.add(ph); printf("whenComplete: pid: %s, exception: %s, thread: %s, elapsed: %s%n", ph, ex, Thread.currentThread(), elapsed); }); + completions.put(p, cf); }); // Check that each of the spawned processes is included in the children @@ -153,20 +154,23 @@ public class OnExitTest extends ProcessUtil { proc.destroy(); // kill off the parent proc.waitFor(); - // Wait for all the processes to be completed + // Wait for all the processes and corresponding onExit CF to be completed processes.forEach((p, parent) -> { try { p.onExit().get(); + completions.get(p).join(); } catch (InterruptedException | ExecutionException ex) { // ignore } }); - // Verify that all 9 exit handlers were called - processes.forEach((p, parent) -> - Assert.assertTrue(completions.contains(p), "Child onExit not called: " + p - + ", parent: " + parent - + ": " + p.info())); + // Verify that all 9 exit handlers were called with the correct ProcessHandle + processes.forEach((p, parent) -> { + ProcessHandle value = completions.get(p).getNow(null); + Assert.assertEquals(p, value, "onExit.get value expected: " + p + + ", actual: " + value + + ": " + p.info()); + }); // Show the status of the original children children.forEach(p -> printProcess(p, "after onExit:")); From aebcb1754ebd4c4591eedfbe40ae928a5b8a78ce Mon Sep 17 00:00:00 2001 From: Weijun Wang Date: Wed, 8 Jul 2015 17:30:38 +0800 Subject: [PATCH 08/43] 8130720: BadKDC1 failed again Reviewed-by: xuelei --- jdk/test/sun/security/krb5/auto/BadKdc1.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jdk/test/sun/security/krb5/auto/BadKdc1.java b/jdk/test/sun/security/krb5/auto/BadKdc1.java index 9921f12b82d..bc70c2a8b74 100644 --- a/jdk/test/sun/security/krb5/auto/BadKdc1.java +++ b/jdk/test/sun/security/krb5/auto/BadKdc1.java @@ -53,7 +53,7 @@ public class BadKdc1 { // k3 off k2 on "(122212(22){1,2}|1222323232-)", // 1 // k1 on - "(12(12){1,2}|122232-)" // empty + "(12(12){1,2}|122212|122232-)" // empty ); } } From 16318cebe6e5f5cc8b876537821a5cd28b646087 Mon Sep 17 00:00:00 2001 From: Daniel Fuchs Date: Wed, 8 Jul 2015 11:58:14 +0200 Subject: [PATCH 09/43] 8130649: java/util/logging/LoggingDeadlock2.java times out Added additional traces and thread dump diagnosis for the child process Reviewed-by: lancea --- .../java/util/logging/LoggingDeadlock2.java | 101 +++++++++++++++++- 1 file changed, 97 insertions(+), 4 deletions(-) diff --git a/jdk/test/java/util/logging/LoggingDeadlock2.java b/jdk/test/java/util/logging/LoggingDeadlock2.java index b33a25191fc..bada1395985 100644 --- a/jdk/test/java/util/logging/LoggingDeadlock2.java +++ b/jdk/test/java/util/logging/LoggingDeadlock2.java @@ -57,35 +57,59 @@ import java.util.concurrent.CyclicBarrier; import java.util.concurrent.atomic.AtomicInteger; import java.util.logging.LogManager; import java.io.File; +import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; +import java.util.concurrent.TimeUnit; public class LoggingDeadlock2 { + // ask child process to dumpstack after 60secs + public static final long DUMP_STACK_FREQUENCY_MS = 60000; + + // A marker that allows to validate the subprocess output. + public static final String MARKER = "$"; + public static void realMain(String arg[]) throws Throwable { try { System.out.println(javaChildArgs); ProcessBuilder pb = new ProcessBuilder(javaChildArgs); ProcessResults r = run(pb.start()); equal(r.exitValue(), 99); - equal(r.out(), ""); + + // output of subprocess should end with "$" + final String out = r.out(); + final String trailingOutput = out.indexOf(MARKER) > -1 + ? out.substring(out.indexOf(MARKER)+MARKER.length()) + : out; + equal(trailingOutput, ""); equal(r.err(), ""); + equal(out.startsWith("JavaChild started"), true); + equal(out.endsWith("$"), true); } catch (Throwable t) { unexpected(t); } } public static class JavaChild { public static void main(String args[]) throws Throwable { + System.out.println("JavaChild started"); + final CyclicBarrier startingGate = new CyclicBarrier(2); final Throwable[] thrown = new Throwable[1]; // Some random variation, to help tickle races. final Random rnd = new Random(); + final long seed = rnd.nextLong(); + rnd.setSeed(seed); + System.out.println("seed=" + seed); final boolean dojoin = rnd.nextBoolean(); final int JITTER = 1024; final int iters1 = rnd.nextInt(JITTER); final int iters2 = JITTER - iters1; final AtomicInteger counter = new AtomicInteger(0); + System.out.println("dojoin=" + dojoin); + System.out.println("iters1=" + iters1); + System.out.println("iters2=" + iters2); Thread exiter = new Thread() { public void run() { @@ -101,6 +125,12 @@ public class LoggingDeadlock2 { }}; exiter.start(); + System.out.println("exiter started"); + + // signal end of verbose output + System.out.print(MARKER); + System.out.flush(); + startingGate.await(); for (int i = 0; i < iters2; i++) counter.getAndIncrement(); @@ -124,6 +154,9 @@ public class LoggingDeadlock2 { private static final String javaExe = System.getProperty("java.home") + File.separator + "bin" + File.separator + "java"; + private static final String jstackExe = + System.getProperty("java.home") + + File.separator + "bin" + File.separator + "jstack"; private static final String classpath = System.getProperty("java.class.path"); @@ -182,10 +215,15 @@ public class LoggingDeadlock2 { public void run() { try { Reader r = new InputStreamReader(is); - char[] buf = new char[4096]; int n; - while ((n = r.read(buf)) > 0) { - sb.append(buf,0,n); + while ((n = r.read()) > 0) { + sb.append((char)n); + + // prints everything immediately to System.out so that we can + // see the traces even in the event of a test timeout + System.out.write((char)n); + System.out.flush(); + } } catch (Throwable t) { throwable = t; @@ -196,6 +234,56 @@ public class LoggingDeadlock2 { } } + /** + * If the child process deadlocks, then the parent may fail in timeout. + * In that case, we won't have any interesting traces, unless we manage + * to get a thread dump from the child. + * It is unsure whether obtaining a thread dump from a deadlocked child + * will work - but maybe we could see something if the timeout is a false + * positive (the child has not deadlocked but hasn't managed to fully start + * yet, for instance). + * The idea here is to periodically try to obtain a thread dump from the + * child, every 60sec - which should be always less than the jtreg timeout. + */ + private static class TimeoutThread extends Thread { + final long ms; + final Process process; + TimeoutThread(long ms, Process p) { + super("TimeoutThread"); + setDaemon(true); + this.ms = ms; + this.process = p; + } + + @Override + public void run() { + long start = System.nanoTime(); + try { + while (true) { + sleep(ms); + System.err.println("Timeout reached: " + ms); + if (process.isAlive()) { + long pid = process.getPid(); + ProcessBuilder jstack = new ProcessBuilder(jstackExe, String.valueOf(pid)); + System.err.println("Dumping subprocess stack: " + pid); + Process p = jstack.inheritIO().start(); + p.waitFor(ms, TimeUnit.MILLISECONDS); + } else { + System.err.println("Process is not alive!"); + break; + } + } + } catch (InterruptedException ex) { + System.err.println("Interrupted: " + ex); + } catch (IOException io) { + System.err.println("Failed to get stack from subprocess"); + io.printStackTrace(); + } + } + + + } + private static ProcessResults run(Process p) { Throwable throwable = null; int exitValue = -1; @@ -208,10 +296,15 @@ public class LoggingDeadlock2 { new StreamAccumulator(p.getErrorStream()); try { + System.out.println("Waiting for child process to exit"); outAccumulator.start(); errAccumulator.start(); + // ask subprocess to dump stack every 60 secs. + new TimeoutThread(DUMP_STACK_FREQUENCY_MS, p).start(); + exitValue = p.waitFor(); + System.out.println("\nChild exited with status: " + exitValue); outAccumulator.join(); errAccumulator.join(); From d65b7a8ec9503abec521bc3300cdaf8d120a3545 Mon Sep 17 00:00:00 2001 From: Claes Redestad Date: Wed, 8 Jul 2015 16:04:42 +0200 Subject: [PATCH 10/43] 8081589: Output of -XX:+TraceClassLoadingPreorder in JDK9 incompatible with MakeClasslist tool Reviewed-by: iklam, hseigel --- jdk/make/non-build-utils/sharing/README.txt | 34 ----- .../non-build-utils/sharing/tests/GHello.java | 53 ------- .../non-build-utils/sharing/tests/Hello.java | 32 ----- .../non-build-utils/sharing/tests/JHello.java | 53 ------- .../tools/makeclasslist/MakeClasslist.java | 130 ------------------ .../tools/makeclasslist/makeClasslist.js | 62 +++++++++ 6 files changed, 62 insertions(+), 302 deletions(-) delete mode 100644 jdk/make/non-build-utils/sharing/README.txt delete mode 100644 jdk/make/non-build-utils/sharing/tests/GHello.java delete mode 100644 jdk/make/non-build-utils/sharing/tests/Hello.java delete mode 100644 jdk/make/non-build-utils/sharing/tests/JHello.java delete mode 100644 jdk/make/non-build-utils/src/build/tools/makeclasslist/MakeClasslist.java create mode 100644 jdk/make/non-build-utils/src/build/tools/makeclasslist/makeClasslist.js diff --git a/jdk/make/non-build-utils/sharing/README.txt b/jdk/make/non-build-utils/sharing/README.txt deleted file mode 100644 index e7953175bd8..00000000000 --- a/jdk/make/non-build-utils/sharing/README.txt +++ /dev/null @@ -1,34 +0,0 @@ -This directory contains tools and tests associated with creating the -class list for class data sharing. - -The class list is produced by running the refWorkload startup3 benchmark with -the -XX:+TraceClassLoadingPreorder option. The -Xshare:off option must also be -used so that bootclasspath classes are loaded from rt.jar. The MakeClasslist -program should be built into the jar file makeclasslist.jar and is run -on one of the logs from each of the benchmarks in the following fashion: - -cd ...//results.startup3 -$JAVA_HOME/bin/java -jar makeclasslist.jar results.Noop/results_1/log results.Framer/results_1/log results.XFramer/results_1/log results.JEdit/results_1/log results.LimeWire/results_1/log results.NetBeans50/results_1/log - -Presently, $JAVA_HOME must be the same path used to run the startup3 benchmark. - -The logs are deliberately concatenated in roughly smallest to largest order -based on application size. The resulting output is redirected into a file -and results in one of classlist.solaris, classlist.linux, classlist.macosx, -or classlist.windows. These files are checked in to the workspace. A -necessary checksum (AddJsum.java) is added to the final classlist -(installed in lib/ or jre/lib/) during the build process by the -makefiles in make/java/redist. - -In a forthcoming JDK build we plan to manually add the dependent -classes for the calendar manager Glow, which pulls in the Preferences -classes and, on Unix platforms, the XML parsing classes. - -The properties file supplied to the refworkload is approximately the -following: - -javahome=/usr/java/j2sdk1.8.0 -resultsdir=classlist-run -iterations=1 -benchmarks=startup3 -globalvmoptions=-client -Xshare:off -XX:+TraceClassLoadingPreorder diff --git a/jdk/make/non-build-utils/sharing/tests/GHello.java b/jdk/make/non-build-utils/sharing/tests/GHello.java deleted file mode 100644 index b8107b4f812..00000000000 --- a/jdk/make/non-build-utils/sharing/tests/GHello.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - - -import java.awt.Font; -import java.awt.Frame; -import java.awt.Label; - -public class GHello extends Frame { - - public static void main(String[] args) { - System.out.println("Hello"); - - new GHello().show(); - if (args.length == 1 && args[0].equals("quit")) { - try { - Thread.currentThread().sleep(200); - } catch (InterruptedException e) { - } - System.exit(0); - } - } - - - GHello() { - Label label = new Label("Hello"); - label.setFont(new Font("Monospaced", Font.PLAIN, 144)); - add(label); - pack(); - } -} diff --git a/jdk/make/non-build-utils/sharing/tests/Hello.java b/jdk/make/non-build-utils/sharing/tests/Hello.java deleted file mode 100644 index f24bb47c4c2..00000000000 --- a/jdk/make/non-build-utils/sharing/tests/Hello.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - - - -public class Hello { - public static void main(String[] args) { - System.out.println("Hello, World!"); - } -} diff --git a/jdk/make/non-build-utils/sharing/tests/JHello.java b/jdk/make/non-build-utils/sharing/tests/JHello.java deleted file mode 100644 index 8af527d4ef6..00000000000 --- a/jdk/make/non-build-utils/sharing/tests/JHello.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - - -import java.awt.Font; -import javax.swing.JFrame; -import javax.swing.JLabel; - -public class JHello extends JFrame { - - public static void main(String[] args) { - System.out.println("Hello"); - - new JHello().show(); - if (args.length == 1 && args[0].equals("quit")) { - try { - Thread.currentThread().sleep(1000); - } catch (InterruptedException e) { - } - System.exit(0); - } - } - - - JHello() { - JLabel jlabel = new JLabel("Hello"); - jlabel.setFont(new Font("Monospaced", Font.PLAIN, 144)); - getContentPane().add(jlabel); - pack(); - } -} diff --git a/jdk/make/non-build-utils/src/build/tools/makeclasslist/MakeClasslist.java b/jdk/make/non-build-utils/src/build/tools/makeclasslist/MakeClasslist.java deleted file mode 100644 index d1ade9c3da0..00000000000 --- a/jdk/make/non-build-utils/src/build/tools/makeclasslist/MakeClasslist.java +++ /dev/null @@ -1,130 +0,0 @@ -/* - * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -package build.tools.makeclasslist; - -import java.io.*; -import java.util.*; -import java.util.jar.*; - -/** Reads a set of files containing the output of java - -XX:+TraceClassLoadingPreorder runs. Finds all classes that were - loaded from the bootstrap class path by comparing the prefix of - the load path to the current JRE's java.home system property. - Prints the names of these classes to stdout. -*/ - -public class MakeClasslist { - public static void main(String[] args) throws IOException { - List classes = new ArrayList<>(); - String origJavaHome = System.getProperty("java.home"); - String javaHome = origJavaHome.toLowerCase(); - if (javaHome.endsWith("jre")) { - origJavaHome = origJavaHome.substring(0, origJavaHome.length() - 4); - javaHome = javaHome.substring(0, javaHome.length() - 4); - } - for (int i = 0; i < args.length; i++) { - try { - File file = new File(args[i]); - BufferedReader reader = new BufferedReader(new FileReader(file)); - String line = null; - while ((line = reader.readLine()) != null) { - StringTokenizer tok = new StringTokenizer(line, "[ \t\n\r\f"); - if (tok.hasMoreTokens()) { - String t = tok.nextToken(); - // Understand only "Loading" from -XX:+TraceClassLoadingPreorder. - // This ignores old "Loaded" from -verbose:class to force correct - // classlist generation on Mustang. - if (t.equals("Loading")) { - t = tok.nextToken(); - t = t.replace('.', '/'); - - // Check to make sure it came from the boot class path - if (tok.hasMoreTokens()) { - String tmp = tok.nextToken(); - if (tmp.equals("from")) { - if (tok.hasMoreTokens()) { - tmp = tok.nextToken().toLowerCase(); - // System.err.println("Loaded " + t + " from " + tmp); - if (tmp.startsWith(javaHome)) { - // OK, remember this class for later - classes.add(t); - } - } - } - } - } - } - } - } catch (IOException e) { - System.err.println("Error reading file " + args[i]); - throw(e); - } - } - - Set seenClasses = new HashSet<>(); - - for (String str : classes) { - if (seenClasses.add(str)) { - System.out.println(str); - } - } - - // Try to complete certain packages - // Note: not using this new code yet; need to consider whether the - // footprint increase is worth any startup gains - // Note also that the packages considered below for completion are - // (obviously) platform-specific - // JarFile rtJar = new JarFile(origJavaHome + File.separator + - // "jre" + File.separator + - // "lib" + File.separator + - // "rt.jar"); - // completePackage(seenClasses, rtJar, "java/awt"); - // completePackage(seenClasses, rtJar, "sun/awt"); - // completePackage(seenClasses, rtJar, "sun/awt/X11"); - // completePackage(seenClasses, rtJar, "java/awt/im/spi"); - // completePackage(seenClasses, rtJar, "java/lang"); - } - - private static void completePackage(Set seenClasses, - JarFile jar, - String packageName) { - int len = packageName.length(); - Enumeration entries = jar.entries(); - while (entries.hasMoreElements()) { - JarEntry entry = entries.nextElement(); - String name = entry.getName(); - if (name.startsWith(packageName) && - name.endsWith(".class") && - name.lastIndexOf('/') == len) { - // Trim ".class" from end - name = name.substring(0, name.length() - 6); - if (seenClasses.add(name)) { - System.out.println(name); - } - } - } - } -} diff --git a/jdk/make/non-build-utils/src/build/tools/makeclasslist/makeClasslist.js b/jdk/make/non-build-utils/src/build/tools/makeclasslist/makeClasslist.js new file mode 100644 index 00000000000..3c5198949f3 --- /dev/null +++ b/jdk/make/non-build-utils/src/build/tools/makeclasslist/makeClasslist.js @@ -0,0 +1,62 @@ +/* + * Copyright (c) 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. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/** + * This tool is used to help create the class list for class data sharing. + * + * The classlist is produced internally by first running a select number of + * startup benchmarks with the -XX:DumpLoadedClassList= option, then + * running this tool in the following fashion to produce a complete classlist: + * + * jjs -scripting makeClasslist.js -- list1 list2 list3 > classlist.platform + * + * The lists should be listed in roughly smallest to largest order based on + * application size. + * + * After generating the classlist it's necessary to add a checksum (using + * AddJsum.java) before checking it into the workspace as the corresponding + * platform-specific classlist, such as make/data/classlist/classlist.linux + */ +"use strict"; +var classlist = []; +var seenClasses = {}; + +for (var a in $ARG) { + var arg = $ARG[a]; + + var classes = readFully(arg).replace(/[\r\n]+/g, "\n").split("\n"); + + for (var c in classes) { + var clazz = classes[c]; + if (clazz !== "" && seenClasses[clazz] === undefined) { + seenClasses[clazz] = clazz; + classlist.push(clazz); + } + } +} + +for (c in classlist) { + print(classlist[c]); +} From a1b2aad0802b3d9e797d468569ac0e1b58233049 Mon Sep 17 00:00:00 2001 From: Xue-Lei Andrew Fan Date: Wed, 8 Jul 2015 23:52:15 +0000 Subject: [PATCH 11/43] 8130460: Increase the stability of DTLS test CipherSuite.java Reviewed-by: wetmore --- jdk/test/javax/net/ssl/DTLS/DTLSOverDatagram.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/jdk/test/javax/net/ssl/DTLS/DTLSOverDatagram.java b/jdk/test/javax/net/ssl/DTLS/DTLSOverDatagram.java index c8912cc1e17..891ae7f0e29 100644 --- a/jdk/test/javax/net/ssl/DTLS/DTLSOverDatagram.java +++ b/jdk/test/javax/net/ssl/DTLS/DTLSOverDatagram.java @@ -46,8 +46,8 @@ import sun.misc.HexDumpEncoder; * An example to show the way to use SSLEngine in datagram connections. */ public class DTLSOverDatagram { - private static int MAX_HANDSHAKE_LOOPS = 60; - private static int MAX_APP_READ_LOOPS = 10; + private static int MAX_HANDSHAKE_LOOPS = 200; + private static int MAX_APP_READ_LOOPS = 60; /* * The following is to set up the keystores. From 74427b9101f5854514a5548110116b5feeea93f3 Mon Sep 17 00:00:00 2001 From: Roger Riggs Date: Wed, 8 Jul 2015 21:54:32 -0400 Subject: [PATCH 12/43] 8130296: [TESTBUG] java/lang/ProcessHandle/OnExitTest - Unaccounted for children expected [0] but found [1] Ignore extra processes that are not created by the test and cleanup any remaining child processes Reviewed-by: darcy --- .../java/lang/ProcessHandle/OnExitTest.java | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/jdk/test/java/lang/ProcessHandle/OnExitTest.java b/jdk/test/java/lang/ProcessHandle/OnExitTest.java index e2700945a8b..5de89a3a353 100644 --- a/jdk/test/java/lang/ProcessHandle/OnExitTest.java +++ b/jdk/test/java/lang/ProcessHandle/OnExitTest.java @@ -27,16 +27,19 @@ import java.time.Duration; import java.time.Instant; import java.util.ArrayList; import java.util.List; -import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutionException; + +import jdk.testlibrary.Utils; + import org.testng.annotations.Test; import org.testng.Assert; import org.testng.TestNG; /* * @test + * @build jdk.testlibrary.Utils * @summary Functions of Process.onExit and ProcessHandle.onExit * @author Roger Riggs */ @@ -88,6 +91,7 @@ public class OnExitTest extends ProcessUtil { */ @Test public static void test2() { + ProcessHandle procHandle = null; try { ConcurrentHashMap processes = new ConcurrentHashMap<>(); List children = getChildren(ProcessHandle.current()); @@ -96,7 +100,7 @@ public class OnExitTest extends ProcessUtil { "Expected to start with zero children; " + children); JavaChild proc = JavaChild.spawnJavaChild("stdin"); - ProcessHandle procHandle = proc.toHandle(); + procHandle = proc.toHandle(); printf(" spawned: %d%n", proc.getPid()); proc.forEachOutputLine((s) -> { @@ -114,7 +118,8 @@ public class OnExitTest extends ProcessUtil { // Poll until all 9 child processes exist or the timeout is reached int expected = 9; - Instant endTimeout = Instant.now().plusSeconds(10L); + long timeout = Utils.adjustTimeout(10L); + Instant endTimeout = Instant.now().plusSeconds(timeout); do { Thread.sleep(200L); printf(" subprocess count: %d, waiting for %d%n", processes.size(), expected); @@ -180,13 +185,12 @@ public class OnExitTest extends ProcessUtil { List children2 = getAllChildren(procHandle); printf(" children2: %s%n", children2.toString()); Assert.assertEquals(children2.size(), 0, "After onExit, expected no children"); - - Assert.assertEquals(remaining.size(), 0, "Unaccounted for children"); - } catch (IOException | InterruptedException ex) { Assert.fail(ex.getMessage()); } finally { - destroyProcessTree(ProcessHandle.current()); + if (procHandle != null) { + destroyProcessTree(procHandle); + } } } From 82f8a148088b1e757a17254fe64fe1be082d0e62 Mon Sep 17 00:00:00 2001 From: Ivan Gerasimov Date: Thu, 9 Jul 2015 10:37:07 +0300 Subject: [PATCH 13/43] 8130022: Use Java-style array declarations consistently Reviewed-by: coffeys --- .../java/security/AccessControlContext.java | 16 +++--- .../classes/java/security/CodeSource.java | 4 +- .../classes/java/security/Permissions.java | 4 +- .../classes/java/security/SecureRandom.java | 8 +-- .../java/security/UnresolvedPermission.java | 6 +-- .../spec/RSAMultiPrimePrivateCrtKeySpec.java | 2 +- .../classes/sun/security/pkcs/PKCS7.java | 2 +- .../classes/sun/security/pkcs/PKCS8Key.java | 2 +- .../sun/security/pkcs12/PKCS12KeyStore.java | 24 ++++----- .../sun/security/provider/AuthPolicyFile.java | 6 +-- .../provider/DSAParameterGenerator.java | 2 +- .../sun/security/provider/JavaKeyStore.java | 9 ++-- .../sun/security/provider/PolicyFile.java | 8 +-- .../sun/security/provider/PolicyParser.java | 2 +- .../sun/security/provider/SecureRandom.java | 2 +- .../security/ssl/ByteBufferInputStream.java | 4 +- .../sun/security/ssl/ClientHandshaker.java | 2 +- .../sun/security/ssl/DHClientKeyExchange.java | 2 +- .../sun/security/ssl/HandshakeInStream.java | 6 +-- .../sun/security/ssl/HandshakeMessage.java | 40 +++++++------- .../sun/security/ssl/HandshakeOutStream.java | 4 +- .../share/classes/sun/security/ssl/MAC.java | 2 +- .../sun/security/ssl/RandomCookie.java | 2 +- .../sun/security/ssl/ServerHandshaker.java | 2 +- .../classes/sun/security/ssl/SessionId.java | 8 +-- .../security/ssl/X509TrustManagerImpl.java | 4 +- .../sun/security/util/ManifestDigester.java | 17 +++--- .../security/util/ManifestEntryVerifier.java | 2 +- .../sun/security/util/ObjectIdentifier.java | 2 +- .../security/util/SignatureFileVerifier.java | 8 +-- .../share/classes/sun/security/x509/AVA.java | 4 +- .../classes/sun/security/x509/AlgIdDSA.java | 2 +- .../sun/security/x509/AlgorithmId.java | 34 ++++++------ .../x509/NetscapeCertTypeExtension.java | 2 +- .../classes/sun/security/x509/OIDMap.java | 2 +- .../sun/security/x509/PKIXExtensions.java | 52 +++++++++---------- .../classes/sun/security/x509/X500Name.java | 34 ++++++------ .../sun/security/x509/X509CRLImpl.java | 2 +- .../auth/kerberos/ServicePermission.java | 2 +- .../sun/security/jgss/GSSCredentialImpl.java | 2 +- .../sun/security/jgss/GSSManagerImpl.java | 6 +-- .../sun/security/jgss/krb5/Krb5Context.java | 20 +++---- .../sun/security/jgss/spi/GSSContextSpi.java | 14 ++--- .../jgss/wrapper/NativeGSSContext.java | 2 +- .../jgss/wrapper/SunNativeProvider.java | 2 +- .../sun/security/krb5/PrincipalName.java | 2 +- .../security/krb5/internal/Authenticator.java | 2 +- .../krb5/internal/AuthorizationData.java | 2 +- .../security/krb5/internal/EncAPRepPart.java | 2 +- .../krb5/internal/EncKrbCredPart.java | 2 +- .../security/krb5/internal/HostAddresses.java | 4 +- .../security/krb5/internal/KDCReqBody.java | 2 +- .../security/krb5/internal/KrbCredInfo.java | 2 +- .../sun/security/krb5/internal/NetClient.java | 2 +- .../sun/security/krb5/internal/Ticket.java | 2 +- .../internal/ccache/CCacheInputStream.java | 6 +-- .../security/krb5/internal/crypto/crc32.java | 2 +- .../internal/ssl/KerberosPreMasterSecret.java | 4 +- .../sun/security/sasl/ClientFactoryImpl.java | 4 +- .../com/sun/security/sasl/CramMD5Server.java | 4 +- .../sun/security/sasl/ServerFactoryImpl.java | 4 +- .../security/sasl/digest/DigestMD5Base.java | 4 +- .../sun/security/sasl/digest/FactoryImpl.java | 4 +- .../sun/security/sasl/ntlm/FactoryImpl.java | 4 +- .../classes/sun/security/mscapi/KeyStore.java | 2 +- .../sun/security/pkcs11/P11Cipher.java | 2 +- .../sun/security/pkcs11/P11KeyStore.java | 2 +- .../pkcs11/wrapper/CK_AES_CTR_PARAMS.java | 2 +- .../security/ucrypto/UcryptoException.java | 2 +- .../com/sun/security/auth/module/Crypt.java | 4 +- .../security/auth/module/JndiLoginModule.java | 4 +- .../security/auth/module/NTLoginModule.java | 4 +- .../sun/security/auth/module/NTSystem.java | 2 +- .../security/sasl/gsskerb/FactoryImpl.java | 4 +- 74 files changed, 233 insertions(+), 235 deletions(-) diff --git a/jdk/src/java.base/share/classes/java/security/AccessControlContext.java b/jdk/src/java.base/share/classes/java/security/AccessControlContext.java index 5e588602c97..f2ca4129309 100644 --- a/jdk/src/java.base/share/classes/java/security/AccessControlContext.java +++ b/jdk/src/java.base/share/classes/java/security/AccessControlContext.java @@ -76,7 +76,7 @@ import sun.security.util.SecurityConstants; public final class AccessControlContext { - private ProtectionDomain context[]; + private ProtectionDomain[] context; // isPrivileged and isAuthorized are referenced by the VM - do not remove // or change their names private boolean isPrivileged; @@ -89,13 +89,13 @@ public final class AccessControlContext { private DomainCombiner combiner = null; // limited privilege scope - private Permission permissions[]; + private Permission[] permissions; private AccessControlContext parent; private boolean isWrapped; // is constrained by limited privilege scope? private boolean isLimited; - private ProtectionDomain limitedContext[]; + private ProtectionDomain[] limitedContext; private static boolean debugInit = false; private static Debug debug = null; @@ -123,7 +123,7 @@ public final class AccessControlContext { * changes to the array will not affect this AccessControlContext. * @throws NullPointerException if {@code context} is {@code null} */ - public AccessControlContext(ProtectionDomain context[]) + public AccessControlContext(ProtectionDomain[] context) { if (context.length == 0) { this.context = null; @@ -282,7 +282,7 @@ public final class AccessControlContext { * package private constructor for AccessController.getContext() */ - AccessControlContext(ProtectionDomain context[], + AccessControlContext(ProtectionDomain[] context, boolean isPrivileged) { this.context = context; @@ -643,7 +643,7 @@ public final class AccessControlContext { /* * Combine the current (stack) and assigned domains. */ - private static ProtectionDomain[] combine(ProtectionDomain[]current, + private static ProtectionDomain[] combine(ProtectionDomain[] current, ProtectionDomain[] assigned) { // current could be null if only system code is on the stack; @@ -666,7 +666,7 @@ public final class AccessControlContext { int n = (skipAssigned) ? 0 : assigned.length; // now we combine both of them, and create a new context - ProtectionDomain pd[] = new ProtectionDomain[slen + n]; + ProtectionDomain[] pd = new ProtectionDomain[slen + n]; // first copy in the assigned context domains, no need to compress if (!skipAssigned) { @@ -695,7 +695,7 @@ public final class AccessControlContext { } else if (skipAssigned && n == slen) { return current; } - ProtectionDomain tmp[] = new ProtectionDomain[n]; + ProtectionDomain[] tmp = new ProtectionDomain[n]; System.arraycopy(pd, 0, tmp, 0, n); pd = tmp; } diff --git a/jdk/src/java.base/share/classes/java/security/CodeSource.java b/jdk/src/java.base/share/classes/java/security/CodeSource.java index afd3fffd05f..c08050a9f03 100644 --- a/jdk/src/java.base/share/classes/java/security/CodeSource.java +++ b/jdk/src/java.base/share/classes/java/security/CodeSource.java @@ -65,7 +65,7 @@ public class CodeSource implements java.io.Serializable { /* * The code signers. Certificate chains are concatenated. */ - private transient java.security.cert.Certificate certs[] = null; + private transient java.security.cert.Certificate[] certs = null; // cached SocketPermission used for matchLocation private transient SocketPermission sp; @@ -91,7 +91,7 @@ public class CodeSource implements java.io.Serializable { * @param certs the certificate(s). It may be null. The contents of the * array are copied to protect against subsequent modification. */ - public CodeSource(URL url, java.security.cert.Certificate certs[]) { + public CodeSource(URL url, java.security.cert.Certificate[] certs) { this.location = url; if (url != null) { this.locationNoFragString = URLUtil.urlNoFragString(url); diff --git a/jdk/src/java.base/share/classes/java/security/Permissions.java b/jdk/src/java.base/share/classes/java/security/Permissions.java index b9a834a40da..6bb5fa1a445 100644 --- a/jdk/src/java.base/share/classes/java/security/Permissions.java +++ b/jdk/src/java.base/share/classes/java/security/Permissions.java @@ -289,9 +289,9 @@ implements Serializable if (unresolvedPerms == null) return null; - java.security.cert.Certificate certs[] = null; + java.security.cert.Certificate[] certs = null; - Object signers[] = p.getClass().getSigners(); + Object[] signers = p.getClass().getSigners(); int n = 0; if (signers != null) { diff --git a/jdk/src/java.base/share/classes/java/security/SecureRandom.java b/jdk/src/java.base/share/classes/java/security/SecureRandom.java index f1531de25f7..09b5a008f9c 100644 --- a/jdk/src/java.base/share/classes/java/security/SecureRandom.java +++ b/jdk/src/java.base/share/classes/java/security/SecureRandom.java @@ -69,7 +69,7 @@ import sun.security.util.Debug; * *
  *      SecureRandom random = new SecureRandom();
- *      byte bytes[] = new byte[20];
+ *      byte[] bytes = new byte[20];
  *      random.nextBytes(bytes);
  * 
* @@ -77,7 +77,7 @@ import sun.security.util.Debug; * to generate a given number of seed bytes (to seed other random number * generators, for example): *
- *      byte seed[] = random.generateSeed(20);
+ *      byte[] seed = random.generateSeed(20);
  * 
* * Note: Depending on the implementation, the {@code generateSeed} and @@ -186,7 +186,7 @@ public class SecureRandom extends java.util.Random { * * @param seed the seed. */ - public SecureRandom(byte seed[]) { + public SecureRandom(byte[] seed) { super(0); getDefaultPRNG(true, seed); } @@ -486,7 +486,7 @@ public class SecureRandom extends java.util.Random { @Override final protected int next(int numBits) { int numBytes = (numBits+7)/8; - byte b[] = new byte[numBytes]; + byte[] b = new byte[numBytes]; int next = 0; nextBytes(b); diff --git a/jdk/src/java.base/share/classes/java/security/UnresolvedPermission.java b/jdk/src/java.base/share/classes/java/security/UnresolvedPermission.java index e5b0d3047aa..9827788806a 100644 --- a/jdk/src/java.base/share/classes/java/security/UnresolvedPermission.java +++ b/jdk/src/java.base/share/classes/java/security/UnresolvedPermission.java @@ -130,7 +130,7 @@ implements java.io.Serializable */ private String actions; - private transient java.security.cert.Certificate certs[]; + private transient java.security.cert.Certificate[] certs; /** * Creates a new UnresolvedPermission containing the permission @@ -152,7 +152,7 @@ implements java.io.Serializable public UnresolvedPermission(String type, String name, String actions, - java.security.cert.Certificate certs[]) + java.security.cert.Certificate[] certs) { super(type); @@ -224,7 +224,7 @@ implements java.io.Serializable * try and resolve this permission using the class loader of the permission * that was passed in. */ - Permission resolve(Permission p, java.security.cert.Certificate certs[]) { + Permission resolve(Permission p, java.security.cert.Certificate[] certs) { if (this.certs != null) { // if p wasn't signed, we don't have a match if (certs == null) { diff --git a/jdk/src/java.base/share/classes/java/security/spec/RSAMultiPrimePrivateCrtKeySpec.java b/jdk/src/java.base/share/classes/java/security/spec/RSAMultiPrimePrivateCrtKeySpec.java index a198e43a2e1..268d2550b67 100644 --- a/jdk/src/java.base/share/classes/java/security/spec/RSAMultiPrimePrivateCrtKeySpec.java +++ b/jdk/src/java.base/share/classes/java/security/spec/RSAMultiPrimePrivateCrtKeySpec.java @@ -54,7 +54,7 @@ public class RSAMultiPrimePrivateCrtKeySpec extends RSAPrivateKeySpec { private final BigInteger primeExponentP; private final BigInteger primeExponentQ; private final BigInteger crtCoefficient; - private final RSAOtherPrimeInfo otherPrimeInfo[]; + private final RSAOtherPrimeInfo[] otherPrimeInfo; /** * Creates a new {@code RSAMultiPrimePrivateCrtKeySpec} diff --git a/jdk/src/java.base/share/classes/sun/security/pkcs/PKCS7.java b/jdk/src/java.base/share/classes/sun/security/pkcs/PKCS7.java index d525a617ada..5c6c625aa0a 100644 --- a/jdk/src/java.base/share/classes/sun/security/pkcs/PKCS7.java +++ b/jdk/src/java.base/share/classes/sun/security/pkcs/PKCS7.java @@ -507,7 +507,7 @@ public class PKCS7 { // certificates (optional) if (certificates != null && certificates.length != 0) { // cast to X509CertImpl[] since X509CertImpl implements DerEncoder - X509CertImpl implCerts[] = new X509CertImpl[certificates.length]; + X509CertImpl[] implCerts = new X509CertImpl[certificates.length]; for (int i = 0; i < certificates.length; i++) { if (certificates[i] instanceof X509CertImpl) implCerts[i] = (X509CertImpl) certificates[i]; diff --git a/jdk/src/java.base/share/classes/sun/security/pkcs/PKCS8Key.java b/jdk/src/java.base/share/classes/sun/security/pkcs/PKCS8Key.java index 59512f11b6e..88742d37668 100644 --- a/jdk/src/java.base/share/classes/sun/security/pkcs/PKCS8Key.java +++ b/jdk/src/java.base/share/classes/sun/security/pkcs/PKCS8Key.java @@ -78,7 +78,7 @@ public class PKCS8Key implements PrivateKey { * data is stored and transmitted losslessly, but no knowledge * about this particular algorithm is available. */ - private PKCS8Key (AlgorithmId algid, byte key []) + private PKCS8Key (AlgorithmId algid, byte[] key) throws InvalidKeyException { this.algid = algid; this.key = key; diff --git a/jdk/src/java.base/share/classes/sun/security/pkcs12/PKCS12KeyStore.java b/jdk/src/java.base/share/classes/sun/security/pkcs12/PKCS12KeyStore.java index d5755edb12d..a8c5fa709ba 100644 --- a/jdk/src/java.base/share/classes/sun/security/pkcs12/PKCS12KeyStore.java +++ b/jdk/src/java.base/share/classes/sun/security/pkcs12/PKCS12KeyStore.java @@ -154,28 +154,28 @@ public final class PKCS12KeyStore extends KeyStoreSpi { private static final Debug debug = Debug.getInstance("pkcs12"); - private static final int keyBag[] = {1, 2, 840, 113549, 1, 12, 10, 1, 2}; - private static final int certBag[] = {1, 2, 840, 113549, 1, 12, 10, 1, 3}; - private static final int secretBag[] = {1, 2, 840, 113549, 1, 12, 10, 1, 5}; + private static final int[] keyBag = {1, 2, 840, 113549, 1, 12, 10, 1, 2}; + private static final int[] certBag = {1, 2, 840, 113549, 1, 12, 10, 1, 3}; + private static final int[] secretBag = {1, 2, 840, 113549, 1, 12, 10, 1, 5}; - private static final int pkcs9Name[] = {1, 2, 840, 113549, 1, 9, 20}; - private static final int pkcs9KeyId[] = {1, 2, 840, 113549, 1, 9, 21}; + private static final int[] pkcs9Name = {1, 2, 840, 113549, 1, 9, 20}; + private static final int[] pkcs9KeyId = {1, 2, 840, 113549, 1, 9, 21}; - private static final int pkcs9certType[] = {1, 2, 840, 113549, 1, 9, 22, 1}; + private static final int[] pkcs9certType = {1, 2, 840, 113549, 1, 9, 22, 1}; - private static final int pbeWithSHAAnd40BitRC2CBC[] = + private static final int[] pbeWithSHAAnd40BitRC2CBC = {1, 2, 840, 113549, 1, 12, 1, 6}; - private static final int pbeWithSHAAnd3KeyTripleDESCBC[] = + private static final int[] pbeWithSHAAnd3KeyTripleDESCBC = {1, 2, 840, 113549, 1, 12, 1, 3}; - private static final int pbes2[] = {1, 2, 840, 113549, 1, 5, 13}; + private static final int[] pbes2 = {1, 2, 840, 113549, 1, 5, 13}; // TODO: temporary Oracle OID /* * { joint-iso-itu-t(2) country(16) us(840) organization(1) oracle(113894) * jdk(746875) crypto(1) id-at-trustedKeyUsage(1) } */ - private static final int TrustedKeyUsage[] = + private static final int[] TrustedKeyUsage = {2, 16, 840, 1, 113894, 746875, 1, 1}; - private static final int AnyExtendedKeyUsage[] = {2, 5, 29, 37, 0}; + private static final int[] AnyExtendedKeyUsage = {2, 5, 29, 37, 0}; private static ObjectIdentifier PKCS8ShroudedKeyBag_OID; private static ObjectIdentifier CertBag_OID; @@ -243,7 +243,7 @@ public final class PKCS12KeyStore extends KeyStoreSpi { // A private key entry and its supporting certificate chain private static class PrivateKeyEntry extends KeyEntry { byte[] protectedPrivKey; - Certificate chain[]; + Certificate[] chain; }; // A secret key diff --git a/jdk/src/java.base/share/classes/sun/security/provider/AuthPolicyFile.java b/jdk/src/java.base/share/classes/sun/security/provider/AuthPolicyFile.java index b93c4d863f6..05150c95145 100644 --- a/jdk/src/java.base/share/classes/sun/security/provider/AuthPolicyFile.java +++ b/jdk/src/java.base/share/classes/sun/security/provider/AuthPolicyFile.java @@ -403,7 +403,7 @@ public class AuthPolicyFile extends javax.security.auth.Policy { debug.println(" "+perm); } } catch (ClassNotFoundException cnfe) { - Certificate certs[]; + Certificate[] certs; if (pe.signedBy != null) { certs = getCertificates(keyStore, pe.signedBy); } else { @@ -623,7 +623,7 @@ public class AuthPolicyFile extends javax.security.auth.Policy { init(); } - final CodeSource codesource[] = {null}; + final CodeSource[] codesource = {null}; codesource[0] = canonicalizeCodebase(cs, true); @@ -666,7 +666,7 @@ public class AuthPolicyFile extends javax.security.auth.Policy { // now see if any of the keys are trusted ids. if (!ignoreIdentityScope) { - Certificate certs[] = codesource[0].getCertificates(); + Certificate[] certs = codesource[0].getCertificates(); if (certs != null) { for (int k=0; k < certs.length; k++) { if (aliasMapping.get(certs[k]) == null && diff --git a/jdk/src/java.base/share/classes/sun/security/provider/DSAParameterGenerator.java b/jdk/src/java.base/share/classes/sun/security/provider/DSAParameterGenerator.java index ac50e96f268..a8d4803dcbb 100644 --- a/jdk/src/java.base/share/classes/sun/security/provider/DSAParameterGenerator.java +++ b/jdk/src/java.base/share/classes/sun/security/provider/DSAParameterGenerator.java @@ -237,7 +237,7 @@ public class DSAParameterGenerator extends AlgorithmParameterGeneratorSpi { BigInteger offset = ONE; /* Step 11 */ for (counter = 0; counter < 4*valueL; counter++) { - BigInteger V[] = new BigInteger[n + 1]; + BigInteger[] V = new BigInteger[n + 1]; /* Step 11.1 */ for (int j = 0; j <= n; j++) { BigInteger J = BigInteger.valueOf(j); diff --git a/jdk/src/java.base/share/classes/sun/security/provider/JavaKeyStore.java b/jdk/src/java.base/share/classes/sun/security/provider/JavaKeyStore.java index 59b759bd3c8..49d645b863f 100644 --- a/jdk/src/java.base/share/classes/sun/security/provider/JavaKeyStore.java +++ b/jdk/src/java.base/share/classes/sun/security/provider/JavaKeyStore.java @@ -82,7 +82,7 @@ public abstract class JavaKeyStore extends KeyStoreSpi { private static class KeyEntry { Date date; // the creation date of this entry byte[] protectedPrivKey; - Certificate chain[]; + Certificate[] chain; }; // Trusted certificates @@ -604,7 +604,7 @@ public abstract class JavaKeyStore extends KeyStoreSpi { * the keystore (such as deleting or modifying key or * certificate entries). */ - byte digest[] = md.digest(); + byte[] digest = md.digest(); dos.write(digest); dos.flush(); @@ -770,9 +770,8 @@ public abstract class JavaKeyStore extends KeyStoreSpi { * with */ if (password != null) { - byte computed[], actual[]; - computed = md.digest(); - actual = new byte[computed.length]; + byte[] computed = md.digest(); + byte[] actual = new byte[computed.length]; dis.readFully(actual); for (int i = 0; i < computed.length; i++) { if (computed[i] != actual[i]) { diff --git a/jdk/src/java.base/share/classes/sun/security/provider/PolicyFile.java b/jdk/src/java.base/share/classes/sun/security/provider/PolicyFile.java index 33605436f82..58d483e4293 100644 --- a/jdk/src/java.base/share/classes/sun/security/provider/PolicyFile.java +++ b/jdk/src/java.base/share/classes/sun/security/provider/PolicyFile.java @@ -795,7 +795,7 @@ public class PolicyFile extends java.security.Policy { // an unresolved permission which will be resolved // when implies is called // Add it to entry - Certificate certs[]; + Certificate[] certs; if (pe.signedBy != null) { certs = getCertificates(keyStore, pe.signedBy, @@ -817,7 +817,7 @@ public class PolicyFile extends java.security.Policy { debug.println(" "+perm); } } catch (ClassNotFoundException cnfe) { - Certificate certs[]; + Certificate[] certs; if (pe.signedBy != null) { certs = getCertificates(keyStore, pe.signedBy, @@ -2032,7 +2032,7 @@ public class PolicyFile extends java.security.Policy { * * @serial */ - private Certificate certs[]; + private Certificate[] certs; /** * Creates a new SelfPermission containing the permission @@ -2048,7 +2048,7 @@ public class PolicyFile extends java.security.Policy { * certificate first and the (root) certificate authority last). */ public SelfPermission(String type, String name, String actions, - Certificate certs[]) + Certificate[] certs) { super(type); if (type == null) { diff --git a/jdk/src/java.base/share/classes/sun/security/provider/PolicyParser.java b/jdk/src/java.base/share/classes/sun/security/provider/PolicyParser.java index 2658a9e03ba..ba8ed750254 100644 --- a/jdk/src/java.base/share/classes/sun/security/provider/PolicyParser.java +++ b/jdk/src/java.base/share/classes/sun/security/provider/PolicyParser.java @@ -1353,7 +1353,7 @@ public class PolicyParser { } } - public static void main(String arg[]) throws Exception { + public static void main(String[] arg) throws Exception { try (FileReader fr = new FileReader(arg[0]); FileWriter fw = new FileWriter(arg[1])) { PolicyParser pp = new PolicyParser(true); diff --git a/jdk/src/java.base/share/classes/sun/security/provider/SecureRandom.java b/jdk/src/java.base/share/classes/sun/security/provider/SecureRandom.java index 99edb6a89d2..167558bd8f8 100644 --- a/jdk/src/java.base/share/classes/sun/security/provider/SecureRandom.java +++ b/jdk/src/java.base/share/classes/sun/security/provider/SecureRandom.java @@ -85,7 +85,7 @@ implements java.io.Serializable { * * @param seed the seed. */ - private SecureRandom(byte seed[]) { + private SecureRandom(byte[] seed) { init(seed); } diff --git a/jdk/src/java.base/share/classes/sun/security/ssl/ByteBufferInputStream.java b/jdk/src/java.base/share/classes/sun/security/ssl/ByteBufferInputStream.java index 05107988a53..753a728a1b8 100644 --- a/jdk/src/java.base/share/classes/sun/security/ssl/ByteBufferInputStream.java +++ b/jdk/src/java.base/share/classes/sun/security/ssl/ByteBufferInputStream.java @@ -70,7 +70,7 @@ class ByteBufferInputStream extends InputStream { * Increments position(). */ @Override - public int read(byte b[]) throws IOException { + public int read(byte[] b) throws IOException { if (bb == null) { throw new IOException("read on a closed InputStream"); @@ -85,7 +85,7 @@ class ByteBufferInputStream extends InputStream { * Increments position(). */ @Override - public int read(byte b[], int off, int len) throws IOException { + public int read(byte[] b, int off, int len) throws IOException { if (bb == null) { throw new IOException("read on a closed InputStream"); diff --git a/jdk/src/java.base/share/classes/sun/security/ssl/ClientHandshaker.java b/jdk/src/java.base/share/classes/sun/security/ssl/ClientHandshaker.java index 1561fc5b893..16384007238 100644 --- a/jdk/src/java.base/share/classes/sun/security/ssl/ClientHandshaker.java +++ b/jdk/src/java.base/share/classes/sun/security/ssl/ClientHandshaker.java @@ -810,7 +810,7 @@ final class ClientHandshaker extends Handshaker { String alias = null; int keytypesTmpSize = keytypesTmp.size(); if (keytypesTmpSize != 0) { - String keytypes[] = + String[] keytypes = keytypesTmp.toArray(new String[keytypesTmpSize]); if (conn != null) { diff --git a/jdk/src/java.base/share/classes/sun/security/ssl/DHClientKeyExchange.java b/jdk/src/java.base/share/classes/sun/security/ssl/DHClientKeyExchange.java index 94426f47d70..878a8fd0203 100644 --- a/jdk/src/java.base/share/classes/sun/security/ssl/DHClientKeyExchange.java +++ b/jdk/src/java.base/share/classes/sun/security/ssl/DHClientKeyExchange.java @@ -48,7 +48,7 @@ final class DHClientKeyExchange extends HandshakeMessage { * This value may be empty if it was included in the * client's certificate ... */ - private byte dh_Yc[]; // 1 to 2^16 -1 bytes + private byte[] dh_Yc; // 1 to 2^16 -1 bytes BigInteger getClientPublicKey() { return dh_Yc == null ? null : new BigInteger(1, dh_Yc); diff --git a/jdk/src/java.base/share/classes/sun/security/ssl/HandshakeInStream.java b/jdk/src/java.base/share/classes/sun/security/ssl/HandshakeInStream.java index 2111f344609..f61d1beb6f3 100644 --- a/jdk/src/java.base/share/classes/sun/security/ssl/HandshakeInStream.java +++ b/jdk/src/java.base/share/classes/sun/security/ssl/HandshakeInStream.java @@ -146,7 +146,7 @@ public final class HandshakeInStream extends ByteArrayInputStream { byte[] getBytes8() throws IOException { int len = getInt8(); verifyLength(len); - byte b[] = new byte[len]; + byte[] b = new byte[len]; read(b); return b; @@ -155,7 +155,7 @@ public final class HandshakeInStream extends ByteArrayInputStream { public byte[] getBytes16() throws IOException { int len = getInt16(); verifyLength(len); - byte b[] = new byte[len]; + byte[] b = new byte[len]; read(b); return b; @@ -164,7 +164,7 @@ public final class HandshakeInStream extends ByteArrayInputStream { byte[] getBytes24() throws IOException { int len = getInt24(); verifyLength(len); - byte b[] = new byte[len]; + byte[] b = new byte[len]; read(b); return b; diff --git a/jdk/src/java.base/share/classes/sun/security/ssl/HandshakeMessage.java b/jdk/src/java.base/share/classes/sun/security/ssl/HandshakeMessage.java index 00b84262e09..f4452faaa2c 100644 --- a/jdk/src/java.base/share/classes/sun/security/ssl/HandshakeMessage.java +++ b/jdk/src/java.base/share/classes/sun/security/ssl/HandshakeMessage.java @@ -689,8 +689,8 @@ static abstract class ServerKeyExchange extends HandshakeMessage static final class RSA_ServerKeyExchange extends ServerKeyExchange { - private byte rsa_modulus[]; // 1 to 2^16 - 1 bytes - private byte rsa_exponent[]; // 1 to 2^16 - 1 bytes + private byte[] rsa_modulus; // 1 to 2^16 - 1 bytes + private byte[] rsa_exponent; // 1 to 2^16 - 1 bytes private Signature signature; private byte[] signatureBytes; @@ -698,7 +698,7 @@ class RSA_ServerKeyExchange extends ServerKeyExchange /* * Hash the nonces and the ephemeral RSA public key. */ - private void updateSignature(byte clntNonce[], byte svrNonce[]) + private void updateSignature(byte[] clntNonce, byte[] svrNonce) throws SignatureException { int tmp; @@ -827,11 +827,11 @@ class DH_ServerKeyExchange extends ServerKeyExchange private final static boolean dhKeyExchangeFix = Debug.getBooleanProperty("com.sun.net.ssl.dhKeyExchangeFix", true); - private byte dh_p []; // 1 to 2^16 - 1 bytes - private byte dh_g []; // 1 to 2^16 - 1 bytes - private byte dh_Ys []; // 1 to 2^16 - 1 bytes + private byte[] dh_p; // 1 to 2^16 - 1 bytes + private byte[] dh_g; // 1 to 2^16 - 1 bytes + private byte[] dh_Ys; // 1 to 2^16 - 1 bytes - private byte signature []; + private byte[] signature; // protocol version being established using this ServerKeyExchange message ProtocolVersion protocolVersion; @@ -857,8 +857,8 @@ class DH_ServerKeyExchange extends ServerKeyExchange * with the cert chain which was sent ... for DHE_DSS and DHE_RSA * key exchange. (Constructor called by server.) */ - DH_ServerKeyExchange(DHCrypt obj, PrivateKey key, byte clntNonce[], - byte svrNonce[], SecureRandom sr, + DH_ServerKeyExchange(DHCrypt obj, PrivateKey key, byte[] clntNonce, + byte[] svrNonce, SecureRandom sr, SignatureAndHashAlgorithm signAlgorithm, ProtocolVersion protocolVersion) throws GeneralSecurityException { @@ -913,7 +913,7 @@ class DH_ServerKeyExchange extends ServerKeyExchange * DHE_DSS or DHE_RSA key exchange. (Called by client.) */ DH_ServerKeyExchange(HandshakeInStream input, PublicKey publicKey, - byte clntNonce[], byte svrNonce[], int messageSize, + byte[] clntNonce, byte[] svrNonce, int messageSize, Collection localSupportedSignAlgs, ProtocolVersion protocolVersion) throws IOException, GeneralSecurityException { @@ -948,7 +948,7 @@ class DH_ServerKeyExchange extends ServerKeyExchange } // read the signature - byte signature[]; + byte[] signature; if (dhKeyExchangeFix) { signature = input.getBytes16(); } else { @@ -1004,8 +1004,8 @@ class DH_ServerKeyExchange extends ServerKeyExchange /* * Update sig with nonces and Diffie-Hellman public key. */ - private void updateSignature(Signature sig, byte clntNonce[], - byte svrNonce[]) throws SignatureException { + private void updateSignature(Signature sig, byte[] clntNonce, + byte[] svrNonce) throws SignatureException { int tmp; sig.update(clntNonce); @@ -1268,8 +1268,8 @@ class ECDH_ServerKeyExchange extends ServerKeyExchange { } } - private void updateSignature(Signature sig, byte clntNonce[], - byte svrNonce[]) throws SignatureException { + private void updateSignature(Signature sig, byte[] clntNonce, + byte[] svrNonce) throws SignatureException { sig.update(clntNonce); sig.update(svrNonce); @@ -1334,7 +1334,7 @@ static final class DistinguishedName { * DER encoded distinguished name. * TLS requires that its not longer than 65535 bytes. */ - byte name[]; + byte[] name; DistinguishedName(HandshakeInStream input) throws IOException { name = input.getBytes16(); @@ -1411,8 +1411,8 @@ class CertificateRequest extends HandshakeMessage private final static byte[] TYPES_ECC = { cct_rsa_sign, cct_dss_sign, cct_ecdsa_sign }; - byte types []; // 1 to 255 types - DistinguishedName authorities []; // 3 to 2^16 - 1 + byte[] types; // 1 to 255 types + DistinguishedName[] authorities; // 3 to 2^16 - 1 // ... "3" because that's the smallest DER-encoded X500 DN // protocol version being established using this CertificateRequest message @@ -1424,7 +1424,7 @@ class CertificateRequest extends HandshakeMessage // length of supported_signature_algorithms private int algorithmsLen; - CertificateRequest(X509Certificate ca[], KeyExchange keyExchange, + CertificateRequest(X509Certificate[] ca, KeyExchange keyExchange, Collection signAlgs, ProtocolVersion protocolVersion) throws IOException { @@ -2063,7 +2063,7 @@ static final class Finished extends HandshakeMessage { if (protocolVersion.useTLS10PlusSpec()) { // TLS 1.0+ try { - byte [] seed; + byte[] seed; String prfAlg; PRF prf; diff --git a/jdk/src/java.base/share/classes/sun/security/ssl/HandshakeOutStream.java b/jdk/src/java.base/share/classes/sun/security/ssl/HandshakeOutStream.java index 99ab971ed86..049da437a32 100644 --- a/jdk/src/java.base/share/classes/sun/security/ssl/HandshakeOutStream.java +++ b/jdk/src/java.base/share/classes/sun/security/ssl/HandshakeOutStream.java @@ -119,7 +119,7 @@ public class HandshakeOutStream extends ByteArrayOutputStream { } } - public void putBytes16(byte b[]) throws IOException { + public void putBytes16(byte[] b) throws IOException { if (b == null) { putInt16(0); } else { @@ -128,7 +128,7 @@ public class HandshakeOutStream extends ByteArrayOutputStream { } } - void putBytes24(byte b[]) throws IOException { + void putBytes24(byte[] b) throws IOException { if (b == null) { putInt24(0); } else { diff --git a/jdk/src/java.base/share/classes/sun/security/ssl/MAC.java b/jdk/src/java.base/share/classes/sun/security/ssl/MAC.java index d78c8282794..c41b1bb8962 100644 --- a/jdk/src/java.base/share/classes/sun/security/ssl/MAC.java +++ b/jdk/src/java.base/share/classes/sun/security/ssl/MAC.java @@ -52,7 +52,7 @@ final class MAC extends Authenticator { final static MAC TLS_NULL = new MAC(false); // Value of the null MAC is fixed - private static final byte nullMAC[] = new byte[0]; + private static final byte[] nullMAC = new byte[0]; // internal identifier for the MAC algorithm private final MacAlg macAlg; diff --git a/jdk/src/java.base/share/classes/sun/security/ssl/RandomCookie.java b/jdk/src/java.base/share/classes/sun/security/ssl/RandomCookie.java index 22e50eb7c0e..5ba6b47da3e 100644 --- a/jdk/src/java.base/share/classes/sun/security/ssl/RandomCookie.java +++ b/jdk/src/java.base/share/classes/sun/security/ssl/RandomCookie.java @@ -38,7 +38,7 @@ import java.security.SecureRandom; */ final class RandomCookie { - byte random_bytes[]; // exactly 32 bytes + byte[] random_bytes; // exactly 32 bytes RandomCookie(SecureRandom generator) { long temp = System.currentTimeMillis() / 1000; diff --git a/jdk/src/java.base/share/classes/sun/security/ssl/ServerHandshaker.java b/jdk/src/java.base/share/classes/sun/security/ssl/ServerHandshaker.java index deea7949d9e..993ab27496d 100644 --- a/jdk/src/java.base/share/classes/sun/security/ssl/ServerHandshaker.java +++ b/jdk/src/java.base/share/classes/sun/security/ssl/ServerHandshaker.java @@ -986,7 +986,7 @@ final class ServerHandshaker extends Handshaker { ClientKeyExchangeService.find(keyExchange.name) == null) { CertificateRequest m4; - X509Certificate caCerts[]; + X509Certificate[] caCerts; Collection localSignAlgs = null; if (protocolVersion.useTLS12PlusSpec()) { diff --git a/jdk/src/java.base/share/classes/sun/security/ssl/SessionId.java b/jdk/src/java.base/share/classes/sun/security/ssl/SessionId.java index 31a4ab9f2f8..d716eb08e90 100644 --- a/jdk/src/java.base/share/classes/sun/security/ssl/SessionId.java +++ b/jdk/src/java.base/share/classes/sun/security/ssl/SessionId.java @@ -43,7 +43,7 @@ final class SessionId { static int MAX_LENGTH = 32; - private byte sessionId []; // max 32 bytes + private byte[] sessionId; // max 32 bytes /** Constructs a new session ID ... perhaps for a rejoinable session */ SessionId (boolean isRejoinable, SecureRandom generator) @@ -56,7 +56,7 @@ class SessionId } /** Constructs a session ID from a byte array (max size 32 bytes) */ - SessionId (byte sessionId []) + SessionId (byte[] sessionId) { this.sessionId = sessionId; } /** Returns the length of the ID, in bytes */ @@ -64,7 +64,7 @@ class SessionId { return sessionId.length; } /** Returns the bytes in the ID. May be an empty array. */ - byte [] getId () + byte[] getId () { return sessionId.clone (); } @@ -106,7 +106,7 @@ class SessionId return false; SessionId s = (SessionId) obj; - byte b [] = s.getId (); + byte[] b = s.getId (); if (b.length != sessionId.length) return false; diff --git a/jdk/src/java.base/share/classes/sun/security/ssl/X509TrustManagerImpl.java b/jdk/src/java.base/share/classes/sun/security/ssl/X509TrustManagerImpl.java index bff87c8f7e2..066b5c013ea 100644 --- a/jdk/src/java.base/share/classes/sun/security/ssl/X509TrustManagerImpl.java +++ b/jdk/src/java.base/share/classes/sun/security/ssl/X509TrustManagerImpl.java @@ -94,13 +94,13 @@ final class X509TrustManagerImpl extends X509ExtendedTrustManager } @Override - public void checkClientTrusted(X509Certificate chain[], String authType) + public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { checkTrusted(chain, authType, (Socket)null, true); } @Override - public void checkServerTrusted(X509Certificate chain[], String authType) + public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { checkTrusted(chain, authType, (Socket)null, false); } diff --git a/jdk/src/java.base/share/classes/sun/security/util/ManifestDigester.java b/jdk/src/java.base/share/classes/sun/security/util/ManifestDigester.java index 568e296f719..820ec18e0b1 100644 --- a/jdk/src/java.base/share/classes/sun/security/util/ManifestDigester.java +++ b/jdk/src/java.base/share/classes/sun/security/util/ManifestDigester.java @@ -37,7 +37,7 @@ public class ManifestDigester { public static final String MF_MAIN_ATTRS = "Manifest-Main-Attributes"; /** the raw bytes of the manifest */ - private byte rawBytes[]; + private byte[] rawBytes; /** the offset/length pair for a section */ private HashMap entries; // key is a UTF-8 string @@ -107,7 +107,7 @@ public class ManifestDigester { return false; } - public ManifestDigester(byte bytes[]) + public ManifestDigester(byte[] bytes) { rawBytes = bytes; entries = new HashMap<>(); @@ -181,7 +181,7 @@ public class ManifestDigester { } } - private boolean isNameAttr(byte bytes[], int start) + private boolean isNameAttr(byte[] bytes, int start) { return ((bytes[start] == 'N') || (bytes[start] == 'n')) && ((bytes[start+1] == 'a') || (bytes[start+1] == 'A')) && @@ -261,11 +261,10 @@ public class ManifestDigester { return e; } - public byte[] manifestDigest(MessageDigest md) - { - md.reset(); - md.update(rawBytes, 0, rawBytes.length); - return md.digest(); - } + public byte[] manifestDigest(MessageDigest md) { + md.reset(); + md.update(rawBytes, 0, rawBytes.length); + return md.digest(); + } } diff --git a/jdk/src/java.base/share/classes/sun/security/util/ManifestEntryVerifier.java b/jdk/src/java.base/share/classes/sun/security/util/ManifestEntryVerifier.java index 6fcc26143e2..19cc730ce6f 100644 --- a/jdk/src/java.base/share/classes/sun/security/util/ManifestEntryVerifier.java +++ b/jdk/src/java.base/share/classes/sun/security/util/ManifestEntryVerifier.java @@ -165,7 +165,7 @@ public class ManifestEntryVerifier { /** * update the digests for the digests we are interested in */ - public void update(byte buffer[], int off, int len) { + public void update(byte[] buffer, int off, int len) { if (skip) return; for (int i=0; i < digests.size(); i++) { diff --git a/jdk/src/java.base/share/classes/sun/security/util/ObjectIdentifier.java b/jdk/src/java.base/share/classes/sun/security/util/ObjectIdentifier.java index 5e8c6e0b1ae..ab92d1cdc40 100644 --- a/jdk/src/java.base/share/classes/sun/security/util/ObjectIdentifier.java +++ b/jdk/src/java.base/share/classes/sun/security/util/ObjectIdentifier.java @@ -212,7 +212,7 @@ class ObjectIdentifier implements Serializable * Constructor, from an array of integers. * Validity check included. */ - public ObjectIdentifier (int values []) throws IOException + public ObjectIdentifier(int[] values) throws IOException { checkCount(values.length); checkFirstComponent(values[0]); diff --git a/jdk/src/java.base/share/classes/sun/security/util/SignatureFileVerifier.java b/jdk/src/java.base/share/classes/sun/security/util/SignatureFileVerifier.java index 88d0ccb00e4..841aa0adabc 100644 --- a/jdk/src/java.base/share/classes/sun/security/util/SignatureFileVerifier.java +++ b/jdk/src/java.base/share/classes/sun/security/util/SignatureFileVerifier.java @@ -55,7 +55,7 @@ public class SignatureFileVerifier { private PKCS7 block; /** the raw bytes of the .SF file */ - private byte sfBytes[]; + private byte[] sfBytes; /** the name of the signature block file, uppercased and without * the extension (.DSA/.RSA/.EC) @@ -84,7 +84,7 @@ public class SignatureFileVerifier { public SignatureFileVerifier(ArrayList signerCache, ManifestDigester md, String name, - byte rawBytes[]) + byte[] rawBytes) throws IOException, CertificateException { // new PKCS7() calls CertificateFactory.getInstance() @@ -129,7 +129,7 @@ public class SignatureFileVerifier { * used to set the raw bytes of the .SF file when it * is external to the signature block file. */ - public void setSignatureFile(byte sfBytes[]) + public void setSignatureFile(byte[] sfBytes) { this.sfBytes = sfBytes; } @@ -511,7 +511,7 @@ public class SignatureFileVerifier { * CodeSigner objects. We do this only *once* for a given * signature block file. */ - private CodeSigner[] getSigners(SignerInfo infos[], PKCS7 block) + private CodeSigner[] getSigners(SignerInfo[] infos, PKCS7 block) throws IOException, NoSuchAlgorithmException, SignatureException, CertificateException { diff --git a/jdk/src/java.base/share/classes/sun/security/x509/AVA.java b/jdk/src/java.base/share/classes/sun/security/x509/AVA.java index b7b98d3da0e..1b7d297b233 100644 --- a/jdk/src/java.base/share/classes/sun/security/x509/AVA.java +++ b/jdk/src/java.base/share/classes/sun/security/x509/AVA.java @@ -967,7 +967,7 @@ public class AVA implements DerEncoder { previousWhite = false; - byte valueBytes[] = null; + byte[] valueBytes = null; try { valueBytes = Character.toString(c).getBytes("UTF8"); } catch (IOException ie) { @@ -1051,7 +1051,7 @@ public class AVA implements DerEncoder { // using the hex format below. This will be used only // when the value is not a string type - byte data [] = value.toByteArray(); + byte[] data = value.toByteArray(); retval.append('#'); for (int i = 0; i < data.length; i++) { diff --git a/jdk/src/java.base/share/classes/sun/security/x509/AlgIdDSA.java b/jdk/src/java.base/share/classes/sun/security/x509/AlgIdDSA.java index c4d2f896b5d..2e08c0509e7 100644 --- a/jdk/src/java.base/share/classes/sun/security/x509/AlgIdDSA.java +++ b/jdk/src/java.base/share/classes/sun/security/x509/AlgIdDSA.java @@ -117,7 +117,7 @@ class AlgIdDSA extends AlgorithmId implements DSAParams * @param q the DSS/DSA parameter "Q" * @param g the DSS/DSA parameter "G" */ - public AlgIdDSA (byte p [], byte q [], byte g []) + public AlgIdDSA (byte[] p, byte[] q, byte[] g) throws IOException { this (new BigInteger (1, p), diff --git a/jdk/src/java.base/share/classes/sun/security/x509/AlgorithmId.java b/jdk/src/java.base/share/classes/sun/security/x509/AlgorithmId.java index 294888bfaf4..530dc167c00 100644 --- a/jdk/src/java.base/share/classes/sun/security/x509/AlgorithmId.java +++ b/jdk/src/java.base/share/classes/sun/security/x509/AlgorithmId.java @@ -648,12 +648,12 @@ public class AlgorithmId implements Serializable, DerEncoder { /* * COMMON PUBLIC KEY TYPES */ - private static final int DH_data[] = { 1, 2, 840, 113549, 1, 3, 1 }; - private static final int DH_PKIX_data[] = { 1, 2, 840, 10046, 2, 1 }; - private static final int DSA_OIW_data[] = { 1, 3, 14, 3, 2, 12 }; - private static final int DSA_PKIX_data[] = { 1, 2, 840, 10040, 4, 1 }; - private static final int RSA_data[] = { 2, 5, 8, 1, 1 }; - private static final int RSAEncryption_data[] = + private static final int[] DH_data = { 1, 2, 840, 113549, 1, 3, 1 }; + private static final int[] DH_PKIX_data = { 1, 2, 840, 10046, 2, 1 }; + private static final int[] DSA_OIW_data = { 1, 3, 14, 3, 2, 12 }; + private static final int[] DSA_PKIX_data = { 1, 2, 840, 10040, 4, 1 }; + private static final int[] RSA_data = { 2, 5, 8, 1, 1 }; + private static final int[] RSAEncryption_data = { 1, 2, 840, 113549, 1, 1, 1 }; public static final ObjectIdentifier DH_oid; @@ -674,27 +674,27 @@ public class AlgorithmId implements Serializable, DerEncoder { /* * COMMON SIGNATURE ALGORITHMS */ - private static final int md2WithRSAEncryption_data[] = + private static final int[] md2WithRSAEncryption_data = { 1, 2, 840, 113549, 1, 1, 2 }; - private static final int md5WithRSAEncryption_data[] = + private static final int[] md5WithRSAEncryption_data = { 1, 2, 840, 113549, 1, 1, 4 }; - private static final int sha1WithRSAEncryption_data[] = + private static final int[] sha1WithRSAEncryption_data = { 1, 2, 840, 113549, 1, 1, 5 }; - private static final int sha1WithRSAEncryption_OIW_data[] = + private static final int[] sha1WithRSAEncryption_OIW_data = { 1, 3, 14, 3, 2, 29 }; - private static final int sha224WithRSAEncryption_data[] = + private static final int[] sha224WithRSAEncryption_data = { 1, 2, 840, 113549, 1, 1, 14 }; - private static final int sha256WithRSAEncryption_data[] = + private static final int[] sha256WithRSAEncryption_data = { 1, 2, 840, 113549, 1, 1, 11 }; - private static final int sha384WithRSAEncryption_data[] = + private static final int[] sha384WithRSAEncryption_data = { 1, 2, 840, 113549, 1, 1, 12 }; - private static final int sha512WithRSAEncryption_data[] = + private static final int[] sha512WithRSAEncryption_data = { 1, 2, 840, 113549, 1, 1, 13 }; - private static final int shaWithDSA_OIW_data[] = + private static final int[] shaWithDSA_OIW_data = { 1, 3, 14, 3, 2, 13 }; - private static final int sha1WithDSA_OIW_data[] = + private static final int[] sha1WithDSA_OIW_data = { 1, 3, 14, 3, 2, 27 }; - private static final int dsaWithSHA1_PKIX_data[] = + private static final int[] dsaWithSHA1_PKIX_data = { 1, 2, 840, 10040, 4, 3 }; public static final ObjectIdentifier md2WithRSAEncryption_oid; diff --git a/jdk/src/java.base/share/classes/sun/security/x509/NetscapeCertTypeExtension.java b/jdk/src/java.base/share/classes/sun/security/x509/NetscapeCertTypeExtension.java index 735efddfc3a..ca4dc3c53c3 100644 --- a/jdk/src/java.base/share/classes/sun/security/x509/NetscapeCertTypeExtension.java +++ b/jdk/src/java.base/share/classes/sun/security/x509/NetscapeCertTypeExtension.java @@ -69,7 +69,7 @@ implements CertAttrSet { public static final String S_MIME_CA = "s_mime_ca"; public static final String OBJECT_SIGNING_CA = "object_signing_ca"; - private static final int CertType_data[] = { 2, 16, 840, 1, 113730, 1, 1 }; + private static final int[] CertType_data = { 2, 16, 840, 1, 113730, 1, 1 }; /** * Object identifier for the Netscape-Cert-Type extension. diff --git a/jdk/src/java.base/share/classes/sun/security/x509/OIDMap.java b/jdk/src/java.base/share/classes/sun/security/x509/OIDMap.java index c8f0da3a671..b6d1b25e51d 100644 --- a/jdk/src/java.base/share/classes/sun/security/x509/OIDMap.java +++ b/jdk/src/java.base/share/classes/sun/security/x509/OIDMap.java @@ -102,7 +102,7 @@ public class OIDMap { private static final String OCSPNOCHECK = ROOT + "." + OCSPNoCheckExtension.NAME; - private static final int NetscapeCertType_data[] = + private static final int[] NetscapeCertType_data = { 2, 16, 840, 1, 113730, 1, 1 }; /** Map ObjectIdentifier(oid) -> OIDInfo(info) */ diff --git a/jdk/src/java.base/share/classes/sun/security/x509/PKIXExtensions.java b/jdk/src/java.base/share/classes/sun/security/x509/PKIXExtensions.java index 3c7696327af..37ac3fbb963 100644 --- a/jdk/src/java.base/share/classes/sun/security/x509/PKIXExtensions.java +++ b/jdk/src/java.base/share/classes/sun/security/x509/PKIXExtensions.java @@ -49,32 +49,32 @@ import sun.security.util.*; */ public class PKIXExtensions { // The object identifiers - private static final int AuthorityKey_data [] = { 2, 5, 29, 35 }; - private static final int SubjectKey_data [] = { 2, 5, 29, 14 }; - private static final int KeyUsage_data [] = { 2, 5, 29, 15 }; - private static final int PrivateKeyUsage_data [] = { 2, 5, 29, 16 }; - private static final int CertificatePolicies_data [] = { 2, 5, 29, 32 }; - private static final int PolicyMappings_data [] = { 2, 5, 29, 33 }; - private static final int SubjectAlternativeName_data [] = { 2, 5, 29, 17 }; - private static final int IssuerAlternativeName_data [] = { 2, 5, 29, 18 }; - private static final int SubjectDirectoryAttributes_data [] = { 2, 5, 29, 9 }; - private static final int BasicConstraints_data [] = { 2, 5, 29, 19 }; - private static final int NameConstraints_data [] = { 2, 5, 29, 30 }; - private static final int PolicyConstraints_data [] = { 2, 5, 29, 36 }; - private static final int CRLDistributionPoints_data [] = { 2, 5, 29, 31 }; - private static final int CRLNumber_data [] = { 2, 5, 29, 20 }; - private static final int IssuingDistributionPoint_data [] = { 2, 5, 29, 28 }; - private static final int DeltaCRLIndicator_data [] = { 2, 5, 29, 27 }; - private static final int ReasonCode_data [] = { 2, 5, 29, 21 }; - private static final int HoldInstructionCode_data [] = { 2, 5, 29, 23 }; - private static final int InvalidityDate_data [] = { 2, 5, 29, 24 }; - private static final int ExtendedKeyUsage_data [] = { 2, 5, 29, 37 }; - private static final int InhibitAnyPolicy_data [] = { 2, 5, 29, 54 }; - private static final int CertificateIssuer_data [] = { 2, 5, 29, 29 }; - private static final int AuthInfoAccess_data [] = { 1, 3, 6, 1, 5, 5, 7, 1, 1}; - private static final int SubjectInfoAccess_data [] = { 1, 3, 6, 1, 5, 5, 7, 1, 11}; - private static final int FreshestCRL_data [] = { 2, 5, 29, 46 }; - private static final int OCSPNoCheck_data [] = { 1, 3, 6, 1, 5, 5, 7, + private static final int[] AuthorityKey_data = { 2, 5, 29, 35 }; + private static final int[] SubjectKey_data = { 2, 5, 29, 14 }; + private static final int[] KeyUsage_data = { 2, 5, 29, 15 }; + private static final int[] PrivateKeyUsage_data = { 2, 5, 29, 16 }; + private static final int[] CertificatePolicies_data = { 2, 5, 29, 32 }; + private static final int[] PolicyMappings_data = { 2, 5, 29, 33 }; + private static final int[] SubjectAlternativeName_data = { 2, 5, 29, 17 }; + private static final int[] IssuerAlternativeName_data = { 2, 5, 29, 18 }; + private static final int[] SubjectDirectoryAttributes_data = { 2, 5, 29, 9 }; + private static final int[] BasicConstraints_data = { 2, 5, 29, 19 }; + private static final int[] NameConstraints_data = { 2, 5, 29, 30 }; + private static final int[] PolicyConstraints_data = { 2, 5, 29, 36 }; + private static final int[] CRLDistributionPoints_data = { 2, 5, 29, 31 }; + private static final int[] CRLNumber_data = { 2, 5, 29, 20 }; + private static final int[] IssuingDistributionPoint_data = { 2, 5, 29, 28 }; + private static final int[] DeltaCRLIndicator_data = { 2, 5, 29, 27 }; + private static final int[] ReasonCode_data = { 2, 5, 29, 21 }; + private static final int[] HoldInstructionCode_data = { 2, 5, 29, 23 }; + private static final int[] InvalidityDate_data = { 2, 5, 29, 24 }; + private static final int[] ExtendedKeyUsage_data = { 2, 5, 29, 37 }; + private static final int[] InhibitAnyPolicy_data = { 2, 5, 29, 54 }; + private static final int[] CertificateIssuer_data = { 2, 5, 29, 29 }; + private static final int[] AuthInfoAccess_data = { 1, 3, 6, 1, 5, 5, 7, 1, 1}; + private static final int[] SubjectInfoAccess_data = { 1, 3, 6, 1, 5, 5, 7, 1, 11}; + private static final int[] FreshestCRL_data = { 2, 5, 29, 46 }; + private static final int[] OCSPNoCheck_data = { 1, 3, 6, 1, 5, 5, 7, 48, 1, 5}; /** diff --git a/jdk/src/java.base/share/classes/sun/security/x509/X500Name.java b/jdk/src/java.base/share/classes/sun/security/x509/X500Name.java index 79d64e84555..740b7fed538 100644 --- a/jdk/src/java.base/share/classes/sun/security/x509/X500Name.java +++ b/jdk/src/java.base/share/classes/sun/security/x509/X500Name.java @@ -1119,25 +1119,25 @@ public class X500Name implements GeneralNameInterface, Principal { * Includes all those specified in RFC 5280 as MUST or SHOULD * be recognized */ - private static final int commonName_data[] = { 2, 5, 4, 3 }; - private static final int SURNAME_DATA[] = { 2, 5, 4, 4 }; - private static final int SERIALNUMBER_DATA[] = { 2, 5, 4, 5 }; - private static final int countryName_data[] = { 2, 5, 4, 6 }; - private static final int localityName_data[] = { 2, 5, 4, 7 }; - private static final int stateName_data[] = { 2, 5, 4, 8 }; - private static final int streetAddress_data[] = { 2, 5, 4, 9 }; - private static final int orgName_data[] = { 2, 5, 4, 10 }; - private static final int orgUnitName_data[] = { 2, 5, 4, 11 }; - private static final int title_data[] = { 2, 5, 4, 12 }; - private static final int GIVENNAME_DATA[] = { 2, 5, 4, 42 }; - private static final int INITIALS_DATA[] = { 2, 5, 4, 43 }; - private static final int GENERATIONQUALIFIER_DATA[] = { 2, 5, 4, 44 }; - private static final int DNQUALIFIER_DATA[] = { 2, 5, 4, 46 }; + private static final int[] commonName_data = { 2, 5, 4, 3 }; + private static final int[] SURNAME_DATA = { 2, 5, 4, 4 }; + private static final int[] SERIALNUMBER_DATA = { 2, 5, 4, 5 }; + private static final int[] countryName_data = { 2, 5, 4, 6 }; + private static final int[] localityName_data = { 2, 5, 4, 7 }; + private static final int[] stateName_data = { 2, 5, 4, 8 }; + private static final int[] streetAddress_data = { 2, 5, 4, 9 }; + private static final int[] orgName_data = { 2, 5, 4, 10 }; + private static final int[] orgUnitName_data = { 2, 5, 4, 11 }; + private static final int[] title_data = { 2, 5, 4, 12 }; + private static final int[] GIVENNAME_DATA = { 2, 5, 4, 42 }; + private static final int[] INITIALS_DATA = { 2, 5, 4, 43 }; + private static final int[] GENERATIONQUALIFIER_DATA = { 2, 5, 4, 44 }; + private static final int[] DNQUALIFIER_DATA = { 2, 5, 4, 46 }; - private static final int ipAddress_data[] = { 1, 3, 6, 1, 4, 1, 42, 2, 11, 2, 1 }; - private static final int DOMAIN_COMPONENT_DATA[] = + private static final int[] ipAddress_data = { 1, 3, 6, 1, 4, 1, 42, 2, 11, 2, 1 }; + private static final int[] DOMAIN_COMPONENT_DATA = { 0, 9, 2342, 19200300, 100, 1, 25 }; - private static final int userid_data[] = + private static final int[] userid_data = { 0, 9, 2342, 19200300, 100, 1, 1 }; diff --git a/jdk/src/java.base/share/classes/sun/security/x509/X509CRLImpl.java b/jdk/src/java.base/share/classes/sun/security/x509/X509CRLImpl.java index ff62de87e63..d248121fd97 100644 --- a/jdk/src/java.base/share/classes/sun/security/x509/X509CRLImpl.java +++ b/jdk/src/java.base/share/classes/sun/security/x509/X509CRLImpl.java @@ -1086,7 +1086,7 @@ public class X509CRLImpl extends X509CRL implements DerEncoder { throw new CRLException("Invalid DER-encoded CRL data"); signedCRL = val.toByteArray(); - DerValue seq[] = new DerValue[3]; + DerValue[] seq = new DerValue[3]; seq[0] = val.data.getDerValue(); seq[1] = val.data.getDerValue(); diff --git a/jdk/src/java.security.jgss/share/classes/javax/security/auth/kerberos/ServicePermission.java b/jdk/src/java.security.jgss/share/classes/javax/security/auth/kerberos/ServicePermission.java index 648ab959d5f..0ae18e980e5 100644 --- a/jdk/src/java.security.jgss/share/classes/javax/security/auth/kerberos/ServicePermission.java +++ b/jdk/src/java.security.jgss/share/classes/javax/security/auth/kerberos/ServicePermission.java @@ -427,7 +427,7 @@ public final class ServicePermission extends Permission /* - public static void main(String args[]) throws Exception { + public static void main(String[] args) throws Exception { ServicePermission this_ = new ServicePermission(args[0], "accept"); ServicePermission that_ = diff --git a/jdk/src/java.security.jgss/share/classes/sun/security/jgss/GSSCredentialImpl.java b/jdk/src/java.security.jgss/share/classes/sun/security/jgss/GSSCredentialImpl.java index 617505f8320..fff2c39f619 100644 --- a/jdk/src/java.security.jgss/share/classes/sun/security/jgss/GSSCredentialImpl.java +++ b/jdk/src/java.security.jgss/share/classes/sun/security/jgss/GSSCredentialImpl.java @@ -75,7 +75,7 @@ public class GSSCredentialImpl implements GSSCredential { } GSSCredentialImpl(GSSManagerImpl gssManager, GSSName name, - int lifetime, Oid mechs[], int usage) + int lifetime, Oid[] mechs, int usage) throws GSSException { init(gssManager); boolean defaultList = false; diff --git a/jdk/src/java.security.jgss/share/classes/sun/security/jgss/GSSManagerImpl.java b/jdk/src/java.security.jgss/share/classes/sun/security/jgss/GSSManagerImpl.java index 9d27b53822b..487d5e31080 100644 --- a/jdk/src/java.security.jgss/share/classes/sun/security/jgss/GSSManagerImpl.java +++ b/jdk/src/java.security.jgss/share/classes/sun/security/jgss/GSSManagerImpl.java @@ -128,7 +128,7 @@ public class GSSManagerImpl extends GSSManager { return new GSSNameImpl(this, nameStr, nameType); } - public GSSName createName(byte name[], Oid nameType) + public GSSName createName(byte[] name, Oid nameType) throws GSSException { return new GSSNameImpl(this, name, nameType); } @@ -138,7 +138,7 @@ public class GSSManagerImpl extends GSSManager { return new GSSNameImpl(this, nameStr, nameType, mech); } - public GSSName createName(byte name[], Oid nameType, Oid mech) + public GSSName createName(byte[] name, Oid nameType, Oid mech) throws GSSException { return new GSSNameImpl(this, name, nameType, mech); } @@ -155,7 +155,7 @@ public class GSSManagerImpl extends GSSManager { } public GSSCredential createCredential(GSSName aName, - int lifetime, Oid mechs[], int usage) + int lifetime, Oid[] mechs, int usage) throws GSSException { return wrap(new GSSCredentialImpl(this, aName, lifetime, mechs, usage)); } diff --git a/jdk/src/java.security.jgss/share/classes/sun/security/jgss/krb5/Krb5Context.java b/jdk/src/java.security.jgss/share/classes/sun/security/jgss/krb5/Krb5Context.java index 4b7b0eeb367..b6897391dee 100644 --- a/jdk/src/java.security.jgss/share/classes/sun/security/jgss/krb5/Krb5Context.java +++ b/jdk/src/java.security.jgss/share/classes/sun/security/jgss/krb5/Krb5Context.java @@ -159,7 +159,7 @@ class Krb5Context implements GSSContextSpi { /** * Constructor for Krb5Context to import a previously exported context. */ - public Krb5Context(GSSCaller caller, byte [] interProcessToken) + public Krb5Context(GSSCaller caller, byte[] interProcessToken) throws GSSException { throw new GSSException(GSSException.UNAVAILABLE, -1, "GSS Import Context not available"); @@ -905,7 +905,7 @@ class Krb5Context implements GSSContextSpi { * and verifyMIC care about the remote sequence number (peerSeqNumber). */ - public final byte[] wrap(byte inBuf[], int offset, int len, + public final byte[] wrap(byte[] inBuf, int offset, int len, MessageProp msgProp) throws GSSException { if (DEBUG) { System.out.println("Krb5Context.wrap: data=[" @@ -943,7 +943,7 @@ class Krb5Context implements GSSContextSpi { } } - public final int wrap(byte inBuf[], int inOffset, int len, + public final int wrap(byte[] inBuf, int inOffset, int len, byte[] outBuf, int outOffset, MessageProp msgProp) throws GSSException { @@ -977,7 +977,7 @@ class Krb5Context implements GSSContextSpi { } } - public final void wrap(byte inBuf[], int offset, int len, + public final void wrap(byte[] inBuf, int offset, int len, OutputStream os, MessageProp msgProp) throws GSSException { @@ -1032,7 +1032,7 @@ class Krb5Context implements GSSContextSpi { wrap(data, 0, data.length, os, msgProp); } - public final byte[] unwrap(byte inBuf[], int offset, int len, + public final byte[] unwrap(byte[] inBuf, int offset, int len, MessageProp msgProp) throws GSSException { @@ -1069,7 +1069,7 @@ class Krb5Context implements GSSContextSpi { return data; } - public final int unwrap(byte inBuf[], int inOffset, int len, + public final int unwrap(byte[] inBuf, int inOffset, int len, byte[] outBuf, int outOffset, MessageProp msgProp) throws GSSException { @@ -1141,7 +1141,7 @@ class Krb5Context implements GSSContextSpi { } } - public final byte[] getMIC(byte []inMsg, int offset, int len, + public final byte[] getMIC(byte[] inMsg, int offset, int len, MessageProp msgProp) throws GSSException { @@ -1166,7 +1166,7 @@ class Krb5Context implements GSSContextSpi { } } - private int getMIC(byte []inMsg, int offset, int len, + private int getMIC(byte[] inMsg, int offset, int len, byte[] outBuf, int outOffset, MessageProp msgProp) throws GSSException { @@ -1236,7 +1236,7 @@ class Krb5Context implements GSSContextSpi { getMIC(data, 0, data.length, os, msgProp); } - public final void verifyMIC(byte []inTok, int tokOffset, int tokLen, + public final void verifyMIC(byte[] inTok, int tokOffset, int tokLen, byte[] inMsg, int msgOffset, int msgLen, MessageProp msgProp) throws GSSException { @@ -1293,7 +1293,7 @@ class Krb5Context implements GSSContextSpi { * @param os the output token will be written to this stream * @exception GSSException */ - public final byte [] export() throws GSSException { + public final byte[] export() throws GSSException { throw new GSSException(GSSException.UNAVAILABLE, -1, "GSS Export Context not available"); } diff --git a/jdk/src/java.security.jgss/share/classes/sun/security/jgss/spi/GSSContextSpi.java b/jdk/src/java.security.jgss/share/classes/sun/security/jgss/spi/GSSContextSpi.java index 500557b4a8e..057dcf2ccf4 100644 --- a/jdk/src/java.security.jgss/share/classes/sun/security/jgss/spi/GSSContextSpi.java +++ b/jdk/src/java.security.jgss/share/classes/sun/security/jgss/spi/GSSContextSpi.java @@ -265,7 +265,7 @@ public interface GSSContextSpi { /** * For apps that want simplicity and don't care about buffer copies. */ - public byte[] wrap(byte inBuf[], int offset, int len, + public byte[] wrap(byte[] inBuf, int offset, int len, MessageProp msgProp) throws GSSException; /** @@ -275,7 +275,7 @@ public interface GSSContextSpi { * * NOTE: This method is not defined in public class org.ietf.jgss.GSSContext * - public int wrap(byte inBuf[], int inOffset, int len, + public int wrap(byte[] inBuf, int inOffset, int len, byte[] outBuf, int outOffset, MessageProp msgProp) throws GSSException; @@ -292,7 +292,7 @@ public interface GSSContextSpi { * * NOTE: This method is not defined in public class org.ietf.jgss.GSSContext * - public void wrap(byte inBuf[], int offset, int len, + public void wrap(byte[] inBuf, int offset, int len, OutputStream os, MessageProp msgProp) throws GSSException; */ @@ -314,7 +314,7 @@ public interface GSSContextSpi { /** * For apps that want simplicity and don't care about buffer copies. */ - public byte[] unwrap(byte inBuf[], int offset, int len, + public byte[] unwrap(byte[] inBuf, int offset, int len, MessageProp msgProp) throws GSSException; /** @@ -324,7 +324,7 @@ public interface GSSContextSpi { * * NOTE: This method is not defined in public class org.ietf.jgss.GSSContext * - public int unwrap(byte inBuf[], int inOffset, int len, + public int unwrap(byte[] inBuf, int inOffset, int len, byte[] outBuf, int outOffset, MessageProp msgProp) throws GSSException; @@ -356,7 +356,7 @@ public interface GSSContextSpi { MessageProp msgProp) throws GSSException; - public byte[] getMIC(byte []inMsg, int offset, int len, + public byte[] getMIC(byte[] inMsg, int offset, int len, MessageProp msgProp) throws GSSException; /** @@ -372,7 +372,7 @@ public interface GSSContextSpi { public void verifyMIC(InputStream is, InputStream msgStr, MessageProp mProp) throws GSSException; - public void verifyMIC(byte []inTok, int tokOffset, int tokLen, + public void verifyMIC(byte[] inTok, int tokOffset, int tokLen, byte[] inMsg, int msgOffset, int msgLen, MessageProp msgProp) throws GSSException; diff --git a/jdk/src/java.security.jgss/share/classes/sun/security/jgss/wrapper/NativeGSSContext.java b/jdk/src/java.security.jgss/share/classes/sun/security/jgss/wrapper/NativeGSSContext.java index 0e0f38d177b..271fcfb896b 100644 --- a/jdk/src/java.security.jgss/share/classes/sun/security/jgss/wrapper/NativeGSSContext.java +++ b/jdk/src/java.security.jgss/share/classes/sun/security/jgss/wrapper/NativeGSSContext.java @@ -372,7 +372,7 @@ class NativeGSSContext implements GSSContextSpi { } return cStub.wrap(pContext, data, msgProp); } - public void wrap(byte inBuf[], int offset, int len, + public void wrap(byte[] inBuf, int offset, int len, OutputStream os, MessageProp msgProp) throws GSSException { try { diff --git a/jdk/src/java.security.jgss/share/classes/sun/security/jgss/wrapper/SunNativeProvider.java b/jdk/src/java.security.jgss/share/classes/sun/security/jgss/wrapper/SunNativeProvider.java index 94ca2c669bf..f7b84570e8c 100644 --- a/jdk/src/java.security.jgss/share/classes/sun/security/jgss/wrapper/SunNativeProvider.java +++ b/jdk/src/java.security.jgss/share/classes/sun/security/jgss/wrapper/SunNativeProvider.java @@ -78,7 +78,7 @@ public final class SunNativeProvider extends Provider { if (DEBUG) err.printStackTrace(); return null; } - String gssLibs[] = new String[0]; + String[] gssLibs = new String[0]; String defaultLib = System.getProperty(LIB_PROP); if (defaultLib == null || defaultLib.trim().equals("")) { String osname = System.getProperty("os.name"); diff --git a/jdk/src/java.security.jgss/share/classes/sun/security/krb5/PrincipalName.java b/jdk/src/java.security.jgss/share/classes/sun/security/krb5/PrincipalName.java index f66a2ec2c75..8cd833f0966 100644 --- a/jdk/src/java.security.jgss/share/classes/sun/security/krb5/PrincipalName.java +++ b/jdk/src/java.security.jgss/share/classes/sun/security/krb5/PrincipalName.java @@ -568,7 +568,7 @@ public class PrincipalName implements Cloneable { temp.putInteger(bint); bytes.write(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte)0x00), temp); temp = new DerOutputStream(); - DerValue der[] = new DerValue[nameStrings.length]; + DerValue[] der = new DerValue[nameStrings.length]; for (int i = 0; i < nameStrings.length; i++) { der[i] = new KerberosString(nameStrings[i]).toDerValue(); } diff --git a/jdk/src/java.security.jgss/share/classes/sun/security/krb5/internal/Authenticator.java b/jdk/src/java.security.jgss/share/classes/sun/security/krb5/internal/Authenticator.java index b3144b92051..5eeccd6dab2 100644 --- a/jdk/src/java.security.jgss/share/classes/sun/security/krb5/internal/Authenticator.java +++ b/jdk/src/java.security.jgss/share/classes/sun/security/krb5/internal/Authenticator.java @@ -198,7 +198,7 @@ public class Authenticator { if (authorizationData != null) { v.addElement(new DerValue(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte) 0x08), authorizationData.asn1Encode())); } - DerValue der[] = new DerValue[v.size()]; + DerValue[] der = new DerValue[v.size()]; v.copyInto(der); temp = new DerOutputStream(); temp.putSequence(der); diff --git a/jdk/src/java.security.jgss/share/classes/sun/security/krb5/internal/AuthorizationData.java b/jdk/src/java.security.jgss/share/classes/sun/security/krb5/internal/AuthorizationData.java index 9a9de81932f..204c8b8e354 100644 --- a/jdk/src/java.security.jgss/share/classes/sun/security/krb5/internal/AuthorizationData.java +++ b/jdk/src/java.security.jgss/share/classes/sun/security/krb5/internal/AuthorizationData.java @@ -120,7 +120,7 @@ public class AuthorizationData implements Cloneable { */ public byte[] asn1Encode() throws Asn1Exception, IOException { DerOutputStream bytes = new DerOutputStream(); - DerValue der[] = new DerValue[entry.length]; + DerValue[] der = new DerValue[entry.length]; for (int i = 0; i < entry.length; i++) { der[i] = new DerValue(entry[i].asn1Encode()); } diff --git a/jdk/src/java.security.jgss/share/classes/sun/security/krb5/internal/EncAPRepPart.java b/jdk/src/java.security.jgss/share/classes/sun/security/krb5/internal/EncAPRepPart.java index b2158073652..2ab92b85ada 100644 --- a/jdk/src/java.security.jgss/share/classes/sun/security/krb5/internal/EncAPRepPart.java +++ b/jdk/src/java.security.jgss/share/classes/sun/security/krb5/internal/EncAPRepPart.java @@ -151,7 +151,7 @@ public class EncAPRepPart { v.addElement(new DerValue(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte) 0x03), temp.toByteArray())); } - DerValue der[] = new DerValue[v.size()]; + DerValue[] der = new DerValue[v.size()]; v.copyInto(der); temp = new DerOutputStream(); temp.putSequence(der); diff --git a/jdk/src/java.security.jgss/share/classes/sun/security/krb5/internal/EncKrbCredPart.java b/jdk/src/java.security.jgss/share/classes/sun/security/krb5/internal/EncKrbCredPart.java index 0dececef09e..a9fd2bdd1d3 100644 --- a/jdk/src/java.security.jgss/share/classes/sun/security/krb5/internal/EncKrbCredPart.java +++ b/jdk/src/java.security.jgss/share/classes/sun/security/krb5/internal/EncKrbCredPart.java @@ -129,7 +129,7 @@ public class EncKrbCredPart { subDer = der.getData().getDerValue(); if ((subDer.getTag() & (byte) 0x1F) == (byte) 0x00) { - DerValue derValues[] = subDer.getData().getSequence(1); + DerValue[] derValues = subDer.getData().getSequence(1); ticketInfo = new KrbCredInfo[derValues.length]; for (int i = 0; i < derValues.length; i++) { ticketInfo[i] = new KrbCredInfo(derValues[i]); diff --git a/jdk/src/java.security.jgss/share/classes/sun/security/krb5/internal/HostAddresses.java b/jdk/src/java.security.jgss/share/classes/sun/security/krb5/internal/HostAddresses.java index 04eeb5de994..da80d8c0e00 100644 --- a/jdk/src/java.security.jgss/share/classes/sun/security/krb5/internal/HostAddresses.java +++ b/jdk/src/java.security.jgss/share/classes/sun/security/krb5/internal/HostAddresses.java @@ -98,8 +98,8 @@ public class HostAddresses implements Cloneable { throw new KrbException(Krb5.KRB_ERR_GENERIC, "Bad name"); String host = components[1]; - InetAddress addr[] = InetAddress.getAllByName(host); - HostAddress hAddrs[] = new HostAddress[addr.length]; + InetAddress[] addr = InetAddress.getAllByName(host); + HostAddress[] hAddrs = new HostAddress[addr.length]; for (int i = 0; i < addr.length; i++) { hAddrs[i] = new HostAddress(addr[i]); diff --git a/jdk/src/java.security.jgss/share/classes/sun/security/krb5/internal/KDCReqBody.java b/jdk/src/java.security.jgss/share/classes/sun/security/krb5/internal/KDCReqBody.java index 83178b6cc4c..85411698f02 100644 --- a/jdk/src/java.security.jgss/share/classes/sun/security/krb5/internal/KDCReqBody.java +++ b/jdk/src/java.security.jgss/share/classes/sun/security/krb5/internal/KDCReqBody.java @@ -269,7 +269,7 @@ public class KDCReqBody { ticketsTemp.write(DerValue.tag_SequenceOf, temp); v.addElement(new DerValue(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte)0x0B), ticketsTemp.toByteArray())); } - DerValue der[] = new DerValue[v.size()]; + DerValue[] der = new DerValue[v.size()]; v.copyInto(der); temp = new DerOutputStream(); temp.putSequence(der); diff --git a/jdk/src/java.security.jgss/share/classes/sun/security/krb5/internal/KrbCredInfo.java b/jdk/src/java.security.jgss/share/classes/sun/security/krb5/internal/KrbCredInfo.java index 18fa7412fac..2b771e0616e 100644 --- a/jdk/src/java.security.jgss/share/classes/sun/security/krb5/internal/KrbCredInfo.java +++ b/jdk/src/java.security.jgss/share/classes/sun/security/krb5/internal/KrbCredInfo.java @@ -172,7 +172,7 @@ public class KrbCredInfo { } if (caddr != null) v.addElement(new DerValue(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte)0x0A), caddr.asn1Encode())); - DerValue der[] = new DerValue[v.size()]; + DerValue[] der = new DerValue[v.size()]; v.copyInto(der); DerOutputStream out = new DerOutputStream(); out.putSequence(der); diff --git a/jdk/src/java.security.jgss/share/classes/sun/security/krb5/internal/NetClient.java b/jdk/src/java.security.jgss/share/classes/sun/security/krb5/internal/NetClient.java index 62243560ca1..f27abd2bb3e 100644 --- a/jdk/src/java.security.jgss/share/classes/sun/security/krb5/internal/NetClient.java +++ b/jdk/src/java.security.jgss/share/classes/sun/security/krb5/internal/NetClient.java @@ -200,7 +200,7 @@ class UDPClient extends NetClient { @Override public byte[] receive() throws IOException { - byte ibuf[] = new byte[bufSize]; + byte[] ibuf = new byte[bufSize]; dgPacketIn = new DatagramPacket(ibuf, ibuf.length); try { dgSocket.receive(dgPacketIn); diff --git a/jdk/src/java.security.jgss/share/classes/sun/security/krb5/internal/Ticket.java b/jdk/src/java.security.jgss/share/classes/sun/security/krb5/internal/Ticket.java index 0f1c3d9af15..17aa05940fe 100644 --- a/jdk/src/java.security.jgss/share/classes/sun/security/krb5/internal/Ticket.java +++ b/jdk/src/java.security.jgss/share/classes/sun/security/krb5/internal/Ticket.java @@ -135,7 +135,7 @@ public class Ticket implements Cloneable { public byte[] asn1Encode() throws Asn1Exception, IOException { DerOutputStream bytes = new DerOutputStream(); DerOutputStream temp = new DerOutputStream(); - DerValue der[] = new DerValue[4]; + DerValue[] der = new DerValue[4]; temp.putInteger(BigInteger.valueOf(tkt_vno)); bytes.write(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte)0x00), temp); bytes.write(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte)0x01), sname.getRealm().asn1Encode()); diff --git a/jdk/src/java.security.jgss/share/classes/sun/security/krb5/internal/ccache/CCacheInputStream.java b/jdk/src/java.security.jgss/share/classes/sun/security/krb5/internal/ccache/CCacheInputStream.java index d6f2da7134f..09e02b78df6 100644 --- a/jdk/src/java.security.jgss/share/classes/sun/security/krb5/internal/ccache/CCacheInputStream.java +++ b/jdk/src/java.security.jgss/share/classes/sun/security/krb5/internal/ccache/CCacheInputStream.java @@ -357,7 +357,7 @@ public class CCacheInputStream extends KrbDataInputStream implements FileCCacheC if (DEBUG) { System.out.println(">>>DEBUG key type: " + key.getEType()); } - long times[] = readTimes(); + long[] times = readTimes(); KerberosTime authtime = new KerberosTime(times[0]); KerberosTime starttime = (times[1]==0) ? null : new KerberosTime(times[1]); @@ -374,9 +374,9 @@ public class CCacheInputStream extends KrbDataInputStream implements FileCCacheC ((renewTill==null)?"null":renewTill.toDate().toString())); } boolean skey = readskey(); - boolean flags[] = readFlags(); + boolean[] flags = readFlags(); TicketFlags tFlags = new TicketFlags(flags); - HostAddress addr[] = readAddr(); + HostAddress[] addr = readAddr(); HostAddresses addrs = null; if (addr != null) { addrs = new HostAddresses(addr); diff --git a/jdk/src/java.security.jgss/share/classes/sun/security/krb5/internal/crypto/crc32.java b/jdk/src/java.security.jgss/share/classes/sun/security/krb5/internal/crypto/crc32.java index 7639ba48f37..fc165a64e64 100644 --- a/jdk/src/java.security.jgss/share/classes/sun/security/krb5/internal/crypto/crc32.java +++ b/jdk/src/java.security.jgss/share/classes/sun/security/krb5/internal/crypto/crc32.java @@ -112,7 +112,7 @@ public final class crc32 extends MessageDigestSpi implements Cloneable { * This version is more efficient than the byte-at-a-time version; * it avoids data copies and reduces per-byte call overhead. */ - protected synchronized void engineUpdate(byte input[], int offset, + protected synchronized void engineUpdate(byte[] input, int offset, int len) { processData(input, offset, len); } diff --git a/jdk/src/java.security.jgss/share/classes/sun/security/krb5/internal/ssl/KerberosPreMasterSecret.java b/jdk/src/java.security.jgss/share/classes/sun/security/krb5/internal/ssl/KerberosPreMasterSecret.java index c1e89653a91..962d7490f06 100644 --- a/jdk/src/java.security.jgss/share/classes/sun/security/krb5/internal/ssl/KerberosPreMasterSecret.java +++ b/jdk/src/java.security.jgss/share/classes/sun/security/krb5/internal/ssl/KerberosPreMasterSecret.java @@ -53,8 +53,8 @@ import sun.security.ssl.ProtocolVersion; final class KerberosPreMasterSecret { private ProtocolVersion protocolVersion; // preMaster [0,1] - private byte preMaster[]; // 48 bytes - private byte encrypted[]; + private byte[] preMaster; // 48 bytes + private byte[] encrypted; /** * Constructor used by client to generate premaster secret. diff --git a/jdk/src/java.security.sasl/share/classes/com/sun/security/sasl/ClientFactoryImpl.java b/jdk/src/java.security.sasl/share/classes/com/sun/security/sasl/ClientFactoryImpl.java index e094518b499..0d79f50d231 100644 --- a/jdk/src/java.security.sasl/share/classes/com/sun/security/sasl/ClientFactoryImpl.java +++ b/jdk/src/java.security.sasl/share/classes/com/sun/security/sasl/ClientFactoryImpl.java @@ -47,13 +47,13 @@ import javax.security.auth.callback.UnsupportedCallbackException; * @author Rosanna Lee */ final public class ClientFactoryImpl implements SaslClientFactory { - private static final String myMechs[] = { + private static final String[] myMechs = { "EXTERNAL", "CRAM-MD5", "PLAIN", }; - private static final int mechPolicies[] = { + private static final int[] mechPolicies = { // %%% RL: Policies should actually depend on the external channel PolicyUtils.NOPLAINTEXT|PolicyUtils.NOACTIVE|PolicyUtils.NODICTIONARY, PolicyUtils.NOPLAINTEXT|PolicyUtils.NOANONYMOUS, // CRAM-MD5 diff --git a/jdk/src/java.security.sasl/share/classes/com/sun/security/sasl/CramMD5Server.java b/jdk/src/java.security.sasl/share/classes/com/sun/security/sasl/CramMD5Server.java index 94512f806dd..1d06b3960ab 100644 --- a/jdk/src/java.security.sasl/share/classes/com/sun/security/sasl/CramMD5Server.java +++ b/jdk/src/java.security.sasl/share/classes/com/sun/security/sasl/CramMD5Server.java @@ -165,7 +165,7 @@ final class CramMD5Server extends CramMD5Base implements SaslServer { PasswordCallback pcb = new PasswordCallback("CRAM-MD5 password: ", false); cbh.handle(new Callback[]{ncb,pcb}); - char pwChars[] = pcb.getPassword(); + char[] pwChars = pcb.getPassword(); if (pwChars == null || pwChars.length == 0) { // user has no password; OK to disclose to server aborted = true; @@ -190,7 +190,7 @@ final class CramMD5Server extends CramMD5Base implements SaslServer { clearPassword(); // Check whether digest is as expected - byte [] expectedDigest = digest.getBytes("UTF8"); + byte[] expectedDigest = digest.getBytes("UTF8"); int digestLen = responseData.length - ulen - 1; if (expectedDigest.length != digestLen) { aborted = true; diff --git a/jdk/src/java.security.sasl/share/classes/com/sun/security/sasl/ServerFactoryImpl.java b/jdk/src/java.security.sasl/share/classes/com/sun/security/sasl/ServerFactoryImpl.java index 2ea051878e3..565cfa85d65 100644 --- a/jdk/src/java.security.sasl/share/classes/com/sun/security/sasl/ServerFactoryImpl.java +++ b/jdk/src/java.security.sasl/share/classes/com/sun/security/sasl/ServerFactoryImpl.java @@ -41,11 +41,11 @@ import javax.security.auth.callback.CallbackHandler; * @author Rosanna Lee */ final public class ServerFactoryImpl implements SaslServerFactory { - private static final String myMechs[] = { + private static final String[] myMechs = { "CRAM-MD5", // }; - private static final int mechPolicies[] = { + private static final int[] mechPolicies = { PolicyUtils.NOPLAINTEXT|PolicyUtils.NOANONYMOUS, // CRAM-MD5 }; diff --git a/jdk/src/java.security.sasl/share/classes/com/sun/security/sasl/digest/DigestMD5Base.java b/jdk/src/java.security.sasl/share/classes/com/sun/security/sasl/digest/DigestMD5Base.java index 138f21509ae..4fa9fd1a857 100644 --- a/jdk/src/java.security.sasl/share/classes/com/sun/security/sasl/digest/DigestMD5Base.java +++ b/jdk/src/java.security.sasl/share/classes/com/sun/security/sasl/digest/DigestMD5Base.java @@ -272,7 +272,7 @@ abstract class DigestMD5Base extends AbstractSaslImpl { */ /** This array maps the characters to their 6 bit values */ - private final static char pem_array[] = { + private final static char[] pem_array = { // 0 1 2 3 4 5 6 7 'A','B','C','D','E','F','G','H', // 0 'I','J','K','L','M','N','O','P', // 1 @@ -1068,7 +1068,7 @@ abstract class DigestMD5Base extends AbstractSaslImpl { byte[] hMAC_MD5 = m.doFinal(); /* First 10 bytes of HMAC_MD5 digest */ - byte macBuffer[] = new byte[10]; + byte[] macBuffer = new byte[10]; System.arraycopy(hMAC_MD5, 0, macBuffer, 0, 10); return macBuffer; diff --git a/jdk/src/java.security.sasl/share/classes/com/sun/security/sasl/digest/FactoryImpl.java b/jdk/src/java.security.sasl/share/classes/com/sun/security/sasl/digest/FactoryImpl.java index 39ec03d7593..fa0e67bee59 100644 --- a/jdk/src/java.security.sasl/share/classes/com/sun/security/sasl/digest/FactoryImpl.java +++ b/jdk/src/java.security.sasl/share/classes/com/sun/security/sasl/digest/FactoryImpl.java @@ -44,9 +44,9 @@ import com.sun.security.sasl.util.PolicyUtils; public final class FactoryImpl implements SaslClientFactory, SaslServerFactory{ - private static final String myMechs[] = { "DIGEST-MD5" }; + private static final String[] myMechs = { "DIGEST-MD5" }; private static final int DIGEST_MD5 = 0; - private static final int mechPolicies[] = { + private static final int[] mechPolicies = { PolicyUtils.NOPLAINTEXT|PolicyUtils.NOANONYMOUS}; /** diff --git a/jdk/src/java.security.sasl/share/classes/com/sun/security/sasl/ntlm/FactoryImpl.java b/jdk/src/java.security.sasl/share/classes/com/sun/security/sasl/ntlm/FactoryImpl.java index e7a3097ca27..4a9b730a9ad 100644 --- a/jdk/src/java.security.sasl/share/classes/com/sun/security/sasl/ntlm/FactoryImpl.java +++ b/jdk/src/java.security.sasl/share/classes/com/sun/security/sasl/ntlm/FactoryImpl.java @@ -43,8 +43,8 @@ import com.sun.security.sasl.util.PolicyUtils; public final class FactoryImpl implements SaslClientFactory, SaslServerFactory{ - private static final String myMechs[] = { "NTLM" }; - private static final int mechPolicies[] = { + private static final String[] myMechs = { "NTLM" }; + private static final int[] mechPolicies = { PolicyUtils.NOPLAINTEXT|PolicyUtils.NOANONYMOUS }; diff --git a/jdk/src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/KeyStore.java b/jdk/src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/KeyStore.java index 75ed7b1dcac..7c080d14a4a 100644 --- a/jdk/src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/KeyStore.java +++ b/jdk/src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/KeyStore.java @@ -66,7 +66,7 @@ abstract class KeyStore extends KeyStoreSpi { class KeyEntry { private Key privateKey; - private X509Certificate certChain[]; + private X509Certificate[] certChain; private String alias; KeyEntry(Key key, X509Certificate[] chain) { diff --git a/jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/P11Cipher.java b/jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/P11Cipher.java index 6fe59f8da8d..690d865167e 100644 --- a/jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/P11Cipher.java +++ b/jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/P11Cipher.java @@ -175,7 +175,7 @@ final class P11Cipher extends CipherSpi { this.algorithm = algorithm; this.mechanism = mechanism; - String algoParts[] = algorithm.split("/"); + String[] algoParts = algorithm.split("/"); if (algoParts[0].startsWith("AES")) { blockSize = 16; diff --git a/jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/P11KeyStore.java b/jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/P11KeyStore.java index aac76f3e6ab..1fba98270e9 100644 --- a/jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/P11KeyStore.java +++ b/jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/P11KeyStore.java @@ -164,7 +164,7 @@ final class P11KeyStore extends KeyStoreSpi { private X509Certificate cert = null; // chain - private X509Certificate chain[] = null; + private X509Certificate[] chain = null; // true if CKA_ID for private key and cert match up private boolean matched = false; diff --git a/jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/wrapper/CK_AES_CTR_PARAMS.java b/jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/wrapper/CK_AES_CTR_PARAMS.java index 4f9cf3630aa..dff62e1f823 100644 --- a/jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/wrapper/CK_AES_CTR_PARAMS.java +++ b/jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/wrapper/CK_AES_CTR_PARAMS.java @@ -42,7 +42,7 @@ package sun.security.pkcs11.wrapper; public class CK_AES_CTR_PARAMS { private final long ulCounterBits; - private final byte cb[]; + private final byte[] cb; public CK_AES_CTR_PARAMS(byte[] cb) { ulCounterBits = 128; diff --git a/jdk/src/jdk.crypto.ucrypto/solaris/classes/com/oracle/security/ucrypto/UcryptoException.java b/jdk/src/jdk.crypto.ucrypto/solaris/classes/com/oracle/security/ucrypto/UcryptoException.java index 1e09a48d5ee..8ef10f8be67 100644 --- a/jdk/src/jdk.crypto.ucrypto/solaris/classes/com/oracle/security/ucrypto/UcryptoException.java +++ b/jdk/src/jdk.crypto.ucrypto/solaris/classes/com/oracle/security/ucrypto/UcryptoException.java @@ -40,7 +40,7 @@ public final class UcryptoException extends ProviderException { private static final long serialVersionUID = -933864511110035746L; // NOTE: check /usr/include/sys/crypto/common.h for updates - private static final String ERROR_MSG[] = { + private static final String[] ERROR_MSG = { "CRYPTO_SUCCESS", "CRYPTO_CANCEL", "CRYPTO_HOST_MEMORY", diff --git a/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/module/Crypt.java b/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/module/Crypt.java index a79b40372ee..4dce8bb5eca 100644 --- a/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/module/Crypt.java +++ b/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/module/Crypt.java @@ -377,7 +377,7 @@ class Crypt { * */ - public static void main(String arg[]) { + public static void main(String[] arg) { if (arg.length!=2) { System.err.println("usage: Crypt password salt"); @@ -386,7 +386,7 @@ class Crypt { Crypt c = new Crypt(); try { - byte result[] = c.crypt + byte[] result = c.crypt (arg[0].getBytes("ISO-8859-1"), arg[1].getBytes("ISO-8859-1")); for (int i=0; i 0) { - String groupSIDs[] = ntSystem.getGroupIDs(); + String[] groupSIDs = ntSystem.getGroupIDs(); groups = new NTSidGroupPrincipal[groupSIDs.length]; for (int i = 0; i < groupSIDs.length; i++) { groups[i] = new NTSidGroupPrincipal(groupSIDs[i]); diff --git a/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/module/NTSystem.java b/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/module/NTSystem.java index 54fa4c23348..d15636955a6 100644 --- a/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/module/NTSystem.java +++ b/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/module/NTSystem.java @@ -40,7 +40,7 @@ public class NTSystem { private String domain; private String domainSID; private String userSID; - private String groupIDs[]; + private String[] groupIDs; private String primaryGroupID; private long impersonationToken; diff --git a/jdk/src/jdk.security.jgss/share/classes/com/sun/security/sasl/gsskerb/FactoryImpl.java b/jdk/src/jdk.security.jgss/share/classes/com/sun/security/sasl/gsskerb/FactoryImpl.java index 8f74a1393ba..b95873f7894 100644 --- a/jdk/src/jdk.security.jgss/share/classes/com/sun/security/sasl/gsskerb/FactoryImpl.java +++ b/jdk/src/jdk.security.jgss/share/classes/com/sun/security/sasl/gsskerb/FactoryImpl.java @@ -38,10 +38,10 @@ import javax.security.auth.callback.CallbackHandler; * @author Rosanna Lee */ public final class FactoryImpl implements SaslClientFactory, SaslServerFactory { - private static final String myMechs[] = { + private static final String[] myMechs = { "GSSAPI"}; - private static final int mechPolicies[] = { + private static final int[] mechPolicies = { PolicyUtils.NOPLAINTEXT|PolicyUtils.NOANONYMOUS|PolicyUtils.NOACTIVE }; From 99f867bdedfbc43ccede40075f60847d49470a7e Mon Sep 17 00:00:00 2001 From: Roger Riggs Date: Thu, 9 Jul 2015 09:55:36 -0400 Subject: [PATCH 14/43] 8098852: java/lang/ProcessHandle/InfoTest.java failed: total cpu time expected < 10s more Correct javachild to spin until cputime increases by amount; cleanup InfoTest Reviewed-by: darcy --- .../java/lang/ProcessHandle/InfoTest.java | 45 ++++++++++--------- .../java/lang/ProcessHandle/JavaChild.java | 10 ++--- 2 files changed, 29 insertions(+), 26 deletions(-) diff --git a/jdk/test/java/lang/ProcessHandle/InfoTest.java b/jdk/test/java/lang/ProcessHandle/InfoTest.java index c4c89cf349b..5efc99062d3 100644 --- a/jdk/test/java/lang/ProcessHandle/InfoTest.java +++ b/jdk/test/java/lang/ProcessHandle/InfoTest.java @@ -32,24 +32,24 @@ import java.nio.file.Paths; import java.nio.file.attribute.UserPrincipal; import java.time.Duration; import java.time.Instant; -import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.Random; -import java.util.Scanner; -import java.util.StringTokenizer; import java.util.concurrent.TimeUnit; import jdk.testlibrary.Platform; +import jdk.testlibrary.Utils; + import org.testng.Assert; import org.testng.annotations.Test; import org.testng.TestNG; /* * @test + * @build jdk.testlibrary.* * @library /lib/testlibrary * @summary Functions of ProcessHandle.Info * @author Roger Riggs @@ -91,16 +91,16 @@ public class InfoTest { "test runner is included."); ProcessHandle self = ProcessHandle.current(); - Duration somecpu = Duration.ofMillis(200L); - Instant end = Instant.now().plus(somecpu); + Duration someCPU = Duration.ofMillis(200L); + Instant end = Instant.now().plus(someCPU); while (Instant.now().isBefore(end)) { // waste the cpu } ProcessHandle.Info info = self.info(); System.out.printf(" info: %s%n", info); Optional totalCpu = info.totalCpuDuration(); - if (totalCpu.isPresent() && (totalCpu.get().compareTo(somecpu) < 0)) { - Assert.fail("reported cputime less than expected: " + somecpu + ", " + + if (totalCpu.isPresent() && (totalCpu.get().compareTo(someCPU) < 0)) { + Assert.fail("reported cputime less than expected: " + someCPU + ", " + "actual: " + info.totalCpuDuration()); } } @@ -111,17 +111,16 @@ public class InfoTest { @Test public static void test2() { try { - long cpulooptime = 1 << 8; + long cpuLoopTime = 100; // 100 ms String[] extraArgs = {"pid", "parent", "stdin"}; - Instant beforeStart = Instant.now().truncatedTo(ChronoUnit.SECONDS); JavaChild p1 = JavaChild.spawnJavaChild((Object[])extraArgs); Instant afterStart = Instant.now(); try (BufferedReader lines = p1.outputReader()) { Duration lastCpu = Duration.ofMillis(0L); - for (int j = 0; j < 20; j++) { + for (int j = 0; j < 10; j++) { - p1.sendAction("cpuloop", cpulooptime); + p1.sendAction("cpuloop", cpuLoopTime); p1.sendAction("cputime", ""); // Read cputime from child @@ -187,17 +186,21 @@ public class InfoTest { if (info.totalCpuDuration().isPresent()) { Duration totalCPU = info.totalCpuDuration().get(); Duration epsilon = Duration.ofMillis(200L); - Assert.assertTrue(totalCPU.toNanos() > 0L, - "total cpu time expected > 0ms, actual: " + totalCPU); - Assert.assertTrue(totalCPU.toNanos() < lastCpu.toNanos() + 10_000_000_000L, - "total cpu time expected < 10s more than previous iteration, actual: " + totalCPU); if (childCpuTime != null) { System.out.printf(" info.totalCPU: %s, childCpuTime: %s, diff: %s%n", - totalCPU.toNanos(), childCpuTime.toNanos(), childCpuTime.toNanos() - totalCPU.toNanos()); + totalCPU.toNanos(), childCpuTime.toNanos(), + childCpuTime.toNanos() - totalCPU.toNanos()); Assert.assertTrue(checkEpsilon(childCpuTime, totalCPU, epsilon), childCpuTime + " should be within " + epsilon + " of " + totalCPU); } + Assert.assertTrue(totalCPU.toNanos() > 0L, + "total cpu time expected > 0ms, actual: " + totalCPU); + long t = Utils.adjustTimeout(10L); // Adjusted timeout seconds + Assert.assertTrue(totalCPU.toNanos() < lastCpu.toNanos() + t * 1_000_000_000L, + "total cpu time expected < " + t + + " seconds more than previous iteration, actual: " + + (totalCPU.toNanos() - lastCpu.toNanos())); lastCpu = totalCPU; } @@ -209,7 +212,7 @@ public class InfoTest { } } } - p1.waitFor(5, TimeUnit.SECONDS); + p1.waitFor(Utils.adjustTimeout(5), TimeUnit.SECONDS); } catch (IOException | InterruptedException ie) { ie.printStackTrace(System.out); Assert.fail("unexpected exception", ie); @@ -252,7 +255,7 @@ public class InfoTest { Assert.assertTrue(p.waitFor(15, TimeUnit.SECONDS)); } } catch (IOException | InterruptedException ex) { - ex.printStackTrace(System.out);; + ex.printStackTrace(System.out); } finally { // Destroy any children that still exist ProcessUtil.destroyProcessTree(ProcessHandle.current()); @@ -274,7 +277,7 @@ public class InfoTest { if (dur1.isPresent() && dur2.isPresent()) { Duration total1 = dur1.get(); - Duration total2 = dur2.get(); ; + Duration total2 = dur2.get(); System.out.printf(" total1 vs. mbean: %s, getProcessCpuTime: %s, diff: %s%n", Objects.toString(total1), myCputime1, myCputime1.minus(total1)); System.out.printf(" total2 vs. mbean: %s, getProcessCpuTime: %s, diff: %s%n", @@ -326,7 +329,7 @@ public class InfoTest { * @param d1 a Duration - presumed to be shorter * @param d2 a 2nd Duration - presumed to be greater (or within Epsilon) * @param epsilon Epsilon the amount of overlap allowed - * @return + * @return true if d2 is greater than d1 or within epsilon, false otherwise */ static boolean checkEpsilon(Duration d1, Duration d2, Duration epsilon) { if (d1.toNanos() <= d2.toNanos()) { @@ -339,7 +342,7 @@ public class InfoTest { /** * Spawn a native process with the provided arguments. * @param command the executable of native process - * @args + * @param args to start a new process * @return the Process that was started * @throws IOException thrown by ProcessBuilder.start */ diff --git a/jdk/test/java/lang/ProcessHandle/JavaChild.java b/jdk/test/java/lang/ProcessHandle/JavaChild.java index 0aed8343242..9d4a6e1f2f2 100644 --- a/jdk/test/java/lang/ProcessHandle/JavaChild.java +++ b/jdk/test/java/lang/ProcessHandle/JavaChild.java @@ -281,12 +281,12 @@ private static volatile int commandSeq = 0; // Command sequence number sendResult(action, Integer.toString(millis)); break; case "cpuloop": - long times = Long.valueOf(args[nextArg++]); - Instant end = Instant.now().plusMillis(times); - while (Instant.now().isBefore(end)) { - // burn the cpu til the time is up + long cpuMillis = Long.valueOf(args[nextArg++]); + long cpuTarget = getCpuTime() + cpuMillis * 1_000_000L; + while (getCpuTime() < cpuTarget) { + // burn the cpu until the time is up } - sendResult(action, times); + sendResult(action, cpuMillis); break; case "cputime": sendResult(action, getCpuTime()); From 57996d703c08d77bc49f8cfc315e09b45eeb5bb6 Mon Sep 17 00:00:00 2001 From: Martin Buchholz Date: Mon, 29 Jun 2015 15:02:35 -0700 Subject: [PATCH 15/43] 6260652: (coll) Arrays.asList(x).toArray().getClass() should be Object[].class Return Arrays.copyOf(a, a.length, Object[].class) Reviewed-by: igerasim, psandoz --- jdk/src/java.base/share/classes/java/util/ArrayList.java | 3 ++- jdk/src/java.base/share/classes/java/util/Arrays.java | 2 +- jdk/src/java.base/share/classes/java/util/Vector.java | 3 ++- .../java/util/concurrent/CopyOnWriteArrayList.java | 3 ++- .../share/classes/sun/awt/util/IdentityArrayList.java | 3 ++- jdk/test/java/util/Collection/MOAT.java | 8 +------- 6 files changed, 10 insertions(+), 12 deletions(-) diff --git a/jdk/src/java.base/share/classes/java/util/ArrayList.java b/jdk/src/java.base/share/classes/java/util/ArrayList.java index 9caec34ec64..7a3ad72fb46 100644 --- a/jdk/src/java.base/share/classes/java/util/ArrayList.java +++ b/jdk/src/java.base/share/classes/java/util/ArrayList.java @@ -178,7 +178,8 @@ public class ArrayList extends AbstractList public ArrayList(Collection c) { elementData = c.toArray(); if ((size = elementData.length) != 0) { - // c.toArray might (incorrectly) not return Object[] (see 6260652) + // defend against c.toArray (incorrectly) not returning Object[] + // (see e.g. https://bugs.openjdk.java.net/browse/JDK-6260652) if (elementData.getClass() != Object[].class) elementData = Arrays.copyOf(elementData, size, Object[].class); } else { diff --git a/jdk/src/java.base/share/classes/java/util/Arrays.java b/jdk/src/java.base/share/classes/java/util/Arrays.java index ae321498dc4..8c34de5e41f 100644 --- a/jdk/src/java.base/share/classes/java/util/Arrays.java +++ b/jdk/src/java.base/share/classes/java/util/Arrays.java @@ -3820,7 +3820,7 @@ public class Arrays { @Override public Object[] toArray() { - return a.clone(); + return Arrays.copyOf(a, a.length, Object[].class); } @Override diff --git a/jdk/src/java.base/share/classes/java/util/Vector.java b/jdk/src/java.base/share/classes/java/util/Vector.java index d89f0cd0497..815a6469e73 100644 --- a/jdk/src/java.base/share/classes/java/util/Vector.java +++ b/jdk/src/java.base/share/classes/java/util/Vector.java @@ -174,7 +174,8 @@ public class Vector public Vector(Collection c) { elementData = c.toArray(); elementCount = elementData.length; - // c.toArray might (incorrectly) not return Object[] (see 6260652) + // defend against c.toArray (incorrectly) not returning Object[] + // (see e.g. https://bugs.openjdk.java.net/browse/JDK-6260652) if (elementData.getClass() != Object[].class) elementData = Arrays.copyOf(elementData, elementCount, Object[].class); } diff --git a/jdk/src/java.base/share/classes/java/util/concurrent/CopyOnWriteArrayList.java b/jdk/src/java.base/share/classes/java/util/concurrent/CopyOnWriteArrayList.java index 162ad3b51d1..3e328ec351e 100644 --- a/jdk/src/java.base/share/classes/java/util/concurrent/CopyOnWriteArrayList.java +++ b/jdk/src/java.base/share/classes/java/util/concurrent/CopyOnWriteArrayList.java @@ -134,7 +134,8 @@ public class CopyOnWriteArrayList elements = ((CopyOnWriteArrayList)c).getArray(); else { elements = c.toArray(); - // c.toArray might (incorrectly) not return Object[] (see 6260652) + // defend against c.toArray (incorrectly) not returning Object[] + // (see e.g. https://bugs.openjdk.java.net/browse/JDK-6260652) if (elements.getClass() != Object[].class) elements = Arrays.copyOf(elements, elements.length, Object[].class); } diff --git a/jdk/src/java.desktop/share/classes/sun/awt/util/IdentityArrayList.java b/jdk/src/java.desktop/share/classes/sun/awt/util/IdentityArrayList.java index b6d107b62f6..a3216464a95 100644 --- a/jdk/src/java.desktop/share/classes/sun/awt/util/IdentityArrayList.java +++ b/jdk/src/java.desktop/share/classes/sun/awt/util/IdentityArrayList.java @@ -142,7 +142,8 @@ public class IdentityArrayList extends AbstractList public IdentityArrayList(Collection c) { elementData = c.toArray(); size = elementData.length; - // c.toArray might (incorrectly) not return Object[] (see 6260652) + // defend against c.toArray (incorrectly) not returning Object[] + // (see e.g. https://bugs.openjdk.java.net/browse/JDK-6260652) if (elementData.getClass() != Object[].class) elementData = Arrays.copyOf(elementData, size, Object[].class); } diff --git a/jdk/test/java/util/Collection/MOAT.java b/jdk/test/java/util/Collection/MOAT.java index e04659c4dda..608b7022e9b 100644 --- a/jdk/test/java/util/Collection/MOAT.java +++ b/jdk/test/java/util/Collection/MOAT.java @@ -356,13 +356,7 @@ public class MOAT { } check(c.toArray().length == c.size()); - check(c.toArray().getClass() == Object[].class - || - // !!!! - // 6260652: (coll) Arrays.asList(x).toArray().getClass() - // should be Object[].class - (c.getClass().getName().equals("java.util.Arrays$ArrayList")) - ); + check(c.toArray().getClass() == Object[].class); for (int size : new int[]{0,1,c.size(), c.size()+1}) { Integer[] a = c.toArray(new Integer[size]); check((size > c.size()) || a.length == c.size()); From d71bb8c72b087583b56dd5e5dfea1f10aca83aaf Mon Sep 17 00:00:00 2001 From: Vladimir Kozlov Date: Tue, 30 Jun 2015 12:12:18 -0700 Subject: [PATCH 16/43] 8129893: 8129094 fix is incomplete Move old and add new primitive type check. Reviewed-by: iveresov --- hotspot/src/share/vm/opto/superword.cpp | 20 ++++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/hotspot/src/share/vm/opto/superword.cpp b/hotspot/src/share/vm/opto/superword.cpp index df06cc2577d..d7f035f7f92 100644 --- a/hotspot/src/share/vm/opto/superword.cpp +++ b/hotspot/src/share/vm/opto/superword.cpp @@ -183,13 +183,20 @@ void SuperWord::unrolling_analysis(CountedLoopNode *cl, int &local_loop_unroll_f break; } + // Ignore nodes with non-primitive type. + BasicType bt; + if (n->is_Mem()) { + bt = n->as_Mem()->memory_type(); + } else { + bt = n->bottom_type()->basic_type(); + } + if (is_java_primitive(bt) == false) { + ignored_loop_nodes[i] = n->_idx; + continue; + } + if (n->is_Mem()) { MemNode* current = n->as_Mem(); - BasicType bt = current->memory_type(); - if (is_java_primitive(bt) == false) { - ignored_loop_nodes[i] = n->_idx; - continue; - } Node* adr = n->in(MemNode::Address); Node* n_ctrl = _phase->get_ctrl(adr); @@ -231,11 +238,12 @@ void SuperWord::unrolling_analysis(CountedLoopNode *cl, int &local_loop_unroll_f BasicType bt; Node* n = lpt()->_body.at(i); - if (n->is_Store()) { + if (n->is_Mem()) { bt = n->as_Mem()->memory_type(); } else { bt = n->bottom_type()->basic_type(); } + if (is_java_primitive(bt) == false) continue; int cur_max_vector = Matcher::max_vector_size(bt); From 934ad8e49bad01c782ae4ad581c3a29edf8eeaf8 Mon Sep 17 00:00:00 2001 From: Igor Veresov Date: Tue, 30 Jun 2015 14:44:53 -0700 Subject: [PATCH 17/43] 8079775: Java 9-fastdebug ia32 Error: Unimplemented with "-XX:CompilationPolicyChoice=1 -XX:-TieredCompilation" options 8079062: Java 9-fastdebug crash(hit assertion) with "-XX:CompilationPolicyChoice=1 -XX:-TieredCompilation" options Revive stack walk compilation policy Reviewed-by: kvn --- hotspot/src/share/vm/runtime/arguments.cpp | 8 ++++++-- hotspot/src/share/vm/runtime/compilationPolicy.cpp | 8 ++++---- hotspot/src/share/vm/runtime/rframe.cpp | 8 ++++---- hotspot/src/share/vm/runtime/rframe.hpp | 12 ++++++------ 4 files changed, 20 insertions(+), 16 deletions(-) diff --git a/hotspot/src/share/vm/runtime/arguments.cpp b/hotspot/src/share/vm/runtime/arguments.cpp index 5d89e91b6a4..68901fbe84c 100644 --- a/hotspot/src/share/vm/runtime/arguments.cpp +++ b/hotspot/src/share/vm/runtime/arguments.cpp @@ -3753,8 +3753,12 @@ jint Arguments::apply_ergo() { if (TieredCompilation) { set_tiered_flags(); } else { - // Check if the policy is valid. Policies 0 and 1 are valid for non-tiered setup. - if (CompilationPolicyChoice >= 2) { + int max_compilation_policy_choice = 1; +#ifdef COMPILER2 + max_compilation_policy_choice = 2; +#endif + // Check if the policy is valid. + if (CompilationPolicyChoice >= max_compilation_policy_choice) { vm_exit_during_initialization( "Incompatible compilation policy selected", NULL); } diff --git a/hotspot/src/share/vm/runtime/compilationPolicy.cpp b/hotspot/src/share/vm/runtime/compilationPolicy.cpp index db8122b754d..59c37428da4 100644 --- a/hotspot/src/share/vm/runtime/compilationPolicy.cpp +++ b/hotspot/src/share/vm/runtime/compilationPolicy.cpp @@ -512,7 +512,7 @@ void StackWalkCompPolicy::method_invocation_event(methodHandle m, JavaThread* th RegisterMap reg_map(thread, false); javaVFrame* triggerVF = thread->last_java_vframe(®_map); // triggerVF is the frame that triggered its counter - RFrame* first = new InterpretedRFrame(triggerVF->fr(), thread, m); + RFrame* first = new InterpretedRFrame(triggerVF->fr(), thread, m()); if (first->top_method()->code() != NULL) { // called obsolete method/nmethod -- no need to recompile @@ -557,8 +557,8 @@ RFrame* StackWalkCompPolicy::findTopInlinableFrame(GrowableArray* stack if( !next ) // No next frame up the stack? break; // Then compile with current frame - methodHandle m = current->top_method(); - methodHandle next_m = next->top_method(); + Method* m = current->top_method(); + Method* next_m = next->top_method(); if (TraceCompilationPolicy && Verbose) { tty->print("[caller: "); @@ -644,7 +644,7 @@ RFrame* StackWalkCompPolicy::findTopInlinableFrame(GrowableArray* stack if (TraceCompilationPolicy && Verbose) { tty->print("\n\t check caller: "); next_m->print_short_name(tty); - tty->print(" ( interpreted " INTPTR_FORMAT ", size=%d ) ", p2i((address)next_m()), next_m->code_size()); + tty->print(" ( interpreted " INTPTR_FORMAT ", size=%d ) ", p2i((address)next_m), next_m->code_size()); } current = next; diff --git a/hotspot/src/share/vm/runtime/rframe.cpp b/hotspot/src/share/vm/runtime/rframe.cpp index f3ef5504b37..1707bf13bb0 100644 --- a/hotspot/src/share/vm/runtime/rframe.cpp +++ b/hotspot/src/share/vm/runtime/rframe.cpp @@ -52,12 +52,12 @@ InterpretedRFrame::InterpretedRFrame(frame fr, JavaThread* thread, RFrame*const : RFrame(fr, thread, callee) { RegisterMap map(thread, false); _vf = javaVFrame::cast(vframe::new_vframe(&_fr, &map, thread)); - _method = methodHandle(thread, _vf->method()); + _method = _vf->method(); assert( _vf->is_interpreted_frame(), "must be interpreted"); init(); } -InterpretedRFrame::InterpretedRFrame(frame fr, JavaThread* thread, methodHandle m) +InterpretedRFrame::InterpretedRFrame(frame fr, JavaThread* thread, Method* m) : RFrame(fr, thread, NULL) { RegisterMap map(thread, false); _vf = javaVFrame::cast(vframe::new_vframe(&_fr, &map, thread)); @@ -140,8 +140,8 @@ void CompiledRFrame::init() { _nm = compiledVFrame::cast(vf)->code(); vf = vf->top(); _vf = javaVFrame::cast(vf); - _method = methodHandle(thread(), CodeCache::find_nmethod(_fr.pc())->method()); - assert(_method(), "should have found a method"); + _method = CodeCache::find_nmethod(_fr.pc())->method(); + assert(_method, "should have found a method"); #ifndef PRODUCT _invocations = _method->compiled_invocation_count(); #endif diff --git a/hotspot/src/share/vm/runtime/rframe.hpp b/hotspot/src/share/vm/runtime/rframe.hpp index e70093b944b..af8fea3943e 100644 --- a/hotspot/src/share/vm/runtime/rframe.hpp +++ b/hotspot/src/share/vm/runtime/rframe.hpp @@ -60,7 +60,7 @@ class RFrame : public ResourceObj { frame fr() const { return _fr; } JavaThread* thread() const { return _thread; } virtual int cost() const = 0; // estimated inlining cost (size) - virtual methodHandle top_method() const = 0; + virtual Method* top_method() const = 0; virtual javaVFrame* top_vframe() const = 0; virtual nmethod* nm() const { ShouldNotCallThis(); return NULL; } @@ -79,7 +79,7 @@ class CompiledRFrame : public RFrame { // frame containing a compiled method protected: nmethod* _nm; javaVFrame* _vf; // top vframe; may be NULL (for most recent frame) - methodHandle _method; // top method + Method* _method; // top method CompiledRFrame(frame fr, JavaThread* thread, RFrame*const callee); void init(); @@ -88,7 +88,7 @@ class CompiledRFrame : public RFrame { // frame containing a compiled method public: CompiledRFrame(frame fr, JavaThread* thread); // for nmethod triggering its counter (callee == NULL) bool is_compiled() const { return true; } - methodHandle top_method() const { return _method; } + Method* top_method() const { return _method; } javaVFrame* top_vframe() const { return _vf; } nmethod* nm() const { return _nm; } int cost() const; @@ -98,16 +98,16 @@ class CompiledRFrame : public RFrame { // frame containing a compiled method class InterpretedRFrame : public RFrame { // interpreter frame protected: javaVFrame* _vf; // may be NULL (for most recent frame) - methodHandle _method; + Method* _method; InterpretedRFrame(frame fr, JavaThread* thread, RFrame*const callee); void init(); friend class RFrame; public: - InterpretedRFrame(frame fr, JavaThread* thread, methodHandle m); // constructor for method triggering its invocation counter + InterpretedRFrame(frame fr, JavaThread* thread, Method* m); // constructor for method triggering its invocation counter bool is_interpreted() const { return true; } - methodHandle top_method() const { return _method; } + Method* top_method() const { return _method; } javaVFrame* top_vframe() const { return _vf; } int cost() const; void print(); From fba308328bea3b04e142fc84450bbdee4dcb86e7 Mon Sep 17 00:00:00 2001 From: Tobias Hartmann Date: Wed, 1 Jul 2015 09:07:10 +0200 Subject: [PATCH 18/43] 8129937: compiler/codecache/jmx/UsageThresholdIncreasedTest.java fails with "Usage threshold was hit" Tests should not assume that usage of non-profiled code heap is predictable. Reviewed-by: kvn, dpochepk --- .../codecache/jmx/CodeCacheUtils.java | 36 +++++++++++++++---- .../compiler/codecache/jmx/GetUsageTest.java | 20 +++++------ .../compiler/codecache/jmx/PeakUsageTest.java | 12 +++---- .../codecache/jmx/PoolsIndependenceTest.java | 12 +++---- .../jmx/ThresholdNotificationsTest.java | 8 ++--- .../jmx/UsageThresholdExceededTest.java | 13 +++---- .../jmx/UsageThresholdIncreasedTest.java | 7 ++-- .../jmx/UsageThresholdNotExceededTest.java | 12 +++---- 8 files changed, 64 insertions(+), 56 deletions(-) diff --git a/hotspot/test/compiler/codecache/jmx/CodeCacheUtils.java b/hotspot/test/compiler/codecache/jmx/CodeCacheUtils.java index 6b3313206cb..0adab36140c 100644 --- a/hotspot/test/compiler/codecache/jmx/CodeCacheUtils.java +++ b/hotspot/test/compiler/codecache/jmx/CodeCacheUtils.java @@ -21,6 +21,7 @@ * questions. */ +import jdk.test.lib.Asserts; import jdk.test.lib.Utils; import java.lang.management.MemoryPoolMXBean; import javax.management.Notification; @@ -80,19 +81,42 @@ public final class CodeCacheUtils { } /** - * A "non-nmethods" code heap is used by interpreter during bytecode - * execution, thus, it can't be predicted if this code heap usage will be - * increased or not. Same goes for 'All'. + * Checks if the usage of the code heap corresponding to 'btype' can be + * predicted at runtime if we disable compilation. The usage of the + * 'NonNMethod' code heap can not be predicted because we generate adapters + * and buffers at runtime. The 'MethodNonProfiled' code heap is also not + * predictable because we may generate compiled versions of method handle + * intrinsics while resolving methods at runtime. Same applies to 'All'. * * @param btype BlobType to be checked * @return boolean value, true if respective code heap is predictable */ public static boolean isCodeHeapPredictable(BlobType btype) { - return btype == BlobType.MethodNonProfiled - || btype == BlobType.MethodProfiled; + return btype == BlobType.MethodProfiled; } - public static void disableCollectionUsageThresholds(){ + /** + * Verifies that 'newValue' is equal to 'oldValue' if usage of the + * corresponding code heap is predictable. Checks the weaker condition + * 'newValue >= oldValue' if usage is not predictable because intermediate + * allocations may happen. + * + * @param btype BlobType of the code heap to be checked + * @param newValue New value to be verified + * @param oldValue Old value to be verified + * @param msg Error message if verification fails + */ + public static void assertEQorGTE(BlobType btype, long newValue, long oldValue, String msg) { + if (CodeCacheUtils.isCodeHeapPredictable(btype)) { + // Usage is predictable, check strong == condition + Asserts.assertEQ(newValue, oldValue, msg); + } else { + // Usage is not predictable, check weaker >= condition + Asserts.assertGTE(newValue, oldValue, msg); + } + } + + public static void disableCollectionUsageThresholds() { BlobType.getAvailable().stream() .map(BlobType::getMemoryPool) .filter(MemoryPoolMXBean::isCollectionUsageThresholdSupported) diff --git a/hotspot/test/compiler/codecache/jmx/GetUsageTest.java b/hotspot/test/compiler/codecache/jmx/GetUsageTest.java index 5eaf5515f34..d657699395c 100644 --- a/hotspot/test/compiler/codecache/jmx/GetUsageTest.java +++ b/hotspot/test/compiler/codecache/jmx/GetUsageTest.java @@ -52,10 +52,8 @@ public class GetUsageTest { public static void main(String[] args) throws Exception { for (BlobType btype : BlobType.getAvailable()) { - if (CodeCacheUtils.isCodeHeapPredictable(btype)) { - for (int allocSize = 10; allocSize < 100000; allocSize *= 10) { - new GetUsageTest(btype, allocSize).runTest(); - } + for (int allocSize = 10; allocSize < 100000; allocSize *= 10) { + new GetUsageTest(btype, allocSize).runTest(); } } } @@ -87,13 +85,15 @@ public class GetUsageTest { for (MemoryPoolMXBean entry : predictableBeans) { long diff = current.get(entry) - initial.get(entry); if (entry.equals(btype.getMemoryPool())) { - Asserts.assertFalse(diff <= 0L || diff > usageUpperEstimate, - String.format("Pool %s usage increase was reported " - + "unexpectedly as increased by %d using " - + "allocation size %d", entry.getName(), - diff, allocateSize)); + if (CodeCacheUtils.isCodeHeapPredictable(btype)) { + Asserts.assertFalse(diff <= 0L || diff > usageUpperEstimate, + String.format("Pool %s usage increase was reported " + + "unexpectedly as increased by %d using " + + "allocation size %d", entry.getName(), + diff, allocateSize)); + } } else { - Asserts.assertEQ(diff, 0L, + CodeCacheUtils.assertEQorGTE(btype, diff, 0L, String.format("Pool %s usage changed unexpectedly while" + " trying to increase: %s using allocation " + "size %d", entry.getName(), diff --git a/hotspot/test/compiler/codecache/jmx/PeakUsageTest.java b/hotspot/test/compiler/codecache/jmx/PeakUsageTest.java index 3c596ba0726..e906b86f032 100644 --- a/hotspot/test/compiler/codecache/jmx/PeakUsageTest.java +++ b/hotspot/test/compiler/codecache/jmx/PeakUsageTest.java @@ -52,9 +52,7 @@ public class PeakUsageTest { public static void main(String[] args) { for (BlobType btype : BlobType.getAvailable()) { - if (CodeCacheUtils.isCodeHeapPredictable(btype)) { - new PeakUsageTest(btype).runTest(); - } + new PeakUsageTest(btype).runTest(); } } @@ -65,7 +63,7 @@ public class PeakUsageTest { CodeCacheUtils.ALLOCATION_SIZE, btype.id); long newPeakUsage = bean.getPeakUsage().getUsed(); try { - Asserts.assertEQ(newPeakUsage, bean.getUsage().getUsed(), + CodeCacheUtils.assertEQorGTE(btype, newPeakUsage, bean.getUsage().getUsed(), "Peak usage does not match usage after allocation for " + bean.getName()); } finally { @@ -73,18 +71,18 @@ public class PeakUsageTest { CodeCacheUtils.WB.freeCodeBlob(addr); } } - Asserts.assertEQ(newPeakUsage, bean.getPeakUsage().getUsed(), + CodeCacheUtils.assertEQorGTE(btype, newPeakUsage, bean.getPeakUsage().getUsed(), "Code cache peak usage has changed after usage decreased for " + bean.getName()); bean.resetPeakUsage(); - Asserts.assertEQ(bean.getPeakUsage().getUsed(), + CodeCacheUtils.assertEQorGTE(btype, bean.getPeakUsage().getUsed(), bean.getUsage().getUsed(), "Code cache peak usage is not equal to usage after reset for " + bean.getName()); long addr2 = CodeCacheUtils.WB.allocateCodeBlob( CodeCacheUtils.ALLOCATION_SIZE, btype.id); try { - Asserts.assertEQ(bean.getPeakUsage().getUsed(), + CodeCacheUtils.assertEQorGTE(btype, bean.getPeakUsage().getUsed(), bean.getUsage().getUsed(), "Code cache peak usage is not equal to usage after fresh " + "allocation for " + bean.getName()); diff --git a/hotspot/test/compiler/codecache/jmx/PoolsIndependenceTest.java b/hotspot/test/compiler/codecache/jmx/PoolsIndependenceTest.java index 5c7559346c9..ee0fce1106c 100644 --- a/hotspot/test/compiler/codecache/jmx/PoolsIndependenceTest.java +++ b/hotspot/test/compiler/codecache/jmx/PoolsIndependenceTest.java @@ -97,13 +97,11 @@ public class PoolsIndependenceTest implements NotificationListener { return false; }); for (BlobType bt : BlobType.getAvailable()) { - if (CodeCacheUtils.isCodeHeapPredictable(bt)) { - int expectedNotificationsAmount = bt.equals(btype) ? 1 : 0; - Asserts.assertEQ(counters.get(bt.getMemoryPool().getName()).get(), - expectedNotificationsAmount, String.format("Unexpected " - + "amount of notifications for pool: %s", - bt.getMemoryPool().getName())); - } + int expectedNotificationsAmount = bt.equals(btype) ? 1 : 0; + CodeCacheUtils.assertEQorGTE(btype, counters.get(bt.getMemoryPool().getName()).get(), + expectedNotificationsAmount, String.format("Unexpected " + + "amount of notifications for pool: %s", + bt.getMemoryPool().getName())); } try { ((NotificationEmitter) ManagementFactory.getMemoryMXBean()). diff --git a/hotspot/test/compiler/codecache/jmx/ThresholdNotificationsTest.java b/hotspot/test/compiler/codecache/jmx/ThresholdNotificationsTest.java index 65793eac327..c5b9223ac10 100644 --- a/hotspot/test/compiler/codecache/jmx/ThresholdNotificationsTest.java +++ b/hotspot/test/compiler/codecache/jmx/ThresholdNotificationsTest.java @@ -54,9 +54,7 @@ public class ThresholdNotificationsTest implements NotificationListener { public static void main(String[] args) { for (BlobType bt : BlobType.getAvailable()) { - if (CodeCacheUtils.isCodeHeapPredictable(bt)) { - new ThresholdNotificationsTest(bt).runTest(); - } + new ThresholdNotificationsTest(bt).runTest(); } } @@ -92,7 +90,9 @@ public class ThresholdNotificationsTest implements NotificationListener { } Asserts.assertTrue( Utils.waitForCondition( - () -> counter == iterationsCount, WAIT_TIME), + () -> (CodeCacheUtils.isCodeHeapPredictable(btype) ? + (counter == iterationsCount) : (counter >= iterationsCount)), + WAIT_TIME), "Couldn't receive expected notifications count"); try { ((NotificationEmitter) ManagementFactory.getMemoryMXBean()). diff --git a/hotspot/test/compiler/codecache/jmx/UsageThresholdExceededTest.java b/hotspot/test/compiler/codecache/jmx/UsageThresholdExceededTest.java index 4ebbadc1f7b..a699134c6cb 100644 --- a/hotspot/test/compiler/codecache/jmx/UsageThresholdExceededTest.java +++ b/hotspot/test/compiler/codecache/jmx/UsageThresholdExceededTest.java @@ -51,13 +51,9 @@ public class UsageThresholdExceededTest { } public static void main(String[] args) { - int iterationsCount = - Integer.getInteger("jdk.test.lib.iterations", 1); + int iterationsCount = Integer.getInteger("jdk.test.lib.iterations", 1); for (BlobType btype : BlobType.getAvailable()) { - if (CodeCacheUtils.isCodeHeapPredictable(btype)) { - new UsageThresholdExceededTest(btype, iterationsCount) - .runTest(); - } + new UsageThresholdExceededTest(btype, iterationsCount).runTest(); } } @@ -67,9 +63,8 @@ public class UsageThresholdExceededTest { for (int i = 0; i < iterations; i++) { CodeCacheUtils.hitUsageThreshold(bean, btype); } - Asserts.assertEQ(bean.getUsageThresholdCount(), oldValue + iterations, + CodeCacheUtils.assertEQorGTE(btype, bean.getUsageThresholdCount(), oldValue + iterations, "Unexpected threshold usage count"); - System.out.printf("INFO: Scenario finished successfully for %s%n", - bean.getName()); + System.out.printf("INFO: Scenario finished successfully for %s%n", bean.getName()); } } diff --git a/hotspot/test/compiler/codecache/jmx/UsageThresholdIncreasedTest.java b/hotspot/test/compiler/codecache/jmx/UsageThresholdIncreasedTest.java index ebb5d4b82cd..5fc45184b85 100644 --- a/hotspot/test/compiler/codecache/jmx/UsageThresholdIncreasedTest.java +++ b/hotspot/test/compiler/codecache/jmx/UsageThresholdIncreasedTest.java @@ -27,7 +27,6 @@ import sun.hotspot.code.BlobType; /* * @test UsageThresholdIncreasedTest - * @ignore 8129937 * @library /testlibrary /../../test/lib * @modules java.base/sun.misc * java.management @@ -54,14 +53,12 @@ public class UsageThresholdIncreasedTest { public static void main(String[] args) { for (BlobType btype : BlobType.getAvailable()) { - if (CodeCacheUtils.isCodeHeapPredictable(btype)) { - new UsageThresholdIncreasedTest(btype).runTest(); - } + new UsageThresholdIncreasedTest(btype).runTest(); } } private void checkUsageThresholdCount(MemoryPoolMXBean bean, long count){ - Asserts.assertEQ(bean.getUsageThresholdCount(), count, + CodeCacheUtils.assertEQorGTE(btype, bean.getUsageThresholdCount(), count, String.format("Usage threshold was hit: %d times for %s " + "Threshold value: %d with current usage: %d", bean.getUsageThresholdCount(), bean.getName(), diff --git a/hotspot/test/compiler/codecache/jmx/UsageThresholdNotExceededTest.java b/hotspot/test/compiler/codecache/jmx/UsageThresholdNotExceededTest.java index aabede08001..23036cc1938 100644 --- a/hotspot/test/compiler/codecache/jmx/UsageThresholdNotExceededTest.java +++ b/hotspot/test/compiler/codecache/jmx/UsageThresholdNotExceededTest.java @@ -50,9 +50,7 @@ public class UsageThresholdNotExceededTest { public static void main(String[] args) { for (BlobType btype : BlobType.getAvailable()) { - if (CodeCacheUtils.isCodeHeapPredictable(btype)) { - new UsageThresholdNotExceededTest(btype).runTest(); - } + new UsageThresholdNotExceededTest(btype).runTest(); } } @@ -65,13 +63,11 @@ public class UsageThresholdNotExceededTest { - CodeCacheUtils.getHeaderSize(btype), btype.id); // a gc cycle triggers usage threshold recalculation CodeCacheUtils.WB.fullGC(); - Asserts.assertEQ(bean.getUsageThresholdCount(), initialThresholdCount, - String.format("Usage threshold was hit: %d times for %s. " + CodeCacheUtils.assertEQorGTE(btype, bean.getUsageThresholdCount(), initialThresholdCount, + String.format("Usage threshold was hit: %d times for %s. " + "Threshold value: %d with current usage: %d", bean.getUsageThresholdCount(), bean.getName(), bean.getUsageThreshold(), bean.getUsage().getUsed())); - - System.out.println("INFO: Case finished successfully for " - + bean.getName()); + System.out.println("INFO: Case finished successfully for " + bean.getName()); } } From 833d2385853be65eb99778cb3a7ea0a2d2a1aa1e Mon Sep 17 00:00:00 2001 From: Athijegannathan Sundararajan Date: Fri, 3 Jul 2015 18:41:58 +0530 Subject: [PATCH 19/43] 8130424: if directory specified with --dest-dir does not exist, only .class files are dumped and .js files are not Reviewed-by: attila, lagergren, hannesw --- .../jdk/nashorn/internal/codegen/DumpBytecode.java | 2 +- .../classes/jdk/nashorn/internal/runtime/Source.java | 12 +++++++++--- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/codegen/DumpBytecode.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/codegen/DumpBytecode.java index e6773821e46..620a43e5764 100644 --- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/codegen/DumpBytecode.java +++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/codegen/DumpBytecode.java @@ -88,7 +88,7 @@ public final class DumpBytecode { } - // should code be dumped to disk - only valid in compile_only mode? + // should code be dumped to disk if (env._dest_dir != null) { final String fileName = className.replace('.', File.separatorChar) + ".class"; final int index = fileName.lastIndexOf(File.separatorChar); diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/Source.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/Source.java index 7599ff4028f..df8da96a066 100644 --- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/Source.java +++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/Source.java @@ -995,7 +995,7 @@ public final class Source implements Loggable { return initLogger(Context.getContextTrusted()); } - private File dumpFile(final String dir) { + private File dumpFile(final File dirFile) { final URL u = getURL(); final StringBuilder buf = new StringBuilder(); // make it unique by prefixing current date & time @@ -1010,11 +1010,17 @@ public final class Source implements Loggable { buf.append(getName()); } - return new File(dir, buf.toString()); + return new File(dirFile, buf.toString()); } void dump(final String dir) { - final File file = dumpFile(dir); + final File dirFile = new File(dir); + final File file = dumpFile(dirFile); + if (!dirFile.exists() && !dirFile.mkdirs()) { + debug("Skipping source dump for " + name); + return; + } + try (final FileOutputStream fos = new FileOutputStream(file)) { final PrintWriter pw = new PrintWriter(fos); pw.print(data.toString()); From 94d29a19c8d307abe43a2a06115abcc1673b8653 Mon Sep 17 00:00:00 2001 From: Athijegannathan Sundararajan Date: Mon, 6 Jul 2015 15:59:55 +0530 Subject: [PATCH 20/43] 8130476: Remove unused methods in Global.java Reviewed-by: hannesw, attila --- .../jdk/nashorn/internal/objects/Global.java | 268 ------------------ 1 file changed, 268 deletions(-) diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/Global.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/Global.java index 8a8c62e22d1..2ebfd5fbc51 100644 --- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/Global.java +++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/Global.java @@ -1768,38 +1768,10 @@ public final class Global extends Scope { return ScriptFunction.getPrototype(getBuiltinFloat64Array()); } - private ScriptFunction getBuiltinArray() { - return builtinArray; - } - ScriptFunction getTypeErrorThrower() { return typeErrorThrower; } - /** - * Called from compiled script code to test if builtin has been overridden - * - * @return true if builtin array has not been overridden - */ - public static boolean isBuiltinArray() { - final Global instance = Global.instance(); - return instance.array == instance.getBuiltinArray(); - } - - private ScriptFunction getBuiltinBoolean() { - return builtinBoolean; - } - - /** - * Called from compiled script code to test if builtin has been overridden - * - * @return true if builtin boolean has not been overridden - */ - public static boolean isBuiltinBoolean() { - final Global instance = Global.instance(); - return instance._boolean == instance.getBuiltinBoolean(); - } - private synchronized ScriptFunction getBuiltinDate() { if (this.builtinDate == null) { this.builtinDate = initConstructorAndSwitchPoint("Date", ScriptFunction.class); @@ -1810,30 +1782,6 @@ public final class Global extends Scope { return this.builtinDate; } - /** - * Called from compiled script code to test if builtin has been overridden - * - * @return true if builtin date has not been overridden - */ - public static boolean isBuiltinDate() { - final Global instance = Global.instance(); - return instance.date == LAZY_SENTINEL || instance.date == instance.getBuiltinDate(); - } - - private ScriptFunction getBuiltinError() { - return builtinError; - } - - /** - * Called from compiled script code to test if builtin has been overridden - * - * @return true if builtin error has not been overridden - */ - public static boolean isBuiltinError() { - final Global instance = Global.instance(); - return instance.error == instance.getBuiltinError(); - } - private synchronized ScriptFunction getBuiltinEvalError() { if (this.builtinEvalError == null) { this.builtinEvalError = initErrorSubtype("EvalError", getErrorPrototype()); @@ -1841,30 +1789,10 @@ public final class Global extends Scope { return this.builtinEvalError; } - /** - * Called from compiled script code to test if builtin has been overridden - * - * @return true if builtin eval error has not been overridden - */ - public static boolean isBuiltinEvalError() { - final Global instance = Global.instance(); - return instance.evalError == LAZY_SENTINEL || instance.evalError == instance.getBuiltinEvalError(); - } - private ScriptFunction getBuiltinFunction() { return builtinFunction; } - /** - * Called from compiled script code to test if builtin has been overridden - * - * @return true if builtin function has not been overridden - */ - public static boolean isBuiltinFunction() { - final Global instance = Global.instance(); - return instance.function == instance.getBuiltinFunction(); - } - /** * Get the switchpoint used to check property changes for Function.prototype.apply * @return the switchpoint guarding apply (same as guarding call, and everything else in function) @@ -1906,16 +1834,6 @@ public final class Global extends Scope { return builtinJSAdapter; } - /** - * Called from compiled script code to test if builtin has been overridden - * - * @return true if builtin JSAdapter has not been overridden - */ - public static boolean isBuiltinJSAdapter() { - final Global instance = Global.instance(); - return instance.jsadapter == LAZY_SENTINEL || instance.jsadapter == instance.getBuiltinJSAdapter(); - } - private synchronized ScriptObject getBuiltinJSON() { if (this.builtinJSON == null) { this.builtinJSON = initConstructorAndSwitchPoint("JSON", ScriptObject.class); @@ -1923,44 +1841,6 @@ public final class Global extends Scope { return this.builtinJSON; } - /** - * Called from compiled script code to test if builtin has been overridden - * - * @return true if builtin JSON has has not been overridden - */ - public static boolean isBuiltinJSON() { - final Global instance = Global.instance(); - return instance.json == LAZY_SENTINEL || instance.json == instance.getBuiltinJSON(); - } - - private ScriptObject getBuiltinJava() { - return builtinJava; - } - - /** - * Called from compiled script code to test if builtin has been overridden - * - * @return true if builtin Java has not been overridden - */ - public static boolean isBuiltinJava() { - final Global instance = Global.instance(); - return instance.java == instance.getBuiltinJava(); - } - - private ScriptObject getBuiltinJavax() { - return builtinJavax; - } - - /** - * Called from compiled script code to test if builtin has been overridden - * - * @return true if builtin Javax has not been overridden - */ - public static boolean isBuiltinJavax() { - final Global instance = Global.instance(); - return instance.javax == instance.getBuiltinJavax(); - } - private synchronized ScriptFunction getBuiltinJavaImporter() { if (this.builtinJavaImporter == null) { this.builtinJavaImporter = initConstructor("JavaImporter", ScriptFunction.class); @@ -1975,68 +1855,6 @@ public final class Global extends Scope { return this.builtinJavaApi; } - /** - * Called from compiled script code to test if builtin has been overridden - * - * @return true if builtin Java importer has not been overridden - */ - public static boolean isBuiltinJavaImporter() { - final Global instance = Global.instance(); - return instance.javaImporter == LAZY_SENTINEL || instance.javaImporter == instance.getBuiltinJavaImporter(); - } - - /** - * Called from compiled script code to test if builtin has been overridden - * - * @return true if builtin math has not been overridden - */ - public static boolean isBuiltinMath() { - final Global instance = Global.instance(); - return instance.math == instance.builtinMath; - } - - private ScriptFunction getBuiltinNumber() { - return builtinNumber; - } - - /** - * Called from compiled script code to test if builtin has been overridden - * - * @return true if builtin number has not been overridden - */ - public static boolean isBuiltinNumber() { - final Global instance = Global.instance(); - return instance.number == instance.getBuiltinNumber(); - } - - private ScriptFunction getBuiltinObject() { - return builtinObject; - } - - /** - * Called from compiled script code to test if builtin has been overridden - * - * @return true if builtin object has not been overridden - */ - public static boolean isBuiltinObject() { - final Global instance = Global.instance(); - return instance.object == instance.getBuiltinObject(); - } - - private ScriptObject getBuiltinPackages() { - return builtinPackages; - } - - /** - * Called from compiled script code to test if builtin has been overridden - * - * @return true if builtin package has not been overridden - */ - public static boolean isBuiltinPackages() { - final Global instance = Global.instance(); - return instance.packages == instance.getBuiltinPackages(); - } - private synchronized ScriptFunction getBuiltinRangeError() { if (this.builtinRangeError == null) { this.builtinRangeError = initErrorSubtype("RangeError", getErrorPrototype()); @@ -2044,30 +1862,6 @@ public final class Global extends Scope { return builtinRangeError; } - /** - * Called from compiled script code to test if builtin has been overridden - * - * @return true if builtin range error has not been overridden - */ - public static boolean isBuiltinRangeError() { - final Global instance = Global.instance(); - return instance.rangeError == LAZY_SENTINEL || instance.rangeError == instance.getBuiltinRangeError(); - } - - private synchronized ScriptFunction getBuiltinReferenceError() { - return builtinReferenceError; - } - - /** - * Called from compiled script code to test if builtin has been overridden - * - * @return true if builtin reference error has not been overridden - */ - public static boolean isBuiltinReferenceError() { - final Global instance = Global.instance(); - return instance.referenceError == instance.getBuiltinReferenceError(); - } - private synchronized ScriptFunction getBuiltinRegExp() { if (this.builtinRegExp == null) { this.builtinRegExp = initConstructorAndSwitchPoint("RegExp", ScriptFunction.class); @@ -2081,58 +1875,6 @@ public final class Global extends Scope { return builtinRegExp; } - /** - * Called from compiled script code to test if builtin has been overridden - * - * @return true if builtin regexp has not been overridden - */ - public static boolean isBuiltinRegExp() { - final Global instance = Global.instance(); - return instance.regexp == LAZY_SENTINEL || instance.regexp == instance.getBuiltinRegExp(); - } - - private ScriptFunction getBuiltinString() { - return builtinString; - } - - /** - * Called from compiled script code to test if builtin has been overridden - * - * @return true if builtin Java has not been overridden - */ - public static boolean isBuiltinString() { - final Global instance = Global.instance(); - return instance.string == instance.getBuiltinString(); - } - - private ScriptFunction getBuiltinSyntaxError() { - return builtinSyntaxError; - } - - /** - * Called from compiled script code to test if builtin has been overridden - * - * @return true if builtin syntax error has not been overridden - */ - public static boolean isBuiltinSyntaxError() { - final Global instance = Global.instance(); - return instance.syntaxError == instance.getBuiltinSyntaxError(); - } - - private ScriptFunction getBuiltinTypeError() { - return builtinTypeError; - } - - /** - * Called from compiled script code to test if builtin has been overridden - * - * @return true if builtin type error has not been overridden - */ - public static boolean isBuiltinTypeError() { - final Global instance = Global.instance(); - return instance.typeError == instance.getBuiltinTypeError(); - } - private synchronized ScriptFunction getBuiltinURIError() { if (this.builtinURIError == null) { this.builtinURIError = initErrorSubtype("URIError", getErrorPrototype()); @@ -2140,16 +1882,6 @@ public final class Global extends Scope { return this.builtinURIError; } - /** - * Called from compiled script code to test if builtin has been overridden - * - * @return true if builtin URI error has not been overridden - */ - public static boolean isBuiltinURIError() { - final Global instance = Global.instance(); - return instance.uriError == LAZY_SENTINEL || instance.uriError == instance.getBuiltinURIError(); - } - @Override public String getClassName() { return "global"; From f5a4efc17159691632cae2bb7412a6a6108ed8ad Mon Sep 17 00:00:00 2001 From: Jan Lahoda Date: Tue, 7 Jul 2015 13:17:52 +0200 Subject: [PATCH 21/43] 8080679: Include jline in JDK for Java and JavaScript REPLs Reviewed-by: alanb, erikj, forax, iris, sundar --- make/CompileJavaModules.gmk | 4 ++++ make/Images.gmk | 2 +- modules.xml | 20 ++++++++++++++++++++ 3 files changed, 25 insertions(+), 1 deletion(-) diff --git a/make/CompileJavaModules.gmk b/make/CompileJavaModules.gmk index af91a283696..ea48c7f40f1 100644 --- a/make/CompileJavaModules.gmk +++ b/make/CompileJavaModules.gmk @@ -368,6 +368,10 @@ jdk.compiler_CLEAN_FILES := $(wildcard \ ################################################################################ +jdk.internal.le_COPY := .properties + +################################################################################ + jdk.jcmd_COPY := _options ################################################################################ diff --git a/make/Images.gmk b/make/Images.gmk index 80147ccf9d9..0dfba0f509e 100644 --- a/make/Images.gmk +++ b/make/Images.gmk @@ -46,7 +46,7 @@ PROVIDER_MODULES += jdk.charsets jdk.crypto.ec jdk.crypto.pkcs11 jdk.jvmstat jdk jdk.naming.dns jdk.naming.rmi jdk.scripting.nashorn jdk.zipfs # tools -TOOLS_MODULES += jdk.attach jdk.compiler jdk.dev jdk.javadoc jdk.jcmd jdk.jconsole \ +TOOLS_MODULES += jdk.attach jdk.compiler jdk.dev jdk.internal.le jdk.javadoc jdk.jcmd jdk.jconsole \ jdk.hotspot.agent jdk.hprof.agent jdk.jartool jdk.jdeps jdk.jdi jdk.jdwp.agent \ jdk.policytool jdk.rmic jdk.xml.bind jdk.xml.ws diff --git a/modules.xml b/modules.xml index 355f56a4270..78c9ae561ae 100644 --- a/modules.xml +++ b/modules.xml @@ -1624,6 +1624,26 @@ com.sun.net.httpserver.spi + + jdk.internal.le + java.base + + jdk.internal.jline + jdk.scripting.nashorn.shell + + + jdk.internal.jline.console + jdk.scripting.nashorn.shell + + + jdk.internal.jline.console.completer + jdk.scripting.nashorn.shell + + + jdk.internal.jline.console.history + jdk.scripting.nashorn.shell + + jdk.jartool java.base From 39ea286002788b627af6aa76dd72607367b905b7 Mon Sep 17 00:00:00 2001 From: Athijegannathan Sundararajan Date: Tue, 7 Jul 2015 18:33:24 +0530 Subject: [PATCH 22/43] 8130663: 6 fields can be static fields in Global class Reviewed-by: hannesw, attila --- .../codegen/ObjectClassGenerator.java | 1 - .../jdk/nashorn/internal/objects/Global.java | 24 +++++++++---------- .../internal/runtime/CompiledFunction.java | 2 +- .../nashorn/internal/runtime/Property.java | 14 +++++------ .../nashorn/internal/runtime/PropertyMap.java | 6 ++--- 5 files changed, 23 insertions(+), 24 deletions(-) diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/codegen/ObjectClassGenerator.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/codegen/ObjectClassGenerator.java index 383d2f130d4..b0514a0c34b 100644 --- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/codegen/ObjectClassGenerator.java +++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/codegen/ObjectClassGenerator.java @@ -69,7 +69,6 @@ import jdk.nashorn.internal.runtime.UnwarrantedOptimismException; import jdk.nashorn.internal.runtime.logging.DebugLogger; import jdk.nashorn.internal.runtime.logging.Loggable; import jdk.nashorn.internal.runtime.logging.Logger; -import jdk.nashorn.internal.runtime.options.Options; /** * Generates the ScriptObject subclass structure with fields for a user objects. diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/Global.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/Global.java index 2ebfd5fbc51..81a54252f5a 100644 --- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/Global.java +++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/Global.java @@ -88,14 +88,14 @@ import jdk.nashorn.tools.ShellFunctions; */ @ScriptClass("Global") public final class Global extends Scope { - // Placeholder value used in place of a location property (__FILE__, __DIR__, __LINE__) - private static final Object LOCATION_PROPERTY_PLACEHOLDER = new Object(); + // This special value is used to flag a lazily initialized global property. + // This also serves as placeholder value used in place of a location property + // (__FILE__, __DIR__, __LINE__) + private static final Object LAZY_SENTINEL = new Object(); + private final InvokeByName TO_STRING = new InvokeByName("toString", ScriptObject.class); private final InvokeByName VALUE_OF = new InvokeByName("valueOf", ScriptObject.class); - // placeholder value for lazily initialized global objects - private static final Object LAZY_SENTINEL = new Object(); - /** * Optimistic builtin names that require switchpoint invalidation * upon assignment. Overly conservative, but works for now, to avoid @@ -182,15 +182,15 @@ public final class Global extends Scope { /** Value property NaN of the Global Object - ECMA 15.1.1.1 NaN */ @Property(attributes = Attribute.NON_ENUMERABLE_CONSTANT) - public final double NaN = Double.NaN; + public static final double NaN = Double.NaN; /** Value property Infinity of the Global Object - ECMA 15.1.1.2 Infinity */ @Property(attributes = Attribute.NON_ENUMERABLE_CONSTANT) - public final double Infinity = Double.POSITIVE_INFINITY; + public static final double Infinity = Double.POSITIVE_INFINITY; /** Value property Undefined of the Global Object - ECMA 15.1.1.3 Undefined */ @Property(attributes = Attribute.NON_ENUMERABLE_CONSTANT) - public final Object undefined = UNDEFINED; + public static final Object undefined = UNDEFINED; /** ECMA 15.1.2.1 eval(x) */ @Property(attributes = Attribute.NOT_ENUMERABLE) @@ -830,15 +830,15 @@ public final class Global extends Scope { /** Nashorn extension: current script's file name */ @Property(name = "__FILE__", attributes = Attribute.NON_ENUMERABLE_CONSTANT) - public final Object __FILE__ = LOCATION_PROPERTY_PLACEHOLDER; + public static final Object __FILE__ = LAZY_SENTINEL; /** Nashorn extension: current script's directory */ @Property(name = "__DIR__", attributes = Attribute.NON_ENUMERABLE_CONSTANT) - public final Object __DIR__ = LOCATION_PROPERTY_PLACEHOLDER; + public static final Object __DIR__ = LAZY_SENTINEL; /** Nashorn extension: current source line number being executed */ @Property(name = "__LINE__", attributes = Attribute.NON_ENUMERABLE_CONSTANT) - public final Object __LINE__ = LOCATION_PROPERTY_PLACEHOLDER; + public static final Object __LINE__ = LAZY_SENTINEL; private volatile NativeDate DEFAULT_DATE; @@ -2020,7 +2020,7 @@ public final class Global extends Scope { * @return true if the value is a placeholder, false otherwise. */ public static boolean isLocationPropertyPlaceholder(final Object placeholder) { - return placeholder == LOCATION_PROPERTY_PLACEHOLDER; + return placeholder == LAZY_SENTINEL; } /** diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/CompiledFunction.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/CompiledFunction.java index 371ecacad95..d63e8e16ef3 100644 --- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/CompiledFunction.java +++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/CompiledFunction.java @@ -907,7 +907,7 @@ final class CompiledFunction { OptimismInfo(final RecompilableScriptFunctionData data, final Map invalidatedProgramPoints) { this.data = data; this.log = data.getLogger(); - this.invalidatedProgramPoints = invalidatedProgramPoints == null ? new TreeMap() : invalidatedProgramPoints; + this.invalidatedProgramPoints = invalidatedProgramPoints == null ? new TreeMap<>() : invalidatedProgramPoints; newOptimisticAssumptions(); } diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/Property.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/Property.java index 7d5442088cb..71372be2da8 100644 --- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/Property.java +++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/Property.java @@ -562,8 +562,8 @@ public abstract class Property implements Serializable { @Override public int hashCode() { - final Class type = getLocalType(); - return Objects.hashCode(this.key) ^ flags ^ getSlot() ^ (type == null ? 0 : type.hashCode()); + final Class t = getLocalType(); + return Objects.hashCode(this.key) ^ flags ^ getSlot() ^ (t == null ? 0 : t.hashCode()); } @Override @@ -588,7 +588,7 @@ public abstract class Property implements Serializable { getKey().equals(otherProperty.getKey()); } - private static final String type(final Class type) { + private static String type(final Class type) { if (type == null) { return "undef"; } else if (type == int.class) { @@ -608,8 +608,8 @@ public abstract class Property implements Serializable { */ public final String toStringShort() { final StringBuilder sb = new StringBuilder(); - final Class type = getLocalType(); - sb.append(getKey()).append(" (").append(type(type)).append(')'); + final Class t = getLocalType(); + sb.append(getKey()).append(" (").append(type(t)).append(')'); return sb.toString(); } @@ -625,7 +625,7 @@ public abstract class Property implements Serializable { @Override public String toString() { final StringBuilder sb = new StringBuilder(); - final Class type = getLocalType(); + final Class t = getLocalType(); sb.append(indent(getKey(), 20)). append(" id="). @@ -635,7 +635,7 @@ public abstract class Property implements Serializable { append(") "). append(getClass().getSimpleName()). append(" {"). - append(indent(type(type), 5)). + append(indent(type(t), 5)). append('}'); if (slot != -1) { diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/PropertyMap.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/PropertyMap.java index 9618a69e754..43a6ee02563 100644 --- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/PropertyMap.java +++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/PropertyMap.java @@ -999,10 +999,10 @@ public final class PropertyMap implements Iterable, Serializable { for (final Property p : map0.getProperties()) { final Property p2 = map1.findProperty(p.getKey()); if (p2 == null) { - sb.append("FIRST ONLY : [" + p + "]"); + sb.append("FIRST ONLY : [").append(p).append("]"); found = true; } else if (p2 != p) { - sb.append("DIFFERENT : [" + p + "] != [" + p2 + "]"); + sb.append("DIFFERENT : [").append(p).append("] != [").append(p2).append("]"); found = true; } } @@ -1010,7 +1010,7 @@ public final class PropertyMap implements Iterable, Serializable { for (final Property p2 : map1.getProperties()) { final Property p1 = map0.findProperty(p2.getKey()); if (p1 == null) { - sb.append("SECOND ONLY: [" + p2 + "]"); + sb.append("SECOND ONLY: [").append(p2).append("]"); found = true; } } From 18b9b116dc119bc0852348e3fd0d01750638db10 Mon Sep 17 00:00:00 2001 From: Daniel Fuchs Date: Tue, 7 Jul 2015 18:19:57 +0200 Subject: [PATCH 23/43] 8130238: Remove com.sun.org.apache.xalan.internal.xsltc.cmdline Reviewed-by: lancea, joehw --- .../xalan/internal/xsltc/cmdline/Compile.java | 171 ---------- .../internal/xsltc/cmdline/Transform.java | 292 ------------------ .../internal/xsltc/cmdline/getopt/GetOpt.java | 258 ---------------- .../cmdline/getopt/GetOptsException.java | 34 -- .../getopt/IllegalArgumentException.java | 32 -- .../getopt/MissingOptArgException.java | 35 --- 6 files changed, 822 deletions(-) delete mode 100644 jaxp/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/cmdline/Compile.java delete mode 100644 jaxp/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/cmdline/Transform.java delete mode 100644 jaxp/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/cmdline/getopt/GetOpt.java delete mode 100644 jaxp/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/cmdline/getopt/GetOptsException.java delete mode 100644 jaxp/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/cmdline/getopt/IllegalArgumentException.java delete mode 100644 jaxp/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/cmdline/getopt/MissingOptArgException.java diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/cmdline/Compile.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/cmdline/Compile.java deleted file mode 100644 index 9ab7e30bec6..00000000000 --- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/cmdline/Compile.java +++ /dev/null @@ -1,171 +0,0 @@ -/* - * reserved comment block - * DO NOT REMOVE OR ALTER! - */ -/* - * Copyright 2001-2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/* - * $Id: Compile.java,v 1.2.4.1 2005/08/31 11:24:13 pvedula Exp $ - */ - -package com.sun.org.apache.xalan.internal.xsltc.cmdline; - -import com.sun.org.apache.xalan.internal.utils.FeatureManager; -import java.io.File; -import java.net.URL; -import java.util.Vector; - -import com.sun.org.apache.xalan.internal.xsltc.cmdline.getopt.GetOpt; -import com.sun.org.apache.xalan.internal.xsltc.cmdline.getopt.GetOptsException; -import com.sun.org.apache.xalan.internal.xsltc.compiler.XSLTC; -import com.sun.org.apache.xalan.internal.xsltc.compiler.util.ErrorMsg; - -/** - * @author Jacek Ambroziak - * @author Santiago Pericas-Geertsen - * @author G. Todd Miller - * @author Morten Jorgensen - */ -public final class Compile { - - // Versioning numbers for the compiler -v option output - private static int VERSION_MAJOR = 1; - private static int VERSION_MINOR = 4; - private static int VERSION_DELTA = 0; - - - - // This variable should be set to false to prevent any methods in this - // class from calling System.exit(). As this is a command-line tool, - // calling System.exit() is normally OK, but we also want to allow for - // this class being used in other ways as well. - private static boolean _allowExit = true; - - - public static void printUsage() { - System.err.println("XSLTC version " + - VERSION_MAJOR + "." + VERSION_MINOR + - ((VERSION_DELTA > 0) ? ("." + VERSION_DELTA) : ("")) + "\n" + - new ErrorMsg(ErrorMsg.COMPILE_USAGE_STR)); - if (_allowExit) System.exit(-1); - } - - /** - * This method implements the command line compiler. See the USAGE_STRING - * constant for a description. It may make sense to move the command-line - * handling to a separate package (ie. make one xsltc.cmdline.Compiler - * class that contains this main() method and one xsltc.cmdline.Transform - * class that contains the DefaultRun stuff). - */ - public static void main(String[] args) { - try { - boolean inputIsURL = false; - boolean useStdIn = false; - boolean classNameSet = false; - final GetOpt getopt = new GetOpt(args, "o:d:j:p:uxhsinv"); - if (args.length < 1) printUsage(); - - final XSLTC xsltc = new XSLTC(true, new FeatureManager()); - xsltc.init(); - - int c; - while ((c = getopt.getNextOption()) != -1) { - switch(c) { - case 'i': - useStdIn = true; - break; - case 'o': - xsltc.setClassName(getopt.getOptionArg()); - classNameSet = true; - break; - case 'd': - xsltc.setDestDirectory(getopt.getOptionArg()); - break; - case 'p': - xsltc.setPackageName(getopt.getOptionArg()); - break; - case 'j': - xsltc.setJarFileName(getopt.getOptionArg()); - break; - case 'x': - xsltc.setDebug(true); - break; - case 'u': - inputIsURL = true; - break; - case 's': - _allowExit = false; - break; - case 'n': - xsltc.setTemplateInlining(true); // used to be 'false' - break; - case 'v': - // fall through to case h - case 'h': - default: - printUsage(); - break; - } - } - - boolean compileOK; - - if (useStdIn) { - if (!classNameSet) { - System.err.println(new ErrorMsg(ErrorMsg.COMPILE_STDIN_ERR)); - if (_allowExit) System.exit(-1); - } - compileOK = xsltc.compile(System.in, xsltc.getClassName()); - } - else { - // Generate a vector containg URLs for all stylesheets specified - final String[] stylesheetNames = getopt.getCmdArgs(); - final Vector stylesheetVector = new Vector(); - for (int i = 0; i < stylesheetNames.length; i++) { - final String name = stylesheetNames[i]; - URL url; - if (inputIsURL) - url = new URL(name); - else - url = (new File(name)).toURI().toURL(); - stylesheetVector.addElement(url); - } - compileOK = xsltc.compile(stylesheetVector); - } - - // Compile the stylesheet and output class/jar file(s) - if (compileOK) { - xsltc.printWarnings(); - if (xsltc.getJarFileName() != null) xsltc.outputToJar(); - if (_allowExit) System.exit(0); - } - else { - xsltc.printWarnings(); - xsltc.printErrors(); - if (_allowExit) System.exit(-1); - } - } - catch (GetOptsException ex) { - System.err.println(ex); - printUsage(); // exits with code '-1' - } - catch (Exception e) { - e.printStackTrace(); - if (_allowExit) System.exit(-1); - } - } - -} diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/cmdline/Transform.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/cmdline/Transform.java deleted file mode 100644 index a81cd779594..00000000000 --- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/cmdline/Transform.java +++ /dev/null @@ -1,292 +0,0 @@ -/* - * reserved comment block - * DO NOT REMOVE OR ALTER! - */ -/* - * Copyright 2001-2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/* - * $Id: Transform.java,v 1.2.4.1 2005/09/12 09:07:33 pvedula Exp $ - */ - -package com.sun.org.apache.xalan.internal.xsltc.cmdline; - -import com.sun.org.apache.xalan.internal.utils.ObjectFactory; -import com.sun.org.apache.xalan.internal.xsltc.DOMEnhancedForDTM; -import com.sun.org.apache.xalan.internal.xsltc.StripFilter; -import com.sun.org.apache.xalan.internal.xsltc.TransletException; -import com.sun.org.apache.xalan.internal.xsltc.compiler.util.ErrorMsg; -import com.sun.org.apache.xalan.internal.xsltc.dom.DOMWSFilter; -import com.sun.org.apache.xalan.internal.xsltc.dom.XSLTCDTMManager; -import com.sun.org.apache.xalan.internal.xsltc.runtime.AbstractTranslet; -import com.sun.org.apache.xalan.internal.xsltc.runtime.Constants; -import com.sun.org.apache.xalan.internal.xsltc.runtime.Parameter; -import com.sun.org.apache.xalan.internal.xsltc.runtime.output.TransletOutputHandlerFactory; -import com.sun.org.apache.xml.internal.dtm.DTMWSFilter; -import com.sun.org.apache.xml.internal.serializer.SerializationHandler; -import java.io.FileNotFoundException; -import java.net.MalformedURLException; -import java.net.UnknownHostException; -import java.util.Vector; -import javax.xml.parsers.SAXParser; -import javax.xml.parsers.SAXParserFactory; -import javax.xml.transform.sax.SAXSource; -import org.xml.sax.InputSource; -import org.xml.sax.SAXException; -import org.xml.sax.XMLReader; - -/** - * @author Jacek Ambroziak - * @author Santiago Pericas-Geertsen - * @author G. Todd Miller - * @author Morten Jorgensen - */ -final public class Transform { - - private SerializationHandler _handler; - - private String _fileName; - private String _className; - private String _jarFileSrc; - private boolean _isJarFileSpecified = false; - private Vector _params = null; - private boolean _uri, _debug; - private int _iterations; - - public Transform(String className, String fileName, - boolean uri, boolean debug, int iterations) { - _fileName = fileName; - _className = className; - _uri = uri; - _debug = debug; - _iterations = iterations; - } - - public String getFileName(){return _fileName;} - public String getClassName(){return _className;} - - public void setParameters(Vector params) { - _params = params; - } - - private void setJarFileInputSrc(boolean flag, String jarFile) { - // TODO: at this time we do not do anything with this - // information, attempts to add the jarfile to the CLASSPATH - // were successful via System.setProperty, but the effects - // were not visible to the running JVM. For now we add jarfile - // to CLASSPATH in the wrapper script that calls this program. - _isJarFileSpecified = flag; - // TODO verify jarFile exists... - _jarFileSrc = jarFile; - } - - private void doTransform() { - try { - final Class clazz = ObjectFactory.findProviderClass(_className, true); - final AbstractTranslet translet = (AbstractTranslet)clazz.newInstance(); - translet.postInitialization(); - - // Create a SAX parser and get the XMLReader object it uses - final SAXParserFactory factory = SAXParserFactory.newInstance(); - try { - factory.setFeature(Constants.NAMESPACE_FEATURE,true); - } - catch (Exception e) { - factory.setNamespaceAware(true); - } - final SAXParser parser = factory.newSAXParser(); - final XMLReader reader = parser.getXMLReader(); - - // Set the DOM's DOM builder as the XMLReader's SAX2 content handler - XSLTCDTMManager dtmManager = - XSLTCDTMManager.createNewDTMManagerInstance(); - - DTMWSFilter wsfilter; - if (translet != null && translet instanceof StripFilter) { - wsfilter = new DOMWSFilter(translet); - } else { - wsfilter = null; - } - - final DOMEnhancedForDTM dom = - (DOMEnhancedForDTM)dtmManager.getDTM( - new SAXSource(reader, new InputSource(_fileName)), - false, wsfilter, true, false, translet.hasIdCall()); - - dom.setDocumentURI(_fileName); - translet.prepassDocument(dom); - - // Pass global parameters - int n = _params.size(); - for (int i = 0; i < n; i++) { - Parameter param = (Parameter) _params.elementAt(i); - translet.addParameter(param._name, param._value); - } - - // Transform the document - TransletOutputHandlerFactory tohFactory = - TransletOutputHandlerFactory.newInstance(); - tohFactory.setOutputType(TransletOutputHandlerFactory.STREAM); - tohFactory.setEncoding(translet._encoding); - tohFactory.setOutputMethod(translet._method); - - if (_iterations == -1) { - translet.transform(dom, tohFactory.getSerializationHandler()); - } - else if (_iterations > 0) { - long mm = System.currentTimeMillis(); - for (int i = 0; i < _iterations; i++) { - translet.transform(dom, - tohFactory.getSerializationHandler()); - } - mm = System.currentTimeMillis() - mm; - - System.err.println("\n"); - } - } - catch (TransletException e) { - if (_debug) e.printStackTrace(); - System.err.println(new ErrorMsg(ErrorMsg.RUNTIME_ERROR_KEY)+ - e.getMessage()); - } - catch (RuntimeException e) { - if (_debug) e.printStackTrace(); - System.err.println(new ErrorMsg(ErrorMsg.RUNTIME_ERROR_KEY)+ - e.getMessage()); - } - catch (FileNotFoundException e) { - if (_debug) e.printStackTrace(); - ErrorMsg err = new ErrorMsg(ErrorMsg.FILE_NOT_FOUND_ERR, _fileName); - System.err.println(new ErrorMsg(ErrorMsg.RUNTIME_ERROR_KEY)+ - err.toString()); - } - catch (MalformedURLException e) { - if (_debug) e.printStackTrace(); - ErrorMsg err = new ErrorMsg(ErrorMsg.INVALID_URI_ERR, _fileName); - System.err.println(new ErrorMsg(ErrorMsg.RUNTIME_ERROR_KEY)+ - err.toString()); - } - catch (ClassNotFoundException e) { - if (_debug) e.printStackTrace(); - ErrorMsg err= new ErrorMsg(ErrorMsg.CLASS_NOT_FOUND_ERR,_className); - System.err.println(new ErrorMsg(ErrorMsg.RUNTIME_ERROR_KEY)+ - err.toString()); - } - catch (UnknownHostException e) { - if (_debug) e.printStackTrace(); - ErrorMsg err = new ErrorMsg(ErrorMsg.INVALID_URI_ERR, _fileName); - System.err.println(new ErrorMsg(ErrorMsg.RUNTIME_ERROR_KEY)+ - err.toString()); - } - catch (SAXException e) { - Exception ex = e.getException(); - if (_debug) { - if (ex != null) ex.printStackTrace(); - e.printStackTrace(); - } - System.err.print(new ErrorMsg(ErrorMsg.RUNTIME_ERROR_KEY)); - if (ex != null) - System.err.println(ex.getMessage()); - else - System.err.println(e.getMessage()); - } - catch (Exception e) { - if (_debug) e.printStackTrace(); - System.err.println(new ErrorMsg(ErrorMsg.RUNTIME_ERROR_KEY)+ - e.getMessage()); - } - } - - public static void printUsage() { - System.err.println(new ErrorMsg(ErrorMsg.TRANSFORM_USAGE_STR)); - } - - public static void main(String[] args) { - try { - if (args.length > 0) { - int i; - int iterations = -1; - boolean uri = false, debug = false; - boolean isJarFileSpecified = false; - String jarFile = null; - - // Parse options starting with '-' - for (i = 0; i < args.length && args[i].charAt(0) == '-'; i++) { - if (args[i].equals("-u")) { - uri = true; - } - else if (args[i].equals("-x")) { - debug = true; - } - else if (args[i].equals("-j")) { - isJarFileSpecified = true; - jarFile = args[++i]; - } - else if (args[i].equals("-n")) { - try { - iterations = Integer.parseInt(args[++i]); - } - catch (NumberFormatException e) { - // ignore - } - } - else { - printUsage(); - } - } - - // Enough arguments left ? - if (args.length - i < 2) printUsage(); - - // Get document file and class name - Transform handler = new Transform(args[i+1], args[i], uri, - debug, iterations); - handler.setJarFileInputSrc(isJarFileSpecified, jarFile); - - // Parse stylesheet parameters - Vector params = new Vector(); - for (i += 2; i < args.length; i++) { - final int equal = args[i].indexOf('='); - if (equal > 0) { - final String name = args[i].substring(0, equal); - final String value = args[i].substring(equal+1); - params.addElement(new Parameter(name, value)); - } - else { - printUsage(); - } - } - - if (i == args.length) { - handler.setParameters(params); - handler.doTransform(); - } - } else { - printUsage(); - } - } - catch (Exception e) { - e.printStackTrace(); - } - } -} diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/cmdline/getopt/GetOpt.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/cmdline/getopt/GetOpt.java deleted file mode 100644 index 3e537c9a86a..00000000000 --- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/cmdline/getopt/GetOpt.java +++ /dev/null @@ -1,258 +0,0 @@ -/* - * reserved comment block - * DO NOT REMOVE OR ALTER! - */ -/* - * Copyright 2001-2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/* - * $Id: GetOpt.java,v 1.2.4.1 2005/08/31 11:46:04 pvedula Exp $ - */ - -package com.sun.org.apache.xalan.internal.xsltc.cmdline.getopt; - -import java.util.ArrayList; -import java.util.List; -import java.util.ListIterator; - -import com.sun.org.apache.xalan.internal.xsltc.compiler.util.ErrorMsg; - - -/** -* GetOpt is a Java equivalent to the C getopt() library function -* discussed in man page getopt(3C). It provides command line -* parsing for Java applications. It supports the most rules of the -* command line standard (see man page intro(1)) including stacked -* options such as '-sxm' (which is equivalent to -s -x -m); it -* handles special '--' option that signifies the end of options. -* Additionally this implementation of getopt will check for -* mandatory arguments to options such as in the case of -* '-d ' it will throw a MissingOptArgException if the -* option argument '' is not included on the commandline. -* getopt(3C) does not check for this. - * @author G Todd Miller -*/ -public class GetOpt{ - public GetOpt(String[] args, String optString){ - theOptions = new ArrayList(); - int currOptIndex = 0; - theCmdArgs = new ArrayList(); - theOptionMatcher = new OptionMatcher(optString); - // fill in the options list - for(int i=0; i 2){ - // stacked options found, such as '-shm' - // iterate thru the tokens after the dash and - // add them to theOptions list - for(int j=1; j', if current option parsed is 'd' then - * getOptionArg() would return ''. - * @return String - argument for current parsed option. - * @param none - */ - public String getOptionArg(){ - String retval = null; - String tmp = theCurrentOption.getArgument(); - char c = theCurrentOption.getArgLetter(); - if(theOptionMatcher.hasArg(c)){ - retval = tmp; - } - return retval; - } - - /** - * gets list of the commandline arguments. For example, in command - * such as 'cmd -s -d file file2 file3 file4' with the usage - * 'cmd [-s] [-d ] ...', getCmdArgs() would return - * the list {file2, file3, file4}. - * @return String[] - list of command arguments that may appear - * after options and option arguments. - * @params none - */ - public String[] getCmdArgs(){ - String[] retval = new String[theCmdArgs.size()]; - int i=0; - for(ListIterator it=theCmdArgs.listIterator(); it.hasNext();){ - retval[i++] = (String)it.next(); - } - return retval; - } - - - private Option theCurrentOption = null; - private ListIterator theOptionsIterator; - private List theOptions = null; - private List theCmdArgs = null; - private OptionMatcher theOptionMatcher = null; - - /////////////////////////////////////////////////////////// - // - // Inner Classes - // - /////////////////////////////////////////////////////////// - - // inner class to model an option - class Option{ - private char theArgLetter; - private String theArgument = null; - public Option(char argLetter) { theArgLetter = argLetter; } - public void setArg(String arg) { - theArgument = arg; - } - public boolean hasArg() { return (theArgument != null); } - public char getArgLetter() { return theArgLetter; } - public String getArgument() { return theArgument; } - } // end class Option - - - // inner class to query optString for a possible option match, - // and whether or not a given legal option takes an argument. - // - class OptionMatcher{ - public OptionMatcher(String optString){ - theOptString = optString; - } - public boolean match(char c){ - boolean retval = false; - if(theOptString.indexOf(c) != -1){ - retval = true; - } - return retval; - } - public boolean hasArg(char c){ - boolean retval = false; - int index = theOptString.indexOf(c)+1; - if (index == theOptString.length()){ - // reached end of theOptString - retval = false; - } - else if(theOptString.charAt(index) == ':'){ - retval = true; - } - return retval; - } - private String theOptString = null; - } // end class OptionMatcher -}// end class GetOpt diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/cmdline/getopt/GetOptsException.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/cmdline/getopt/GetOptsException.java deleted file mode 100644 index fac6089576a..00000000000 --- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/cmdline/getopt/GetOptsException.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * reserved comment block - * DO NOT REMOVE OR ALTER! - */ -/* - * Copyright 2001-2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/* - * $Id: GetOptsException.java,v 1.2.4.1 2005/08/31 11:47:06 pvedula Exp $ - */ - -package com.sun.org.apache.xalan.internal.xsltc.cmdline.getopt; - -/** - * @author G Todd Miller - */ -public class GetOptsException extends Exception{ - static final long serialVersionUID = 8736874967183039804L; - public GetOptsException(String msg){ - super(msg); - } -} diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/cmdline/getopt/IllegalArgumentException.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/cmdline/getopt/IllegalArgumentException.java deleted file mode 100644 index 932f61e53f6..00000000000 --- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/cmdline/getopt/IllegalArgumentException.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * reserved comment block - * DO NOT REMOVE OR ALTER! - */ -/* - * Copyright 2001-2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/* - * $Id: IllegalArgumentException.java,v 1.2.4.1 2005/08/31 11:47:56 pvedula Exp $ - */ - -package com.sun.org.apache.xalan.internal.xsltc.cmdline.getopt; - - -class IllegalArgumentException extends GetOptsException{ - static final long serialVersionUID = 8642122427294793651L; - public IllegalArgumentException(String msg){ - super(msg); - } -} diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/cmdline/getopt/MissingOptArgException.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/cmdline/getopt/MissingOptArgException.java deleted file mode 100644 index c5e99b6b60a..00000000000 --- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/cmdline/getopt/MissingOptArgException.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * reserved comment block - * DO NOT REMOVE OR ALTER! - */ -/* - * Copyright 2001-2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/* - * $Id: MissingOptArgException.java,v 1.2.4.1 2005/08/31 11:49:21 pvedula Exp $ - */ - -package com.sun.org.apache.xalan.internal.xsltc.cmdline.getopt; - - -/** - * @author G Todd Miller - */ -class MissingOptArgException extends GetOptsException{ - static final long serialVersionUID = -1972471465394544822L; - public MissingOptArgException(String msg){ - super(msg); - } -} From bc9b78ac813736dc26ddfc8eec47134a6bb1b15d Mon Sep 17 00:00:00 2001 From: Joe Darcy Date: Tue, 7 Jul 2015 17:57:35 -0700 Subject: [PATCH 24/43] 8130716: Fix reference problems in jaxp javadoc Reviewed-by: lancea --- .../java.xml/share/classes/javax/xml/stream/XMLEventReader.java | 2 +- .../share/classes/javax/xml/stream/events/XMLEvent.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/jaxp/src/java.xml/share/classes/javax/xml/stream/XMLEventReader.java b/jaxp/src/java.xml/share/classes/javax/xml/stream/XMLEventReader.java index 97d20767055..3788fad0227 100644 --- a/jaxp/src/java.xml/share/classes/javax/xml/stream/XMLEventReader.java +++ b/jaxp/src/java.xml/share/classes/javax/xml/stream/XMLEventReader.java @@ -49,7 +49,7 @@ public interface XMLEventReader extends Iterator { * Get the next XMLEvent * @see XMLEvent * @throws XMLStreamException if there is an error with the underlying XML. - * @throws NoSuchElementException iteration has no more elements. + * @throws java.util.NoSuchElementException iteration has no more elements. */ public XMLEvent nextEvent() throws XMLStreamException; diff --git a/jaxp/src/java.xml/share/classes/javax/xml/stream/events/XMLEvent.java b/jaxp/src/java.xml/share/classes/javax/xml/stream/events/XMLEvent.java index 4f980121988..338b5cbff72 100644 --- a/jaxp/src/java.xml/share/classes/javax/xml/stream/events/XMLEvent.java +++ b/jaxp/src/java.xml/share/classes/javax/xml/stream/events/XMLEvent.java @@ -170,7 +170,7 @@ public interface XMLEvent extends javax.xml.stream.XMLStreamConstants { * infoset expressed. * * @param writer The writer that will output the data - * @throws XMLStreamException if there is a fatal error writing the event + * @throws javax.xml.stream.XMLStreamException if there is a fatal error writing the event */ public void writeAsEncodedUnicode(Writer writer) throws javax.xml.stream.XMLStreamException; From 4a2aab156b1dca5720c874366ad1b6d17048eca7 Mon Sep 17 00:00:00 2001 From: Athijegannathan Sundararajan Date: Wed, 8 Jul 2015 17:28:08 +0530 Subject: [PATCH 25/43] 8130734: Apply transformations found by netbeans Refactor->Inspect and transform menu Reviewed-by: hannesw, jlaskey, mhaupt --- .../internal/tools/nasgen/MemberInfo.java | 4 +-- .../internal/dynalink/beans/BeanLinker.java | 32 +++++++++---------- .../internal/dynalink/support/NameCodec.java | 2 +- .../support/TypeConverterFactory.java | 4 +-- .../jdk/nashorn/api/scripting/Formatter.java | 2 +- .../internal/codegen/ClassEmitter.java | 2 +- .../internal/codegen/CodeGenerator.java | 6 ++-- .../nashorn/internal/codegen/CompileUnit.java | 2 +- .../nashorn/internal/codegen/Compiler.java | 2 +- .../internal/codegen/ConstantData.java | 4 +-- .../internal/codegen/DumpBytecode.java | 2 +- .../internal/codegen/FindScopeDepths.java | 6 ++-- .../codegen/LocalVariableTypesCalculator.java | 12 +++---- .../jdk/nashorn/internal/codegen/Lower.java | 2 +- .../internal/codegen/types/IntType.java | 2 +- .../internal/ir/debug/NashornClassReader.java | 6 ++-- .../internal/ir/debug/NashornTextifier.java | 6 ++-- .../ir/debug/ObjectSizeCalculator.java | 2 +- .../nashorn/internal/objects/NativeArray.java | 6 ++-- .../nashorn/internal/objects/NativeDate.java | 2 +- .../internal/objects/NativeRegExp.java | 2 +- .../jdk/nashorn/internal/parser/Lexer.java | 4 +-- .../jdk/nashorn/internal/runtime/JSType.java | 12 +++---- .../internal/runtime/NashornLoader.java | 2 +- .../runtime/OptimisticReturnFilters.java | 2 +- .../internal/runtime/RewriteException.java | 4 +-- .../internal/runtime/ScriptRuntime.java | 2 +- .../jdk/nashorn/internal/runtime/Source.java | 2 +- .../runtime/arrays/ContinuousArrayData.java | 7 ++-- .../internal/runtime/arrays/IntArrayData.java | 2 +- .../runtime/arrays/LongArrayData.java | 2 +- .../runtime/arrays/NumberArrayData.java | 2 +- .../runtime/arrays/SparseArrayData.java | 16 +++++----- .../internal/runtime/linker/Bootstrap.java | 1 - .../linker/JavaArgumentConverters.java | 6 ++-- .../internal/runtime/regexp/joni/BitSet.java | 4 +-- .../internal/runtime/regexp/joni/Region.java | 2 +- .../runtime/regexp/joni/ast/AnchorNode.java | 4 +-- .../runtime/regexp/joni/ast/CClassNode.java | 6 ++-- .../runtime/regexp/joni/ast/ConsAltNode.java | 4 +-- .../runtime/regexp/joni/ast/EncloseNode.java | 18 +++++------ .../runtime/regexp/joni/ast/Node.java | 2 +- .../regexp/joni/ast/QuantifierNode.java | 16 +++++----- .../runtime/regexp/joni/ast/StringNode.java | 2 +- .../classes/jdk/nashorn/tools/Shell.java | 1 - .../jdk/nashorn/tools/ShellFunctions.java | 2 -- .../api/javaaccess/test/SharedObject.java | 2 +- .../api/scripting/test/ScriptEngineTest.java | 4 +-- .../test/ScriptObjectMirrorTest.java | 2 +- .../nashorn/api/tree/test/ParseAPITest.java | 2 +- .../internal/performance/OctaneTest.java | 16 +++------- .../test/ExceptionsNotSerializable.java | 2 +- .../framework/AbstractScriptRunnable.java | 8 ++--- .../internal/test/framework/TestFinder.java | 8 ++--- .../test/models/JDK_8081015_TestModel.java | 6 ++-- 55 files changed, 132 insertions(+), 151 deletions(-) diff --git a/nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/MemberInfo.java b/nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/MemberInfo.java index cc3524da2ab..daacb90a70b 100644 --- a/nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/MemberInfo.java +++ b/nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/MemberInfo.java @@ -39,7 +39,7 @@ import jdk.nashorn.internal.runtime.ScriptObject; */ public final class MemberInfo implements Cloneable { // class loader of this class - private static ClassLoader myLoader = MemberInfo.class.getClassLoader(); + private static final ClassLoader MY_LOADER = MemberInfo.class.getClassLoader(); /** * The different kinds of available class annotations @@ -493,7 +493,7 @@ public final class MemberInfo implements Cloneable { if (type.getSort() == Type.OBJECT) { try { - final Class clazz = Class.forName(type.getClassName(), false, myLoader); + final Class clazz = Class.forName(type.getClassName(), false, MY_LOADER); return ScriptObject.class.isAssignableFrom(clazz); } catch (final ClassNotFoundException cnfe) { return false; diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/internal/dynalink/beans/BeanLinker.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/internal/dynalink/beans/BeanLinker.java index a7dad71f5ea..676ef20d988 100644 --- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/internal/dynalink/beans/BeanLinker.java +++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/internal/dynalink/beans/BeanLinker.java @@ -156,14 +156,14 @@ class BeanLinker extends AbstractJavaLinker implements TypeBasedGuardingDynamicL return null; } - private static MethodHandle GET_LIST_ELEMENT = Lookup.PUBLIC.findVirtual(List.class, "get", + private static final MethodHandle GET_LIST_ELEMENT = Lookup.PUBLIC.findVirtual(List.class, "get", MethodType.methodType(Object.class, int.class)); - private static MethodHandle GET_MAP_ELEMENT = Lookup.PUBLIC.findVirtual(Map.class, "get", + private static final MethodHandle GET_MAP_ELEMENT = Lookup.PUBLIC.findVirtual(Map.class, "get", MethodType.methodType(Object.class, Object.class)); - private static MethodHandle LIST_GUARD = Guards.getInstanceOfGuard(List.class); - private static MethodHandle MAP_GUARD = Guards.getInstanceOfGuard(Map.class); + private static final MethodHandle LIST_GUARD = Guards.getInstanceOfGuard(List.class); + private static final MethodHandle MAP_GUARD = Guards.getInstanceOfGuard(Map.class); private enum CollectionType { ARRAY, LIST, MAP @@ -287,7 +287,7 @@ class BeanLinker extends AbstractJavaLinker implements TypeBasedGuardingDynamicL if(intIndex != doubleValue && !Double.isInfinite(doubleValue)) { // let infinites trigger IOOBE return null; // not an exact integer } - return Integer.valueOf(intIndex); + return intIndex; } catch(Exception|Error e) { throw e; } catch(final Throwable t) { @@ -343,9 +343,9 @@ class BeanLinker extends AbstractJavaLinker implements TypeBasedGuardingDynamicL } } - private static MethodHandle RANGE_CHECK_ARRAY = findRangeCheck(Object.class); - private static MethodHandle RANGE_CHECK_LIST = findRangeCheck(List.class); - private static MethodHandle CONTAINS_MAP = Lookup.PUBLIC.findVirtual(Map.class, "containsKey", + private static final MethodHandle RANGE_CHECK_ARRAY = findRangeCheck(Object.class); + private static final MethodHandle RANGE_CHECK_LIST = findRangeCheck(List.class); + private static final MethodHandle CONTAINS_MAP = Lookup.PUBLIC.findVirtual(Map.class, "containsKey", MethodType.methodType(boolean.class, Object.class)); private static MethodHandle findRangeCheck(final Class collectionType) { @@ -353,7 +353,7 @@ class BeanLinker extends AbstractJavaLinker implements TypeBasedGuardingDynamicL } @SuppressWarnings("unused") - private static final boolean rangeCheck(final Object array, final Object index) { + private static boolean rangeCheck(final Object array, final Object index) { if(!(index instanceof Number)) { return false; } @@ -370,7 +370,7 @@ class BeanLinker extends AbstractJavaLinker implements TypeBasedGuardingDynamicL } @SuppressWarnings("unused") - private static final boolean rangeCheck(final List list, final Object index) { + private static boolean rangeCheck(final List list, final Object index) { if(!(index instanceof Number)) { return false; } @@ -386,10 +386,10 @@ class BeanLinker extends AbstractJavaLinker implements TypeBasedGuardingDynamicL throw new IndexOutOfBoundsException("Index: " + n + ", Size: " + list.size()); } - private static MethodHandle SET_LIST_ELEMENT = Lookup.PUBLIC.findVirtual(List.class, "set", + private static final MethodHandle SET_LIST_ELEMENT = Lookup.PUBLIC.findVirtual(List.class, "set", MethodType.methodType(Object.class, int.class, Object.class)); - private static MethodHandle PUT_MAP_ELEMENT = Lookup.PUBLIC.findVirtual(Map.class, "put", + private static final MethodHandle PUT_MAP_ELEMENT = Lookup.PUBLIC.findVirtual(Map.class, "put", MethodType.methodType(Object.class, Object.class, Object.class)); private GuardedInvocationComponent getElementSetter(final CallSiteDescriptor callSiteDescriptor, @@ -471,16 +471,16 @@ class BeanLinker extends AbstractJavaLinker implements TypeBasedGuardingDynamicL gic.getValidatorClass(), gic.getValidationType()); } - private static MethodHandle GET_ARRAY_LENGTH = Lookup.PUBLIC.findStatic(Array.class, "getLength", + private static final MethodHandle GET_ARRAY_LENGTH = Lookup.PUBLIC.findStatic(Array.class, "getLength", MethodType.methodType(int.class, Object.class)); - private static MethodHandle GET_COLLECTION_LENGTH = Lookup.PUBLIC.findVirtual(Collection.class, "size", + private static final MethodHandle GET_COLLECTION_LENGTH = Lookup.PUBLIC.findVirtual(Collection.class, "size", MethodType.methodType(int.class)); - private static MethodHandle GET_MAP_LENGTH = Lookup.PUBLIC.findVirtual(Map.class, "size", + private static final MethodHandle GET_MAP_LENGTH = Lookup.PUBLIC.findVirtual(Map.class, "size", MethodType.methodType(int.class)); - private static MethodHandle COLLECTION_GUARD = Guards.getInstanceOfGuard(Collection.class); + private static final MethodHandle COLLECTION_GUARD = Guards.getInstanceOfGuard(Collection.class); private GuardedInvocationComponent getLengthGetter(final CallSiteDescriptor callSiteDescriptor) { assertParameterCount(callSiteDescriptor, 1); diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/internal/dynalink/support/NameCodec.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/internal/dynalink/support/NameCodec.java index 9a402a59825..5fc84d34370 100644 --- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/internal/dynalink/support/NameCodec.java +++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/internal/dynalink/support/NameCodec.java @@ -164,7 +164,7 @@ public class NameCodec { } } if(b == null) { - return name.toString(); + return name; } assert lastEscape != -1; b.append(name, lastEscape + 1, l); diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/internal/dynalink/support/TypeConverterFactory.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/internal/dynalink/support/TypeConverterFactory.java index 736b787c145..a3b554229f1 100644 --- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/internal/dynalink/support/TypeConverterFactory.java +++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/internal/dynalink/support/TypeConverterFactory.java @@ -166,7 +166,7 @@ public class TypeConverterFactory { } }; - private static final ClassLoader getClassLoader(final Class clazz) { + private static ClassLoader getClassLoader(final Class clazz) { return AccessController.doPrivileged(new PrivilegedAction() { @Override public ClassLoader run() { @@ -298,7 +298,7 @@ public class TypeConverterFactory { * @return true if there can be a conversion, false if there can not. */ public boolean canConvert(final Class from, final Class to) { - return canAutoConvert(from, to) || canConvert.get(from).get(to).booleanValue(); + return canAutoConvert(from, to) || canConvert.get(from).get(to); } /** diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/api/scripting/Formatter.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/api/scripting/Formatter.java index 544e70ce452..2cacbb581d8 100644 --- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/api/scripting/Formatter.java +++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/api/scripting/Formatter.java @@ -170,7 +170,7 @@ final class Formatter { * @return true if '<' is in the string, else false */ private static boolean isPreviousArgument(final String s) { - return (s != null && s.indexOf('<') >= 0) ? true : false; + return (s != null && s.indexOf('<') >= 0); } // %[argument_index$][flags][width][.precision][t]conversion diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/codegen/ClassEmitter.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/codegen/ClassEmitter.java index 577504dc816..c01ddcb644c 100644 --- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/codegen/ClassEmitter.java +++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/codegen/ClassEmitter.java @@ -705,7 +705,7 @@ public class ClassEmitter { /** private access */ PRIVATE(ACC_PRIVATE); - private int value; + private final int value; private Flag(final int value) { this.value = value; diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/codegen/CodeGenerator.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/codegen/CodeGenerator.java index b9ad1e9bfce..2651cc6f696 100644 --- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/codegen/CodeGenerator.java +++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/codegen/CodeGenerator.java @@ -213,7 +213,7 @@ final class CodeGenerator extends NodeOperatorVisitor, Serializable private transient Class clazz; - private transient Map functions = new IdentityHashMap<>(); + private final transient Map functions = new IdentityHashMap<>(); private transient boolean isUsed; diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/codegen/Compiler.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/codegen/Compiler.java index 9b1828b138b..ccfbcd33637 100644 --- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/codegen/Compiler.java +++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/codegen/Compiler.java @@ -437,7 +437,7 @@ public final class Compiler implements Loggable { baseName = baseName.replace('.', '_').replace('-', '_'); if (!env._loader_per_compile) { - baseName = baseName + installer.getUniqueScriptId(); + baseName += installer.getUniqueScriptId(); } // ASM's bytecode verifier does not allow JVM allowed safe escapes using '\' as escape char. diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/codegen/ConstantData.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/codegen/ConstantData.java index a7e6653945a..91faea87440 100644 --- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/codegen/ConstantData.java +++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/codegen/ConstantData.java @@ -162,7 +162,7 @@ final class ConstantData { final Integer value = stringMap.get(string); if (value != null) { - return value.intValue(); + return value; } constants.add(string); @@ -191,7 +191,7 @@ final class ConstantData { final Integer value = objectMap.get(entry); if (value != null) { - return value.intValue(); + return value; } constants.add(object); diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/codegen/DumpBytecode.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/codegen/DumpBytecode.java index 620a43e5764..55de3405628 100644 --- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/codegen/DumpBytecode.java +++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/codegen/DumpBytecode.java @@ -51,7 +51,7 @@ public final class DumpBytecode { if (env._print_code) { final StringBuilder sb = new StringBuilder(); - sb.append("class: " + className). + sb.append("class: ").append(className). append('\n'). append(ClassEmitter.disassemble(bytecode)). append("====="); diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/codegen/FindScopeDepths.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/codegen/FindScopeDepths.java index 9f9abf9c0c9..cf4894d01dc 100644 --- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/codegen/FindScopeDepths.java +++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/codegen/FindScopeDepths.java @@ -121,11 +121,9 @@ final class FindScopeDepths extends NodeVisitor implements Logga private static boolean definedInBlock(final Block block, final Symbol symbol) { if (symbol.isGlobal()) { - if (block.isGlobalScope()) { - return true; - } //globals cannot be defined anywhere else - return false; + + return block.isGlobalScope(); } return block.getExistingSymbol(symbol.getName()) == symbol; } diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/codegen/LocalVariableTypesCalculator.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/codegen/LocalVariableTypesCalculator.java index 2645f24423e..c17edcc0f16 100644 --- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/codegen/LocalVariableTypesCalculator.java +++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/codegen/LocalVariableTypesCalculator.java @@ -272,12 +272,12 @@ final class LocalVariableTypesCalculator extends NodeVisitor{ } private static class SymbolConversions { - private static byte I2L = 1 << 0; - private static byte I2D = 1 << 1; - private static byte I2O = 1 << 2; - private static byte L2D = 1 << 3; - private static byte L2O = 1 << 4; - private static byte D2O = 1 << 5; + private static final byte I2L = 1 << 0; + private static final byte I2D = 1 << 1; + private static final byte I2O = 1 << 2; + private static final byte L2D = 1 << 3; + private static final byte L2O = 1 << 4; + private static final byte D2O = 1 << 5; private byte conversions; diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/codegen/Lower.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/codegen/Lower.java index 294eee39b4e..eac6deca254 100644 --- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/codegen/Lower.java +++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/codegen/Lower.java @@ -101,7 +101,7 @@ final class Lower extends NodeOperatorVisitor implements Lo // Conservative pattern to test if element names consist of characters valid for identifiers. // This matches any non-zero length alphanumeric string including _ and $ and not starting with a digit. - private static Pattern SAFE_PROPERTY_NAME = Pattern.compile("[a-zA-Z_$][\\w$]*"); + private static final Pattern SAFE_PROPERTY_NAME = Pattern.compile("[a-zA-Z_$][\\w$]*"); /** * Constructor. diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/codegen/types/IntType.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/codegen/types/IntType.java index 43b068064e3..1aed2011dc1 100644 --- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/codegen/types/IntType.java +++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/codegen/types/IntType.java @@ -89,7 +89,7 @@ class IntType extends BitwiseType { public Type ldc(final MethodVisitor method, final Object c) { assert c instanceof Integer; - final int value = ((Integer) c).intValue(); + final int value = ((Integer) c); switch (value) { case -1: diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/ir/debug/NashornClassReader.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/ir/debug/NashornClassReader.java index 87eb18df73c..9d478fb023c 100644 --- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/ir/debug/NashornClassReader.java +++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/ir/debug/NashornClassReader.java @@ -88,7 +88,7 @@ public class NashornClassReader extends ClassReader { c = bytecode[i++]; switch (st) { case 0: - c = c & 0xFF; + c &= 0xFF; if (c < 0x80) { // 0xxxxxxx buf[strLen++] = (char) c; } else if (c < 0xE0 && c > 0xBF) { // 110x xxxx 10xx xxxx @@ -457,7 +457,7 @@ public class NashornClassReader extends ClassReader { @SuppressWarnings("unused") final String getType() { - String str = type[tag]; + String str = TYPE[tag]; while (str.length() < 16) { str += " "; } @@ -507,7 +507,7 @@ public class NashornClassReader extends ClassReader { } } - private static String type[] = { + private static final String[] TYPE = { //0 "", //1 diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/ir/debug/NashornTextifier.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/ir/debug/NashornTextifier.java index c5dc56bf26f..9b4f014aa24 100644 --- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/ir/debug/NashornTextifier.java +++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/ir/debug/NashornTextifier.java @@ -535,7 +535,7 @@ public final class NashornTextifier extends Printer { addText(sb); } - private static final boolean noFallThru(final int opcode) { + private static boolean noFallThru(final int opcode) { switch (opcode) { case Opcodes.GOTO: case Opcodes.ATHROW: @@ -901,7 +901,7 @@ public final class NashornTextifier extends Printer { appendDescriptor(sb, INTERNAL_NAME, desc); } } else if (o[i] instanceof Integer) { - switch (((Integer)o[i]).intValue()) { + switch (((Integer)o[i])) { case 0: appendDescriptor(sb, FIELD_DESCRIPTOR, "T"); break; @@ -1090,7 +1090,7 @@ public final class NashornTextifier extends Printer { public String toString() { final StringBuilder sb = new StringBuilder(); - sb.append("digraph " + dottyFriendly(name) + " {"); + sb.append("digraph ").append(dottyFriendly(name)).append(" {"); sb.append("\n"); sb.append("\tgraph [fontname=courier]\n"); sb.append("\tnode [style=filled,color="+COLOR_DEFAULT+",fontname=courier]\n"); diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/ir/debug/ObjectSizeCalculator.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/ir/debug/ObjectSizeCalculator.java index 54fcc597e3a..bd35436ba36 100644 --- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/ir/debug/ObjectSizeCalculator.java +++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/ir/debug/ObjectSizeCalculator.java @@ -450,7 +450,7 @@ public final class ObjectSizeCalculator { for (final Object mp : memoryPoolMXBeans) { final Object usage = getUsage.invoke(mp); final Object max = getMax.invoke(usage); - maxMemory += ((Long)max).longValue(); + maxMemory += ((Long)max); } } catch (IllegalAccessException | IllegalArgumentException | diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/NativeArray.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/NativeArray.java index 9d9790e4cef..4734e048710 100644 --- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/NativeArray.java +++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/NativeArray.java @@ -1874,7 +1874,7 @@ public final class NativeArray extends ScriptObject implements OptimisticBuiltin //TODO - fold these into the Link logics, but I'll do that as a later step, as I want to do a checkin //where everything works first - private static final ContinuousArrayData getContinuousNonEmptyArrayDataCCE(final Object self, final Class clazz) { + private static ContinuousArrayData getContinuousNonEmptyArrayDataCCE(final Object self, final Class clazz) { try { @SuppressWarnings("unchecked") final ContinuousArrayData data = (ContinuousArrayData)(T)((NativeArray)self).getArray(); @@ -1887,7 +1887,7 @@ public final class NativeArray extends ScriptObject implements OptimisticBuiltin throw new ClassCastException(); } - private static final ContinuousArrayData getContinuousArrayDataCCE(final Object self) { + private static ContinuousArrayData getContinuousArrayDataCCE(final Object self) { try { return (ContinuousArrayData)((NativeArray)self).getArray(); } catch (final NullPointerException e) { @@ -1895,7 +1895,7 @@ public final class NativeArray extends ScriptObject implements OptimisticBuiltin } } - private static final ContinuousArrayData getContinuousArrayDataCCE(final Object self, final Class elementType) { + private static ContinuousArrayData getContinuousArrayDataCCE(final Object self, final Class elementType) { try { return (ContinuousArrayData)((NativeArray)self).getArray(elementType); //ensure element type can fit "elementType" } catch (final NullPointerException e) { diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/NativeDate.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/NativeDate.java index 7462e4fb459..3d3f24899de 100644 --- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/NativeDate.java +++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/NativeDate.java @@ -218,7 +218,7 @@ public final class NativeDate extends ScriptObject { @Override public String toString() { - return isValidDate() ? toString(this).toString() : INVALID_DATE; + return isValidDate() ? toString(this) : INVALID_DATE; } /** diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/NativeRegExp.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/NativeRegExp.java index 62ef4835c61..caea1ef98ca 100644 --- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/NativeRegExp.java +++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/NativeRegExp.java @@ -803,7 +803,7 @@ public final class NativeRegExp extends ScriptObject { private static final Object REPLACE_VALUE = new Object(); - private static final MethodHandle getReplaceValueInvoker() { + private static MethodHandle getReplaceValueInvoker() { return Global.instance().getDynamicInvoker(REPLACE_VALUE, new Callable() { @Override diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/parser/Lexer.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/parser/Lexer.java index 7714d49f894..3528ab6a419 100644 --- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/parser/Lexer.java +++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/parser/Lexer.java @@ -1044,9 +1044,9 @@ public class Lexer extends Scanner { try { final long value = Long.parseLong(valueString, radix); if(value >= MIN_INT_L && value <= MAX_INT_L) { - return Integer.valueOf((int)value); + return (int)value; } - return Long.valueOf(value); + return value; } catch (final NumberFormatException e) { if (radix == 10) { return Double.valueOf(valueString); diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/JSType.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/JSType.java index 6350f0818d7..53446a43b8d 100644 --- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/JSType.java +++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/JSType.java @@ -994,7 +994,7 @@ public enum JSType { * @return a long */ public static long toLong(final Object obj) { - return obj instanceof Long ? ((Long)obj).longValue() : toLong(toNumber(obj)); + return obj instanceof Long ? ((Long)obj) : toLong(toNumber(obj)); } /** @@ -1056,7 +1056,7 @@ public enum JSType { */ public static int toInt32Optimistic(final Object obj, final int programPoint) { if (obj != null && obj.getClass() == Integer.class) { - return ((Integer)obj).intValue(); + return ((Integer)obj); } throw new UnwarrantedOptimismException(obj, programPoint); } @@ -1954,11 +1954,11 @@ public enum JSType { public static MethodHandle unboxConstant(final Object o) { if (o != null) { if (o.getClass() == Integer.class) { - return MH.constant(int.class, ((Integer)o).intValue()); + return MH.constant(int.class, ((Integer)o)); } else if (o.getClass() == Long.class) { - return MH.constant(long.class, ((Long)o).longValue()); + return MH.constant(long.class, ((Long)o)); } else if (o.getClass() == Double.class) { - return MH.constant(double.class, ((Double)o).doubleValue()); + return MH.constant(double.class, ((Double)o)); } } return MH.constant(Object.class, o); @@ -1983,7 +1983,7 @@ public enum JSType { } } - private static final List toUnmodifiableList(final MethodHandle... methodHandles) { + private static List toUnmodifiableList(final MethodHandle... methodHandles) { return Collections.unmodifiableList(Arrays.asList(methodHandles)); } } diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/NashornLoader.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/NashornLoader.java index 423b87dbb37..82e37c3234e 100644 --- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/NashornLoader.java +++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/NashornLoader.java @@ -156,7 +156,7 @@ abstract class NashornLoader extends SecureClassLoader { } // If the file does not exist, then assume that it's a directory if (!file.isFile()) { - name = name + "/"; + name += "/"; } try { return new URL("file", "", name); diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/OptimisticReturnFilters.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/OptimisticReturnFilters.java index 9b538630a09..039a0da12b1 100644 --- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/OptimisticReturnFilters.java +++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/OptimisticReturnFilters.java @@ -260,7 +260,7 @@ public final class OptimisticReturnFilters { final Class c = arg.getClass(); if (c == Long.class) { // Must check for Long separately, as Long.doubleValue() isn't precise. - return ((Long)arg).longValue(); + return ((Long)arg); } else if (c == Integer.class || c == Double.class || c == Float.class || c == Short.class || c == Byte.class) { return ensureLong(((Number)arg).doubleValue(), programPoint); diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/RewriteException.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/RewriteException.java index 4c0e0a3a7c6..690d7005b6a 100644 --- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/RewriteException.java +++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/RewriteException.java @@ -359,9 +359,9 @@ public final class RewriteException extends Exception { if (returnValue instanceof String) { str = '\'' + str + '\''; } else if (returnValue instanceof Double) { - str = str + 'd'; + str += 'd'; } else if (returnValue instanceof Long) { - str = str + 'l'; + str += 'l'; } return str; } diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/ScriptRuntime.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/ScriptRuntime.java index 49109dacef9..6bb7aec26d5 100644 --- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/ScriptRuntime.java +++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/ScriptRuntime.java @@ -611,7 +611,7 @@ public final class ScriptRuntime { obj = ((ScriptObject)obj).get(property); if(Global.isLocationPropertyPlaceholder(obj)) { if(CompilerConstants.__LINE__.name().equals(property)) { - obj = Integer.valueOf(0); + obj = 0; } else { obj = ""; } diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/Source.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/Source.java index df8da96a066..99a4bf2de6c 100644 --- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/Source.java +++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/Source.java @@ -1031,7 +1031,7 @@ public final class Source implements Loggable { ": " + ECMAErrors.getMessage( "io.error.cant.write", - dir.toString() + + dir + " : " + ioExp.toString())); } } diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/arrays/ContinuousArrayData.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/arrays/ContinuousArrayData.java index e892f9fc139..e4466cc7592 100644 --- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/arrays/ContinuousArrayData.java +++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/arrays/ContinuousArrayData.java @@ -215,11 +215,8 @@ public abstract class ContinuousArrayData extends ArrayData { int.class); @SuppressWarnings("unused") - private static final boolean guard(final Class clazz, final ScriptObject sobj) { - if (sobj != null && sobj.getArray().getClass() == clazz) { - return true; - } - return false; + private static boolean guard(final Class clazz, final ScriptObject sobj) { + return sobj != null && sobj.getArray().getClass() == clazz; } /** diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/arrays/IntArrayData.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/arrays/IntArrayData.java index 0cba79f23ee..87862cf902b 100644 --- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/arrays/IntArrayData.java +++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/arrays/IntArrayData.java @@ -138,7 +138,7 @@ final class IntArrayData extends ContinuousArrayData implements IntElements { final Object[] oarray = new Object[trim ? len : array.length]; for (int index = 0; index < len; index++) { - oarray[index] = Integer.valueOf(array[index]); + oarray[index] = array[index]; } return oarray; diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/arrays/LongArrayData.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/arrays/LongArrayData.java index 544f883b4e2..6e668c906cb 100644 --- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/arrays/LongArrayData.java +++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/arrays/LongArrayData.java @@ -91,7 +91,7 @@ final class LongArrayData extends ContinuousArrayData implements IntOrLongElemen final Object[] oarray = new Object[trim ? len : array.length]; for (int index = 0; index < len; index++) { - oarray[index] = Long.valueOf(array[index]); + oarray[index] = array[index]; } return oarray; diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/arrays/NumberArrayData.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/arrays/NumberArrayData.java index 0ff1af88dc1..8b385fa74e5 100644 --- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/arrays/NumberArrayData.java +++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/arrays/NumberArrayData.java @@ -91,7 +91,7 @@ final class NumberArrayData extends ContinuousArrayData implements NumericElemen final Object[] oarray = new Object[trim ? len : array.length]; for (int index = 0; index < len; index++) { - oarray[index] = Double.valueOf(array[index]); + oarray[index] = array[index]; } return oarray; } diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/arrays/SparseArrayData.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/arrays/SparseArrayData.java index ede8d877608..4c587b8d111 100644 --- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/arrays/SparseArrayData.java +++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/arrays/SparseArrayData.java @@ -95,11 +95,11 @@ class SparseArrayData extends ArrayData { final TreeMap newSparseMap = new TreeMap<>(); for (final Map.Entry entry : sparseMap.entrySet()) { - final long newIndex = entry.getKey().longValue() - by; + final long newIndex = entry.getKey() - by; if (newIndex < maxDenseLength) { underlying = underlying.set((int) newIndex, entry.getValue(), false); } else if (newIndex >= 0) { - newSparseMap.put(Long.valueOf(newIndex), entry.getValue()); + newSparseMap.put(newIndex, entry.getValue()); } } @@ -114,7 +114,7 @@ class SparseArrayData extends ArrayData { if (len + by > maxDenseLength) { for (long i = maxDenseLength - by; i < len; i++) { if (underlying.has((int) i)) { - newSparseMap.put(Long.valueOf(i + by), underlying.getObject((int) i)); + newSparseMap.put(i + by, underlying.getObject((int) i)); } } underlying = underlying.shrink((int) (maxDenseLength - by)); @@ -123,8 +123,8 @@ class SparseArrayData extends ArrayData { underlying.shiftRight(by); for (final Map.Entry entry : sparseMap.entrySet()) { - final long newIndex = entry.getKey().longValue() + by; - newSparseMap.put(Long.valueOf(newIndex), entry.getValue()); + final long newIndex = entry.getKey() + by; + newSparseMap.put(newIndex, entry.getValue()); } sparseMap = newSparseMap; @@ -158,7 +158,7 @@ class SparseArrayData extends ArrayData { setLength(newLength); } - sparseMap.subMap(Long.valueOf(newLength), Long.MAX_VALUE).clear(); + sparseMap.subMap(newLength, Long.MAX_VALUE).clear(); setLength(newLength); return this; } @@ -333,7 +333,7 @@ class SparseArrayData extends ArrayData { } private static Long indexToKey(final int index) { - return Long.valueOf(ArrayIndex.toLongIndex(index)); + return ArrayIndex.toLongIndex(index); } @Override @@ -355,7 +355,7 @@ class SparseArrayData extends ArrayData { return result; } setLength(len - 1); - final Long key = Long.valueOf(len - 1); + final Long key = len - 1; return sparseMap.containsKey(key) ? sparseMap.remove(key) : ScriptRuntime.UNDEFINED; } diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/linker/Bootstrap.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/linker/Bootstrap.java index 9cdf6d5c352..f9d99501c43 100644 --- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/linker/Bootstrap.java +++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/linker/Bootstrap.java @@ -47,7 +47,6 @@ import jdk.internal.dynalink.linker.MethodTypeConversionStrategy; import jdk.internal.dynalink.support.TypeUtilities; import jdk.nashorn.api.scripting.JSObject; import jdk.nashorn.internal.codegen.CompilerConstants.Call; -import jdk.nashorn.internal.codegen.ObjectClassGenerator; import jdk.nashorn.internal.lookup.MethodHandleFactory; import jdk.nashorn.internal.lookup.MethodHandleFunctionality; import jdk.nashorn.internal.objects.ScriptFunctionImpl; diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/linker/JavaArgumentConverters.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/linker/JavaArgumentConverters.java index e1656440226..30566e29219 100644 --- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/linker/JavaArgumentConverters.java +++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/linker/JavaArgumentConverters.java @@ -107,7 +107,7 @@ final class JavaArgumentConverters { if (o instanceof Number) { final int ival = ((Number)o).intValue(); if (ival >= Character.MIN_VALUE && ival <= Character.MAX_VALUE) { - return Character.valueOf((char) ival); + return (char) ival; } throw typeError("cant.convert.number.to.char"); @@ -196,13 +196,13 @@ final class JavaArgumentConverters { return ((Integer)obj).longValue(); } else if (obj instanceof Double) { final Double d = (Double)obj; - if(Double.isInfinite(d.doubleValue())) { + if(Double.isInfinite(d)) { return 0L; } return d.longValue(); } else if (obj instanceof Float) { final Float f = (Float)obj; - if(Float.isInfinite(f.floatValue())) { + if(Float.isInfinite(f)) { return 0L; } return f.longValue(); diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/regexp/joni/BitSet.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/regexp/joni/BitSet.java index 2747c24cb8f..db6df11893e 100644 --- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/regexp/joni/BitSet.java +++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/regexp/joni/BitSet.java @@ -101,9 +101,7 @@ public final class BitSet { } public void copy(final BitSet other) { - for (int i=0; i"); + s.append("<").append(getAddressName()).append(" (").append(parent == null ? "NULL" : parent.getAddressName()).append(")>"); return s + toString(0); } diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/regexp/joni/ast/QuantifierNode.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/regexp/joni/ast/QuantifierNode.java index d4be3780747..6a28f78acdd 100644 --- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/regexp/joni/ast/QuantifierNode.java +++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/regexp/joni/ast/QuantifierNode.java @@ -118,14 +118,14 @@ public final class QuantifierNode extends StateNode { @Override public String toString(final int level) { final StringBuilder value = new StringBuilder(super.toString(level)); - value.append("\n target: " + pad(target, level + 1)); - value.append("\n lower: " + lower); - value.append("\n upper: " + upper); - value.append("\n greedy: " + greedy); - value.append("\n targetEmptyInfo: " + targetEmptyInfo); - value.append("\n headExact: " + pad(headExact, level + 1)); - value.append("\n nextHeadExact: " + pad(nextHeadExact, level + 1)); - value.append("\n isRefered: " + isRefered); + value.append("\n target: ").append(pad(target, level + 1)); + value.append("\n lower: ").append(lower); + value.append("\n upper: ").append(upper); + value.append("\n greedy: ").append(greedy); + value.append("\n targetEmptyInfo: ").append(targetEmptyInfo); + value.append("\n headExact: ").append(pad(headExact, level + 1)); + value.append("\n nextHeadExact: ").append(pad(nextHeadExact, level + 1)); + value.append("\n isRefered: ").append(isRefered); return value.toString(); } diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/regexp/joni/ast/StringNode.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/regexp/joni/ast/StringNode.java index 985c95e6f3c..0d7f94a9baa 100644 --- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/regexp/joni/ast/StringNode.java +++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/regexp/joni/ast/StringNode.java @@ -71,7 +71,7 @@ public final class StringNode extends Node implements StringType { final char[] tmp = new char[len + NODE_STR_MARGIN]; System.arraycopy(chars, p, tmp, 0, end - p); chars = tmp; - end = end - p; + end -= p; p = 0; clearShared(); } else { diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/tools/Shell.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/tools/Shell.java index f8747b2a392..3d2a67172eb 100644 --- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/tools/Shell.java +++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/tools/Shell.java @@ -54,7 +54,6 @@ import jdk.nashorn.internal.runtime.Property; import jdk.nashorn.internal.runtime.ScriptEnvironment; import jdk.nashorn.internal.runtime.ScriptFunction; import jdk.nashorn.internal.runtime.ScriptRuntime; -import jdk.nashorn.internal.runtime.Source; import jdk.nashorn.internal.runtime.options.Options; /** diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/tools/ShellFunctions.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/tools/ShellFunctions.java index 0c4e4cb016d..6b3e1791357 100644 --- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/tools/ShellFunctions.java +++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/tools/ShellFunctions.java @@ -29,10 +29,8 @@ import static jdk.nashorn.internal.lookup.Lookup.MH; import static jdk.nashorn.internal.runtime.ScriptRuntime.UNDEFINED; import java.io.BufferedReader; -import java.io.File; import java.io.IOException; import java.io.InputStreamReader; -import java.io.OutputStreamWriter; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; import jdk.nashorn.internal.runtime.JSType; diff --git a/nashorn/test/src/jdk/nashorn/api/javaaccess/test/SharedObject.java b/nashorn/test/src/jdk/nashorn/api/javaaccess/test/SharedObject.java index 3c41ac101b2..d47b6f2e0b4 100644 --- a/nashorn/test/src/jdk/nashorn/api/javaaccess/test/SharedObject.java +++ b/nashorn/test/src/jdk/nashorn/api/javaaccess/test/SharedObject.java @@ -176,7 +176,7 @@ public class SharedObject { } public Boolean booleanBoxingMethod(final Boolean arg) { - return !arg.booleanValue(); + return !arg; } public boolean[] booleanArrayMethod(final boolean arg[]) { diff --git a/nashorn/test/src/jdk/nashorn/api/scripting/test/ScriptEngineTest.java b/nashorn/test/src/jdk/nashorn/api/scripting/test/ScriptEngineTest.java index 3b683e2d24b..b31add79019 100644 --- a/nashorn/test/src/jdk/nashorn/api/scripting/test/ScriptEngineTest.java +++ b/nashorn/test/src/jdk/nashorn/api/scripting/test/ScriptEngineTest.java @@ -573,7 +573,7 @@ public class ScriptEngineTest { } // properties that can be read by any code - private static String[] propNames = { + private static final String[] PROP_NAMES = { "java.version", "java.vendor", "java.vendor.url", @@ -601,7 +601,7 @@ public class ScriptEngineTest { final ScriptEngineManager m = new ScriptEngineManager(); final ScriptEngine e = m.getEngineByName("nashorn"); - for (final String name : propNames) { + for (final String name : PROP_NAMES) { checkProperty(e, name); } } diff --git a/nashorn/test/src/jdk/nashorn/api/scripting/test/ScriptObjectMirrorTest.java b/nashorn/test/src/jdk/nashorn/api/scripting/test/ScriptObjectMirrorTest.java index f16ceb92ac7..4a0e262915f 100644 --- a/nashorn/test/src/jdk/nashorn/api/scripting/test/ScriptObjectMirrorTest.java +++ b/nashorn/test/src/jdk/nashorn/api/scripting/test/ScriptObjectMirrorTest.java @@ -278,7 +278,7 @@ public class ScriptObjectMirrorTest { ScriptObjectMirror obj = (ScriptObjectMirror)e.eval( "({ valueOf: function() { return 42 } })"); - assertEquals(Double.valueOf(42.0), obj.to(Double.class)); + assertEquals(42.0, obj.to(Double.class)); obj = (ScriptObjectMirror)e.eval( "({ toString: function() { return 'foo' } })"); diff --git a/nashorn/test/src/jdk/nashorn/api/tree/test/ParseAPITest.java b/nashorn/test/src/jdk/nashorn/api/tree/test/ParseAPITest.java index 00504d93cd6..eb668067f2d 100644 --- a/nashorn/test/src/jdk/nashorn/api/tree/test/ParseAPITest.java +++ b/nashorn/test/src/jdk/nashorn/api/tree/test/ParseAPITest.java @@ -67,7 +67,7 @@ public class ParseAPITest { parseTestSet(TEST262_SUITE_DIR, new TestFilter() { @Override public boolean exclude(final File file, final String content) { - return content.indexOf("@negative") != -1; + return content.contains("@negative"); } }); } diff --git a/nashorn/test/src/jdk/nashorn/internal/performance/OctaneTest.java b/nashorn/test/src/jdk/nashorn/internal/performance/OctaneTest.java index 102ffc1a531..cbb016f5a6b 100644 --- a/nashorn/test/src/jdk/nashorn/internal/performance/OctaneTest.java +++ b/nashorn/test/src/jdk/nashorn/internal/performance/OctaneTest.java @@ -272,10 +272,10 @@ public class OctaneTest { Double nashornToRhino = null; Double nashornToV8 = null; if (rhino != null && rhino != 0) { - nashornToRhino = nashorn.doubleValue() / rhino.doubleValue(); + nashornToRhino = nashorn / rhino; } if (v8 != null && rhino != 0) { - nashornToV8 = nashorn.doubleValue() / v8.doubleValue(); + nashornToV8 = nashorn / v8; } final String normalizedBenchmark=benchmark.replace("-", ""); System.out.println("benchmark-" + normalizedBenchmark + "-nashorn=" + nashorn); @@ -300,20 +300,12 @@ public class OctaneTest { boolean checkRhinoPresence() { final String rhinojar = System.getProperty("rhino.jar"); - if (rhinojar != null) { - // System.out.println("Rhino jar found; performing comparison testing"); - return true; - } - return false; + return rhinojar != null; } boolean checkV8Presence() { final String v8shell = System.getProperty("v8.shell.full.path"); - if (v8shell != null) { - // System.out.println("d8 found; performing comparison testing"); - return true; - } - return false; + return v8shell != null; } } diff --git a/nashorn/test/src/jdk/nashorn/internal/runtime/test/ExceptionsNotSerializable.java b/nashorn/test/src/jdk/nashorn/internal/runtime/test/ExceptionsNotSerializable.java index 3cb27ad09b1..2f498af3cbc 100644 --- a/nashorn/test/src/jdk/nashorn/internal/runtime/test/ExceptionsNotSerializable.java +++ b/nashorn/test/src/jdk/nashorn/internal/runtime/test/ExceptionsNotSerializable.java @@ -62,7 +62,7 @@ public class ExceptionsNotSerializable { @Test public void unwarrantedOptimismExceptionNotSerializable() { - tryToSerialize(new UnwarrantedOptimismException(new Double(1.0), 128)); + tryToSerialize(new UnwarrantedOptimismException(1.0, 128)); } private static void tryToSerialize(final Object obj) { diff --git a/nashorn/test/src/jdk/nashorn/internal/test/framework/AbstractScriptRunnable.java b/nashorn/test/src/jdk/nashorn/internal/test/framework/AbstractScriptRunnable.java index e8ca191da1f..4e59f0fdf60 100644 --- a/nashorn/test/src/jdk/nashorn/internal/test/framework/AbstractScriptRunnable.java +++ b/nashorn/test/src/jdk/nashorn/internal/test/framework/AbstractScriptRunnable.java @@ -159,7 +159,7 @@ public abstract class AbstractScriptRunnable { forkJVMOptions = (vmOptions != null)? vmOptions.split(" ") : new String[0]; } - private static ThreadLocal evaluators = new ThreadLocal<>(); + private static final ThreadLocal EVALUATORS = new ThreadLocal<>(); /** * Create a script evaluator or return from cache @@ -167,7 +167,7 @@ public abstract class AbstractScriptRunnable { */ protected ScriptEvaluator getEvaluator() { synchronized (AbstractScriptRunnable.class) { - ScriptEvaluator evaluator = evaluators.get(); + ScriptEvaluator evaluator = EVALUATORS.get(); if (evaluator == null) { if (sharedContext) { final String[] args; @@ -177,10 +177,10 @@ public abstract class AbstractScriptRunnable { args = new String[] { framework }; } evaluator = new SharedContextEvaluator(args); - evaluators.set(evaluator); + EVALUATORS.set(evaluator); } else { evaluator = new SeparateContextEvaluator(); - evaluators.set(evaluator); + EVALUATORS.set(evaluator); } } return evaluator; diff --git a/nashorn/test/src/jdk/nashorn/internal/test/framework/TestFinder.java b/nashorn/test/src/jdk/nashorn/internal/test/framework/TestFinder.java index 900a21a68ac..fa5ef573ae7 100644 --- a/nashorn/test/src/jdk/nashorn/internal/test/framework/TestFinder.java +++ b/nashorn/test/src/jdk/nashorn/internal/test/framework/TestFinder.java @@ -378,7 +378,7 @@ public final class TestFinder { * @return true if optimistic type override has been set by test suite */ public static boolean hasOptimisticOverride() { - return Boolean.valueOf(OPTIMISTIC_OVERRIDE).toString().equals(System.getProperty("optimistic.override")); + return Boolean.toString(OPTIMISTIC_OVERRIDE).equals(System.getProperty("optimistic.override")); } /** @@ -391,8 +391,8 @@ public final class TestFinder { public static String[] addExplicitOptimisticTypes(final String[] args) { if (hasOptimisticOverride()) { final List newList = new ArrayList<>(Arrays.asList(args)); - newList.add("--optimistic-types=" + Boolean.valueOf(OPTIMISTIC_OVERRIDE)); - return newList.toArray(new String[0]); + newList.add("--optimistic-types=" + OPTIMISTIC_OVERRIDE); + return newList.toArray(new String[newList.size()]); } return args; } @@ -405,7 +405,7 @@ public final class TestFinder { */ public static void addExplicitOptimisticTypes(final List args) { if (hasOptimisticOverride()) { - args.add("--optimistic-types=" + Boolean.valueOf(OPTIMISTIC_OVERRIDE)); + args.add("--optimistic-types=" + OPTIMISTIC_OVERRIDE); } } diff --git a/nashorn/test/src/jdk/nashorn/test/models/JDK_8081015_TestModel.java b/nashorn/test/src/jdk/nashorn/test/models/JDK_8081015_TestModel.java index 069bc1b2a50..e283e59cf99 100644 --- a/nashorn/test/src/jdk/nashorn/test/models/JDK_8081015_TestModel.java +++ b/nashorn/test/src/jdk/nashorn/test/models/JDK_8081015_TestModel.java @@ -64,9 +64,9 @@ public class JDK_8081015_TestModel { private static void walkCollection(final Collection c) { final Iterator it = c.iterator(); - assertEquals(it.next(), Integer.valueOf(1)); - assertEquals(it.next(), Integer.valueOf(2)); - assertEquals(it.next(), Double.valueOf(3.3)); + assertEquals(it.next(), 1); + assertEquals(it.next(), 2); + assertEquals(it.next(), 3.3); assertEquals(it.next(), "foo"); assertFalse(it.hasNext()); } From 7b64cba44ce726aa027ffb5dbecd840d1a239bfc Mon Sep 17 00:00:00 2001 From: Srikanth Adayapalam Date: Wed, 8 Jul 2015 19:01:57 +0530 Subject: [PATCH 26/43] 8130745: Revert fix pushed for JDK-8074346 Reviewed-by: jlahoda --- .../com/sun/tools/javac/comp/Attr.java | 18 +++++++------ .../com/sun/tools/javac/comp/Check.java | 25 ------------------- .../failures/CantAnnotatePackages.java | 6 ++--- .../failures/CantAnnotatePackages.out | 12 ++++----- .../typeAnnotations/failures/T8074346.java | 18 ------------- .../typeAnnotations/failures/T8074346.out | 3 --- 6 files changed, 18 insertions(+), 64 deletions(-) delete mode 100644 langtools/test/tools/javac/annotations/typeAnnotations/failures/T8074346.java delete mode 100644 langtools/test/tools/javac/annotations/typeAnnotations/failures/T8074346.out diff --git a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Attr.java b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Attr.java index 64ddd24e72c..892410f9986 100644 --- a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Attr.java +++ b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Attr.java @@ -4140,12 +4140,7 @@ public class Attr extends JCTree.Visitor { public void visitAnnotatedType(JCAnnotatedType tree) { attribAnnotationTypes(tree.annotations, env); - JCExpression underlyingTypeTree = tree.getUnderlyingType(); - Type underlyingType = attribTree(underlyingTypeTree, env, - new ResultInfo(KindSelector.TYP_PCK, Type.noType)); - if (!chk.checkAnnotableType(underlyingType, tree.annotations, underlyingTypeTree.pos())) { - underlyingType = underlyingTypeTree.type = syms.errType; - } + Type underlyingType = attribType(tree.underlyingType, env); Type annotatedType = underlyingType.annotatedType(Annotations.TO_BE_SET); if (!env.info.isNewClass) @@ -4636,7 +4631,16 @@ public class Attr extends JCTree.Visitor { } } else if (enclTr.hasTag(ANNOTATED_TYPE)) { JCAnnotatedType at = (JCTree.JCAnnotatedType) enclTr; - if (!chk.checkAnnotableType(enclTy, at.getAnnotations(), at.underlyingType.pos())) { + if (enclTy == null || enclTy.hasTag(NONE)) { + if (at.getAnnotations().size() == 1) { + log.error(at.underlyingType.pos(), "cant.type.annotate.scoping.1", at.getAnnotations().head.attribute); + } else { + ListBuffer comps = new ListBuffer<>(); + for (JCAnnotation an : at.getAnnotations()) { + comps.add(an.attribute); + } + log.error(at.underlyingType.pos(), "cant.type.annotate.scoping", comps.toList()); + } repeat = false; } enclTr = at.underlyingType; diff --git a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Check.java b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Check.java index 9ab0f38013b..23f04b89f6f 100644 --- a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Check.java +++ b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Check.java @@ -63,8 +63,6 @@ import static com.sun.tools.javac.code.Scope.LookupKind.NON_RECURSIVE; import static com.sun.tools.javac.code.TypeTag.*; import static com.sun.tools.javac.code.TypeTag.WILDCARD; -import static com.sun.tools.javac.resources.CompilerProperties.Errors.CantTypeAnnotateScoping; -import static com.sun.tools.javac.resources.CompilerProperties.Errors.CantTypeAnnotateScoping1; import static com.sun.tools.javac.tree.JCTree.Tag.*; /** Type checking helper class for the attribution phase. @@ -2694,29 +2692,6 @@ public class Check { * Check annotations **************************************************************************/ - /** Verify that a component of a qualified type name being type annotated - * can indeed be legally be annotated. For example, package names and type - * names used to access static members cannot be annotated. - * - * @param typeComponent the component of the qualified name being annotated - * @param annotations the annotations - * @param pos diagnostic position - * @return true if all is swell, false otherwise. - */ - boolean checkAnnotableType(Type typeComponent, List annotations, DiagnosticPosition pos) { - if (typeComponent == null || typeComponent.hasTag(PACKAGE) || typeComponent.hasTag(NONE)) { - ListBuffer lb = new ListBuffer<>(); - for (JCAnnotation annotation : annotations) { - lb.append(annotation.annotationType.type.tsym); - } - List symbols = lb.toList(); - log.error(pos, - symbols.size() > 1 ? CantTypeAnnotateScoping(symbols) - : CantTypeAnnotateScoping1(symbols.get(0))); - return false; - } - return true; - } /** * Recursively validate annotations values */ diff --git a/langtools/test/tools/javac/annotations/typeAnnotations/failures/CantAnnotatePackages.java b/langtools/test/tools/javac/annotations/typeAnnotations/failures/CantAnnotatePackages.java index e394d5ee277..011a20d2eb6 100644 --- a/langtools/test/tools/javac/annotations/typeAnnotations/failures/CantAnnotatePackages.java +++ b/langtools/test/tools/javac/annotations/typeAnnotations/failures/CantAnnotatePackages.java @@ -1,12 +1,12 @@ /* * @test /nodynamiccopyright/ - * @bug 8026564 8074346 + * @bug 8026564 * @summary The parts of a fully-qualified type can't be annotated. * @author Werner Dietl + * @ignore 8057679 clarify error messages trying to annotate scoping * @compile/fail/ref=CantAnnotatePackages.out -XDrawDiagnostics CantAnnotatePackages.java */ - import java.lang.annotation.*; import java.util.List; @@ -21,8 +21,6 @@ class CantAnnotatePackages { java. @TA lang.Object of3; List of4; - List<@CantAnnotatePackages_TB java.lang.Object> of5; // test that we do reasonable things for missing types. - // TODO: also note the order of error messages. } diff --git a/langtools/test/tools/javac/annotations/typeAnnotations/failures/CantAnnotatePackages.out b/langtools/test/tools/javac/annotations/typeAnnotations/failures/CantAnnotatePackages.out index 6585a948dd3..600d699ebd4 100644 --- a/langtools/test/tools/javac/annotations/typeAnnotations/failures/CantAnnotatePackages.out +++ b/langtools/test/tools/javac/annotations/typeAnnotations/failures/CantAnnotatePackages.out @@ -1,7 +1,5 @@ -CantAnnotatePackages.java:20:14: compiler.err.cant.type.annotate.scoping.1: TA -CantAnnotatePackages.java:21:9: compiler.err.cant.type.annotate.scoping.1: TA -CantAnnotatePackages.java:22:14: compiler.err.cant.type.annotate.scoping.1: TA -CantAnnotatePackages.java:24:11: compiler.err.cant.resolve.location: kindname.class, CantAnnotatePackages_TB, , , (compiler.misc.location: kindname.class, CantAnnotatePackages, null) -CantAnnotatePackages.java:24:35: compiler.err.cant.type.annotate.scoping.1: CantAnnotatePackages_TB -CantAnnotatePackages.java:15:18: compiler.err.cant.type.annotate.scoping.1: @TA -6 errors +CantAnnotatePackages.java:14:13: compiler.err.cant.type.annotate.scoping.1: @TA +CantAnnotatePackages.java:19:18: compiler.err.cant.type.annotate.scoping.1: @TA +CantAnnotatePackages.java:20:19: compiler.err.cant.type.annotate.scoping.1: @TA +CantAnnotatePackages.java:21:24: compiler.err.cant.type.annotate.scoping.1: @TA +4 errors diff --git a/langtools/test/tools/javac/annotations/typeAnnotations/failures/T8074346.java b/langtools/test/tools/javac/annotations/typeAnnotations/failures/T8074346.java deleted file mode 100644 index 347d84b4829..00000000000 --- a/langtools/test/tools/javac/annotations/typeAnnotations/failures/T8074346.java +++ /dev/null @@ -1,18 +0,0 @@ -/* - * @test /nodynamiccopyright/ - * @bug 8074346 - * @author sadayapalam - * @summary Test that type annotation on a qualified type doesn't cause spurious 'cannot find symbol' errors - * @compile/fail/ref=T8074346.out -XDrawDiagnostics T8074346.java -*/ - -abstract class T8074346 implements - @T8074346_TA @T8074346_TB java.util.Map<@T8074346_TA java.lang.String, java.lang.@T8074346_TA String>, - java.util.@T8074346_TA List { -} - -@java.lang.annotation.Target(java.lang.annotation.ElementType.TYPE_USE) -@interface T8074346_TA { } - -@java.lang.annotation.Target(java.lang.annotation.ElementType.TYPE_USE) -@interface T8074346_TB { } \ No newline at end of file diff --git a/langtools/test/tools/javac/annotations/typeAnnotations/failures/T8074346.out b/langtools/test/tools/javac/annotations/typeAnnotations/failures/T8074346.out deleted file mode 100644 index c32d75101c8..00000000000 --- a/langtools/test/tools/javac/annotations/typeAnnotations/failures/T8074346.out +++ /dev/null @@ -1,3 +0,0 @@ -T8074346.java:10:35: compiler.err.cant.type.annotate.scoping: T8074346_TA,T8074346_TB -T8074346.java:10:62: compiler.err.cant.type.annotate.scoping.1: T8074346_TA -2 errors \ No newline at end of file From 7d78c183c48b772a41efbe4974cfc2d98023f30c Mon Sep 17 00:00:00 2001 From: Liam Miller-Cushon Date: Thu, 9 Jul 2015 11:06:48 -0700 Subject: [PATCH 27/43] 8130803: add regression test related to fix for JDK-8078024 Reviewed-by: mcimadamore --- .../generics/inference/8078024/T8078024.java | 45 +++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 langtools/test/tools/javac/generics/inference/8078024/T8078024.java diff --git a/langtools/test/tools/javac/generics/inference/8078024/T8078024.java b/langtools/test/tools/javac/generics/inference/8078024/T8078024.java new file mode 100644 index 00000000000..86fe7da2c85 --- /dev/null +++ b/langtools/test/tools/javac/generics/inference/8078024/T8078024.java @@ -0,0 +1,45 @@ +/* + * Copyright (c) 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. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/** + * @test + * @bug 8078024 + * @summary before the patch for JDK-8078024 this code wasn't accepted by the compiler. After the + * mentioned patch the second method is selected as applicable and the code is accepted. + * @compile T8078024.java + */ + +import java.util.Arrays; +import java.util.List; + +class T8078024 { + public static List> cartesianProduct(List... lists) { + return cartesianProduct(Arrays.asList(lists)); + } + + public static List> cartesianProduct(List> lists) { + return null; + } +} From c265539479cf31001acd8633d6db2c025b1ccc9c Mon Sep 17 00:00:00 2001 From: David Katleman Date: Thu, 9 Jul 2015 13:49:31 -0700 Subject: [PATCH 28/43] Added tag jdk9-b72 for changeset 7dd7a38425a8 --- .hgtags-top-repo | 1 + 1 file changed, 1 insertion(+) diff --git a/.hgtags-top-repo b/.hgtags-top-repo index e6f4871454e..aace44e73fd 100644 --- a/.hgtags-top-repo +++ b/.hgtags-top-repo @@ -314,3 +314,4 @@ f546760134eb861fcfecd4ce611b0040b0d25a6a jdk9-b67 1bcfd6b8726582cff5a42dbfc75903e36f9dd4fe jdk9-b69 eed77fcd77711fcdba05f18fc22f37d86efb243c jdk9-b70 c706ef5ea5da00078dc5e4334660315f7d99c15b jdk9-b71 +8582c35016fb6211b373810b6b172feccf9c483b jdk9-b72 From 1d9002da27613aa799a90421a938d7b13e0799ee Mon Sep 17 00:00:00 2001 From: David Katleman Date: Thu, 9 Jul 2015 13:49:32 -0700 Subject: [PATCH 29/43] Added tag jdk9-b72 for changeset 02be96db190a --- hotspot/.hgtags | 1 + 1 file changed, 1 insertion(+) diff --git a/hotspot/.hgtags b/hotspot/.hgtags index 357e1c2da27..439df02dbb9 100644 --- a/hotspot/.hgtags +++ b/hotspot/.hgtags @@ -474,3 +474,4 @@ d47dfabd16d48eb96a451edd1b61194a39ee0eb5 jdk9-b67 ff0929a59ced0e144201aa05819ae2e47d6f2c61 jdk9-b69 8672e9264db30c21504063932dbc374eabc287a1 jdk9-b70 07c6b035d68b0c41b1dcd442157b50b41a2551e9 jdk9-b71 +c1b2825ef47e75cb34dd18450d1c4280b7c5853c jdk9-b72 From a7374080bc83ed6269a12bdf93a498a25f4b8add Mon Sep 17 00:00:00 2001 From: David Katleman Date: Thu, 9 Jul 2015 13:49:32 -0700 Subject: [PATCH 30/43] Added tag jdk9-b72 for changeset 423e8a18b960 --- corba/.hgtags | 1 + 1 file changed, 1 insertion(+) diff --git a/corba/.hgtags b/corba/.hgtags index 6f8a78b94cc..e323b55a76c 100644 --- a/corba/.hgtags +++ b/corba/.hgtags @@ -314,3 +314,4 @@ afc1e295c4bf83f9a5dd539c29914edd4a754a3f jdk9-b65 de8acedcb5b5870f1dc54cba575aaa5d33897ea2 jdk9-b69 e7cf01990ed366bd493080663259281e91ce223b jdk9-b70 cd39ed501fb0504554a7f58ac6cf3dd2b64afec0 jdk9-b71 +f9f3706bd24c42c07cb260fe05730a749b8e52f4 jdk9-b72 From 722b2a5d051b85afeab746ed61f23668c91f409c Mon Sep 17 00:00:00 2001 From: David Katleman Date: Thu, 9 Jul 2015 13:49:35 -0700 Subject: [PATCH 31/43] Added tag jdk9-b72 for changeset 8ebacfaf4ba6 --- jaxp/.hgtags | 1 + 1 file changed, 1 insertion(+) diff --git a/jaxp/.hgtags b/jaxp/.hgtags index f42c3abe843..3912f8ef4e5 100644 --- a/jaxp/.hgtags +++ b/jaxp/.hgtags @@ -314,3 +314,4 @@ d5963ccce28d7a3e96ee3e2dc8a8676e61699b70 jdk9-b66 f844a908d3308f47d73cf64e87c98d37d5d76ce8 jdk9-b69 42180703e0a362c1de7cdbf61d2cbc6609e678c4 jdk9-b70 a3200b88f259f904876b9ab13fd4c4ec2726f8ba jdk9-b71 +81e85f3b6174314155991048767452a9931e12e2 jdk9-b72 From 34aa20446569990de6b334d36bea8182a841d2e4 Mon Sep 17 00:00:00 2001 From: David Katleman Date: Thu, 9 Jul 2015 13:49:35 -0700 Subject: [PATCH 32/43] Added tag jdk9-b72 for changeset f0d057d75897 --- jaxws/.hgtags | 1 + 1 file changed, 1 insertion(+) diff --git a/jaxws/.hgtags b/jaxws/.hgtags index b27eb94f4d6..b00513266ab 100644 --- a/jaxws/.hgtags +++ b/jaxws/.hgtags @@ -317,3 +317,4 @@ b5878b03d1b2e105917d959fbfa3c57c22495803 jdk9-b68 f5911c6155c29ac24b6f9068273207e5ebd3a3df jdk9-b69 94084caa27a3c8a09a7510aef596ebd64e97c569 jdk9-b70 61caeb7061bbf8cc74a767997e5d17cc00712629 jdk9-b71 +1d87054e2d2f405c114f0061b97cbf8214bddf0a jdk9-b72 From 6a0771f941bf02ccdb552e5ae03c1c1330ef0867 Mon Sep 17 00:00:00 2001 From: David Katleman Date: Thu, 9 Jul 2015 13:49:36 -0700 Subject: [PATCH 33/43] Added tag jdk9-b72 for changeset a006a766c8c9 --- jdk/.hgtags | 1 + 1 file changed, 1 insertion(+) diff --git a/jdk/.hgtags b/jdk/.hgtags index 6a1fe8984b3..42d9aedf7f3 100644 --- a/jdk/.hgtags +++ b/jdk/.hgtags @@ -314,3 +314,4 @@ ed94f3e7ba6bbfec0772de6d24e39543e13f6d88 jdk9-b65 551323004d0ce2f1d4b0e99552f7e0cdcebc6fca jdk9-b69 a7f731125b7fb0e4b0186172f85a21e2d5139f7e jdk9-b70 e47d3bfbc61accc3fbd372a674fdce2933b54f31 jdk9-b71 +f376824d4940f45719d91838f3f6249f873440db jdk9-b72 From 3e638cf75cbe25cfa705d7d52e0c58349c687a0c Mon Sep 17 00:00:00 2001 From: David Katleman Date: Thu, 9 Jul 2015 13:49:40 -0700 Subject: [PATCH 34/43] Added tag jdk9-b72 for changeset 1f783cf1d945 --- langtools/.hgtags | 1 + 1 file changed, 1 insertion(+) diff --git a/langtools/.hgtags b/langtools/.hgtags index b7eeb4e418a..a2e0088c9ea 100644 --- a/langtools/.hgtags +++ b/langtools/.hgtags @@ -314,3 +314,4 @@ c71857c93f57c63be44258d3d67e656c2bacdb45 jdk9-b68 931ec7dd6cd9e4a92bde7b2cd26e9a9fb0ecdb56 jdk9-b69 d732d6dfa72743e3aa96375c6e33f1388dbaa5c6 jdk9-b70 dc35e315436d21eab68ef44909922fb3424917f3 jdk9-b71 +832e51533706b633d37a77282ae94d016b95e649 jdk9-b72 From da2c7d7fc6f031055fd4c2f890da594d5d92bb6a Mon Sep 17 00:00:00 2001 From: David Katleman Date: Thu, 9 Jul 2015 13:49:41 -0700 Subject: [PATCH 35/43] Added tag jdk9-b72 for changeset 93250cfbfa54 --- nashorn/.hgtags | 1 + 1 file changed, 1 insertion(+) diff --git a/nashorn/.hgtags b/nashorn/.hgtags index 206438703ad..0e5872582af 100644 --- a/nashorn/.hgtags +++ b/nashorn/.hgtags @@ -305,3 +305,4 @@ dd6dd848b854dbd3f3cc422668276b1ae0834179 jdk9-b68 194b74467afcab3ca0096f04570def424977215d jdk9-b69 3379235149c0e14e59e05c4ab8df450f5777b552 jdk9-b70 7066af6e7b06f3c6ebf449c88fc1064d2181237a jdk9-b71 +d017877b3b8cd39337f1bdc00d958f821433c4c3 jdk9-b72 From 9e36911148768e36134d422ecefb7f85e56ea4be Mon Sep 17 00:00:00 2001 From: "J. Duke" Date: Wed, 5 Jul 2017 20:40:53 +0200 Subject: [PATCH 36/43] Added tag jdk9-b72 for changeset 61d2d0629b6d --- .hgtags | 1 + 1 file changed, 1 insertion(+) diff --git a/.hgtags b/.hgtags index 07e1de67af7..b65c43f255c 100644 --- a/.hgtags +++ b/.hgtags @@ -314,3 +314,4 @@ ff3fc75f3214ad7e03595be1b0d0f38d887b6f0e jdk9-b66 d69c968463f0ae5d0b45de3fc14fe65171b23948 jdk9-b69 43d0179ee9de3bfffae3417f09e07eb6d8efc963 jdk9-b70 f66c185284727f6e6ffd27e9c45ed2dd9da0a691 jdk9-b71 +61d2d0629b6dbf4c091dc86151ade1b3ef34fffe jdk9-b72 From 91a4a6b0ce83af0fd809956b6cd67aefd9f14ef5 Mon Sep 17 00:00:00 2001 From: Pavel Rappo Date: Fri, 10 Jul 2015 16:40:12 +0100 Subject: [PATCH 37/43] 8064925: URLConnection::getContent needs to be updated to work with modules Reviewed-by: chegar, alanb --- .../classes/java/net/ContentHandler.java | 20 +- .../java/net/ContentHandlerFactory.java | 3 +- .../share/classes/java/net/URLConnection.java | 170 +++++--- .../services/java.net.ContentHandlerFactory | 27 ++ .../content/MultimediaContentHandlers.java | 59 +++ .../{net => awt}/www/content/audio/aiff.java | 2 +- .../{net => awt}/www/content/audio/basic.java | 2 +- .../{net => awt}/www/content/audio/wav.java | 2 +- .../www/content/audio/x_aiff.java | 2 +- .../{net => awt}/www/content/audio/x_wav.java | 2 +- .../{net => awt}/www/content/image/gif.java | 2 +- .../{net => awt}/www/content/image/jpeg.java | 2 +- .../{net => awt}/www/content/image/png.java | 2 +- .../www/content/image/x_xbitmap.java | 2 +- .../www/content/image/x_xpixmap.java | 2 +- .../ContentHandlers/ContentHandlersTest.java | 371 ++++++++++++++++++ .../broken_constructor_factory.template | 40 ++ .../ContentHandlers/broken_factory.template | 36 ++ .../ContentHandlers/plain.template | 37 ++ .../ContentHandlers/test.template | 79 ++++ 20 files changed, 780 insertions(+), 82 deletions(-) create mode 100644 jdk/src/java.desktop/share/classes/META-INF/services/java.net.ContentHandlerFactory create mode 100644 jdk/src/java.desktop/share/classes/sun/awt/www/content/MultimediaContentHandlers.java rename jdk/src/java.desktop/share/classes/sun/{net => awt}/www/content/audio/aiff.java (97%) rename jdk/src/java.desktop/share/classes/sun/{net => awt}/www/content/audio/basic.java (97%) rename jdk/src/java.desktop/share/classes/sun/{net => awt}/www/content/audio/wav.java (97%) rename jdk/src/java.desktop/share/classes/sun/{net => awt}/www/content/audio/x_aiff.java (97%) rename jdk/src/java.desktop/share/classes/sun/{net => awt}/www/content/audio/x_wav.java (97%) rename jdk/src/java.desktop/share/classes/sun/{net => awt}/www/content/image/gif.java (98%) rename jdk/src/java.desktop/share/classes/sun/{net => awt}/www/content/image/jpeg.java (98%) rename jdk/src/java.desktop/share/classes/sun/{net => awt}/www/content/image/png.java (98%) rename jdk/src/java.desktop/share/classes/sun/{net => awt}/www/content/image/x_xbitmap.java (98%) rename jdk/src/java.desktop/share/classes/sun/{net => awt}/www/content/image/x_xpixmap.java (98%) create mode 100644 jdk/test/java/net/URLConnection/ContentHandlers/ContentHandlersTest.java create mode 100644 jdk/test/java/net/URLConnection/ContentHandlers/broken_constructor_factory.template create mode 100644 jdk/test/java/net/URLConnection/ContentHandlers/broken_factory.template create mode 100644 jdk/test/java/net/URLConnection/ContentHandlers/plain.template create mode 100644 jdk/test/java/net/URLConnection/ContentHandlers/test.template diff --git a/jdk/src/java.base/share/classes/java/net/ContentHandler.java b/jdk/src/java.base/share/classes/java/net/ContentHandler.java index 7e71b25d66d..47bc21699f5 100644 --- a/jdk/src/java.base/share/classes/java/net/ContentHandler.java +++ b/jdk/src/java.base/share/classes/java/net/ContentHandler.java @@ -44,14 +44,14 @@ import java.io.IOException; * instance of a subclass of {@code ContentHandler}, and its * {@code getContent} method is called to create the object. *

- * If no content handler could be found, URLConnection will - * look for a content handler in a user-defineable set of places. + * If no content handler could be {@linkplain URLConnection#getContent() found}, + * URLConnection will look for a content handler in a user-definable set of places. * Users can define a vertical-bar delimited set of class prefixes - * to search through by defining the java.content.handler.pkgs + * to search through by defining the {@value java.net.URLConnection#contentPathProp} * property. The class name must be of the form: *

* {package-prefix}.{major}.{minor} - *

+ *

* where {major}.{minor} is formed by taking the * content-type string, replacing all slash characters with a * {@code period} ('.'), and all other non-alphanumeric characters @@ -82,6 +82,7 @@ import java.io.IOException; * @since 1.0 */ abstract public class ContentHandler { + /** * Given a URL connect stream positioned at the beginning of the * representation of an object, this method reads that stream and @@ -104,8 +105,8 @@ abstract public class ContentHandler { * @param urlc a URL connection. * @param classes an array of types requested * @return the object read by the {@code ContentHandler} that is - * the first match of the suggested types. - * null if none of the requested are supported. + * the first match of the suggested types or + * {@code null} if none of the requested are supported. * @exception IOException if an I/O error occurs while reading the object. * @since 1.3 */ @@ -113,12 +114,11 @@ abstract public class ContentHandler { public Object getContent(URLConnection urlc, Class[] classes) throws IOException { Object obj = getContent(urlc); - for (int i = 0; i < classes.length; i++) { - if (classes[i].isInstance(obj)) { + for (Class c : classes) { + if (c.isInstance(obj)) { return obj; - } + } } return null; } - } diff --git a/jdk/src/java.base/share/classes/java/net/ContentHandlerFactory.java b/jdk/src/java.base/share/classes/java/net/ContentHandlerFactory.java index 1e75e71b88f..994e2662403 100644 --- a/jdk/src/java.base/share/classes/java/net/ContentHandlerFactory.java +++ b/jdk/src/java.base/share/classes/java/net/ContentHandlerFactory.java @@ -39,12 +39,13 @@ package java.net; * @since 1.0 */ public interface ContentHandlerFactory { + /** * Creates a new {@code ContentHandler} to read an object from * a {@code URLStreamHandler}. * * @param mimetype the MIME type for which a content handler is desired. - + * * @return a new {@code ContentHandler} to read an object from a * {@code URLStreamHandler}. * @see java.net.ContentHandler diff --git a/jdk/src/java.base/share/classes/java/net/URLConnection.java b/jdk/src/java.base/share/classes/java/net/URLConnection.java index afa80c377aa..26928a554a6 100644 --- a/jdk/src/java.base/share/classes/java/net/URLConnection.java +++ b/jdk/src/java.base/share/classes/java/net/URLConnection.java @@ -28,8 +28,12 @@ package java.net; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; +import java.security.PrivilegedAction; import java.util.Hashtable; import java.util.Date; +import java.util.Iterator; +import java.util.ServiceConfigurationError; +import java.util.ServiceLoader; import java.util.StringTokenizer; import java.util.Collections; import java.util.Map; @@ -107,7 +111,7 @@ import sun.net.www.MessageHeader; *

  • {@code getContentType} *
  • {@code getDate} *
  • {@code getExpiration} - *
  • {@code getLastModifed} + *
  • {@code getLastModified} * *

    * provide convenient access to these fields. The @@ -695,16 +699,30 @@ public abstract class URLConnection { * This method first determines the content type of the object by * calling the {@code getContentType} method. If this is * the first time that the application has seen that specific content - * type, a content handler for that content type is created: + * type, a content handler for that content type is created. + *

    This is done as follows: *

      *
    1. If the application has set up a content handler factory instance * using the {@code setContentHandlerFactory} method, the * {@code createContentHandler} method of that instance is called * with the content type as an argument; the result is a content * handler for that content type. - *
    2. If no content handler factory has yet been set up, or if the - * factory's {@code createContentHandler} method returns - * {@code null}, then this method tries to load a content handler + *
    3. If no {@code ContentHandlerFactory} has yet been set up, + * or if the factory's {@code createContentHandler} method + * returns {@code null}, then the {@linkplain java.util.ServiceLoader + * ServiceLoader} mechanism is used to locate {@linkplain + * java.net.ContentHandlerFactory ContentHandlerFactory} + * implementations using the system class + * loader. The order that factories are located is implementation + * specific, and an implementation is free to cache the located + * factories. A {@linkplain java.util.ServiceConfigurationError + * ServiceConfigurationError}, {@code Error} or {@code RuntimeException} + * thrown from the {@code createContentHandler}, if encountered, will + * be propagated to the calling thread. The {@code + * createContentHandler} method of each factory, if instantiated, is + * invoked, with the content type, until a factory returns non-null, + * or all factories have been exhausted. + *
    4. Failing that, this method tries to load a content handler * class as defined by {@link java.net.ContentHandler ContentHandler}. * If the class does not exist, or is not a subclass of {@code * ContentHandler}, then an {@code UnknownServiceException} is thrown. @@ -855,8 +873,7 @@ public abstract class URLConnection { * @see #getDoInput() */ public void setDoInput(boolean doinput) { - if (connected) - throw new IllegalStateException("Already connected"); + checkConnected(); doInput = doinput; } @@ -885,8 +902,7 @@ public abstract class URLConnection { * @see #getDoOutput() */ public void setDoOutput(boolean dooutput) { - if (connected) - throw new IllegalStateException("Already connected"); + checkConnected(); doOutput = dooutput; } @@ -911,8 +927,7 @@ public abstract class URLConnection { * @see #getAllowUserInteraction() */ public void setAllowUserInteraction(boolean allowuserinteraction) { - if (connected) - throw new IllegalStateException("Already connected"); + checkConnected(); allowUserInteraction = allowuserinteraction; } @@ -974,8 +989,7 @@ public abstract class URLConnection { * @see #getUseCaches() */ public void setUseCaches(boolean usecaches) { - if (connected) - throw new IllegalStateException("Already connected"); + checkConnected(); useCaches = usecaches; } @@ -1000,8 +1014,7 @@ public abstract class URLConnection { * @see #getIfModifiedSince() */ public void setIfModifiedSince(long ifmodifiedsince) { - if (connected) - throw new IllegalStateException("Already connected"); + checkConnected(); ifModifiedSince = ifmodifiedsince; } @@ -1055,12 +1068,11 @@ public abstract class URLConnection { * (e.g., "{@code Accept}"). * @param value the value associated with it. * @throws IllegalStateException if already connected - * @throws NullPointerException if key is null + * @throws NullPointerException if key is {@code null} * @see #getRequestProperty(java.lang.String) */ public void setRequestProperty(String key, String value) { - if (connected) - throw new IllegalStateException("Already connected"); + checkConnected(); if (key == null) throw new NullPointerException ("key is null"); @@ -1084,8 +1096,7 @@ public abstract class URLConnection { * @since 1.4 */ public void addRequestProperty(String key, String value) { - if (connected) - throw new IllegalStateException("Already connected"); + checkConnected(); if (key == null) throw new NullPointerException ("key is null"); @@ -1107,8 +1118,7 @@ public abstract class URLConnection { * @see #setRequestProperty(java.lang.String, java.lang.String) */ public String getRequestProperty(String key) { - if (connected) - throw new IllegalStateException("Already connected"); + checkConnected(); if (requests == null) return null; @@ -1129,8 +1139,7 @@ public abstract class URLConnection { * @since 1.4 */ public Map> getRequestProperties() { - if (connected) - throw new IllegalStateException("Already connected"); + checkConnected(); if (requests == null) return Collections.emptyMap(); @@ -1183,7 +1192,7 @@ public abstract class URLConnection { /** * The ContentHandler factory. */ - static ContentHandlerFactory factory; + private static volatile ContentHandlerFactory factory; /** * Sets the {@code ContentHandlerFactory} of an @@ -1216,37 +1225,45 @@ public abstract class URLConnection { factory = fac; } - private static Hashtable handlers = new Hashtable<>(); + private static final Hashtable handlers = new Hashtable<>(); /** * Gets the Content Handler appropriate for this connection. */ - synchronized ContentHandler getContentHandler() - throws UnknownServiceException - { + private ContentHandler getContentHandler() throws UnknownServiceException { String contentType = stripOffParameters(getContentType()); - ContentHandler handler = null; - if (contentType == null) + if (contentType == null) { throw new UnknownServiceException("no content-type"); - try { - handler = handlers.get(contentType); - if (handler != null) - return handler; - } catch(Exception e) { } - if (factory != null) + ContentHandler handler = handlers.get(contentType); + if (handler != null) + return handler; + + if (factory != null) { handler = factory.createContentHandler(contentType); - if (handler == null) { - try { - handler = lookupContentHandlerClassFor(contentType); - } catch(Exception e) { - e.printStackTrace(); - handler = UnknownContentHandler.INSTANCE; - } - handlers.put(contentType, handler); + if (handler != null) + return handler; } - return handler; + + handler = lookupContentHandlerViaProvider(contentType); + + if (handler != null) { + ContentHandler h = handlers.putIfAbsent(contentType, handler); + return h != null ? h : handler; + } + + try { + handler = lookupContentHandlerClassFor(contentType); + } catch (Exception e) { + e.printStackTrace(); + handler = UnknownContentHandler.INSTANCE; + } + + assert handler != null; + + ContentHandler h = handlers.putIfAbsent(contentType, handler); + return h != null ? h : handler; } /* @@ -1270,10 +1287,10 @@ public abstract class URLConnection { private static final String contentPathProp = "java.content.handler.pkgs"; /** - * Looks for a content handler in a user-defineable set of places. - * By default it looks in sun.net.www.content, but users can define a - * vertical-bar delimited set of class prefixes to search through in - * addition by defining the java.content.handler.pkgs property. + * Looks for a content handler in a user-definable set of places. + * By default it looks in {@value #contentClassPrefix}, but users can define + * a vertical-bar delimited set of class prefixes to search through in + * addition by defining the {@value #contentPathProp} property. * The class name must be of the form: *
            *     {package-prefix}.{major}.{minor}
      @@ -1281,11 +1298,10 @@ public abstract class URLConnection {
            *     YoyoDyne.experimental.text.plain
            * 
      */ - private ContentHandler lookupContentHandlerClassFor(String contentType) - throws InstantiationException, IllegalAccessException, ClassNotFoundException { + private ContentHandler lookupContentHandlerClassFor(String contentType) { String contentHandlerClassName = typeToPackageName(contentType); - String contentHandlerPkgPrefixes =getContentHandlerPkgPrefixes(); + String contentHandlerPkgPrefixes = getContentHandlerPkgPrefixes(); StringTokenizer packagePrefixIter = new StringTokenizer(contentHandlerPkgPrefixes, "|"); @@ -1305,17 +1321,46 @@ public abstract class URLConnection { } } if (cls != null) { - ContentHandler handler = - (ContentHandler)cls.newInstance(); - return handler; + return (ContentHandler) cls.newInstance(); } - } catch(Exception e) { - } + } catch(Exception ignored) { } } return UnknownContentHandler.INSTANCE; } + private ContentHandler lookupContentHandlerViaProvider(String contentType) { + return AccessController.doPrivileged( + new PrivilegedAction<>() { + @Override + public ContentHandler run() { + ClassLoader cl = ClassLoader.getSystemClassLoader(); + ServiceLoader sl = + ServiceLoader.load(ContentHandlerFactory.class, cl); + + Iterator iterator = sl.iterator(); + + ContentHandler handler = null; + while (iterator.hasNext()) { + ContentHandlerFactory f; + try { + f = iterator.next(); + } catch (ServiceConfigurationError e) { + if (e.getCause() instanceof SecurityException) { + continue; + } + throw e; + } + handler = f.createContentHandler(contentType); + if (handler != null) { + break; + } + } + return handler; + } + }); + } + /** * Utility function to map a MIME content type into an equivalent * pair of class name components. For example: "text/html" would @@ -1345,8 +1390,8 @@ public abstract class URLConnection { * Returns a vertical bar separated list of package prefixes for potential * content handlers. Tries to get the java.content.handler.pkgs property * to use as a set of package prefixes to search. Whether or not - * that property has been defined, the sun.net.www.content is always - * the last one on the returned package list. + * that property has been defined, the {@value #contentClassPrefix} + * is always the last one on the returned package list. */ private String getContentHandlerPkgPrefixes() { String packagePrefixList = AccessController.doPrivileged( @@ -1764,9 +1809,12 @@ public abstract class URLConnection { return skipped; } + private void checkConnected() { + if (connected) + throw new IllegalStateException("Already connected"); + } } - class UnknownContentHandler extends ContentHandler { static final ContentHandler INSTANCE = new UnknownContentHandler(); diff --git a/jdk/src/java.desktop/share/classes/META-INF/services/java.net.ContentHandlerFactory b/jdk/src/java.desktop/share/classes/META-INF/services/java.net.ContentHandlerFactory new file mode 100644 index 00000000000..85fce1ef49b --- /dev/null +++ b/jdk/src/java.desktop/share/classes/META-INF/services/java.net.ContentHandlerFactory @@ -0,0 +1,27 @@ +# +# Copyright (c) 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. Oracle designates this +# particular file as subject to the "Classpath" exception as provided +# by Oracle in the LICENSE file that accompanied this code. +# +# This code is distributed in the hope that it will be useful, but WITHOUT +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +# version 2 for more details (a copy is included in the LICENSE file that +# accompanied this code). +# +# You should have received a copy of the GNU General Public License version +# 2 along with this work; if not, write to the Free Software Foundation, +# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. +# +# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA +# or visit www.oracle.com if you need additional information or have any +# questions. +# + +# Provider for content handlers +sun.awt.www.content.MultimediaContentHandlers diff --git a/jdk/src/java.desktop/share/classes/sun/awt/www/content/MultimediaContentHandlers.java b/jdk/src/java.desktop/share/classes/sun/awt/www/content/MultimediaContentHandlers.java new file mode 100644 index 00000000000..88ab6b9802b --- /dev/null +++ b/jdk/src/java.desktop/share/classes/sun/awt/www/content/MultimediaContentHandlers.java @@ -0,0 +1,59 @@ +/* + * Copyright (c) 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. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package sun.awt.www.content; + +import sun.awt.www.content.audio.wav; +import sun.awt.www.content.audio.x_aiff; +import sun.awt.www.content.image.gif; +import sun.awt.www.content.audio.aiff; +import sun.awt.www.content.audio.basic; +import sun.awt.www.content.audio.x_wav; +import sun.awt.www.content.image.jpeg; +import sun.awt.www.content.image.png; +import sun.awt.www.content.image.x_xbitmap; +import sun.awt.www.content.image.x_xpixmap; + +import java.net.ContentHandler; +import java.net.ContentHandlerFactory; + +public final class MultimediaContentHandlers implements ContentHandlerFactory { + + @Override + public ContentHandler createContentHandler(String mimetype) { + switch (mimetype) { + case "audio/aiff": return new aiff(); + case "audio/basic": return new basic(); + case "audio/wav": return new wav(); + case "audio/x-aiff": return new x_aiff(); + case "audio/x-wav": return new x_wav(); + case "image/gif": return new gif(); + case "image/jpeg": return new jpeg(); + case "image/png": return new png(); + case "image/x-xbitmap": return new x_xbitmap(); + case "image/x-xpixmap": return new x_xpixmap(); + default: return null; + } + } +} diff --git a/jdk/src/java.desktop/share/classes/sun/net/www/content/audio/aiff.java b/jdk/src/java.desktop/share/classes/sun/awt/www/content/audio/aiff.java similarity index 97% rename from jdk/src/java.desktop/share/classes/sun/net/www/content/audio/aiff.java rename to jdk/src/java.desktop/share/classes/sun/awt/www/content/audio/aiff.java index 802942d007c..efdec322ae3 100644 --- a/jdk/src/java.desktop/share/classes/sun/net/www/content/audio/aiff.java +++ b/jdk/src/java.desktop/share/classes/sun/awt/www/content/audio/aiff.java @@ -27,7 +27,7 @@ * Basic .aiff audio handler. * @author Jeff Nisewanger */ -package sun.net.www.content.audio; +package sun.awt.www.content.audio; import java.net.*; import java.io.IOException; diff --git a/jdk/src/java.desktop/share/classes/sun/net/www/content/audio/basic.java b/jdk/src/java.desktop/share/classes/sun/awt/www/content/audio/basic.java similarity index 97% rename from jdk/src/java.desktop/share/classes/sun/net/www/content/audio/basic.java rename to jdk/src/java.desktop/share/classes/sun/awt/www/content/audio/basic.java index 0389a3a3c58..399c11f6616 100644 --- a/jdk/src/java.desktop/share/classes/sun/net/www/content/audio/basic.java +++ b/jdk/src/java.desktop/share/classes/sun/awt/www/content/audio/basic.java @@ -27,7 +27,7 @@ * Basic .au and .snd audio handler. * @author Jeff Nisewanger */ -package sun.net.www.content.audio; +package sun.awt.www.content.audio; import java.net.*; import java.io.IOException; diff --git a/jdk/src/java.desktop/share/classes/sun/net/www/content/audio/wav.java b/jdk/src/java.desktop/share/classes/sun/awt/www/content/audio/wav.java similarity index 97% rename from jdk/src/java.desktop/share/classes/sun/net/www/content/audio/wav.java rename to jdk/src/java.desktop/share/classes/sun/awt/www/content/audio/wav.java index 9d76ee13479..e4a3a2ecc57 100644 --- a/jdk/src/java.desktop/share/classes/sun/net/www/content/audio/wav.java +++ b/jdk/src/java.desktop/share/classes/sun/awt/www/content/audio/wav.java @@ -27,7 +27,7 @@ * Basic .wav audio handler. * @author Jeff Nisewanger */ -package sun.net.www.content.audio; +package sun.awt.www.content.audio; import java.net.*; import java.io.IOException; diff --git a/jdk/src/java.desktop/share/classes/sun/net/www/content/audio/x_aiff.java b/jdk/src/java.desktop/share/classes/sun/awt/www/content/audio/x_aiff.java similarity index 97% rename from jdk/src/java.desktop/share/classes/sun/net/www/content/audio/x_aiff.java rename to jdk/src/java.desktop/share/classes/sun/awt/www/content/audio/x_aiff.java index 1c7d94b0b6e..c1e5f906379 100644 --- a/jdk/src/java.desktop/share/classes/sun/net/www/content/audio/x_aiff.java +++ b/jdk/src/java.desktop/share/classes/sun/awt/www/content/audio/x_aiff.java @@ -27,7 +27,7 @@ * Basic .aiff audio handler. * @author Jeff Nisewanger */ -package sun.net.www.content.audio; +package sun.awt.www.content.audio; import java.net.*; import java.io.IOException; diff --git a/jdk/src/java.desktop/share/classes/sun/net/www/content/audio/x_wav.java b/jdk/src/java.desktop/share/classes/sun/awt/www/content/audio/x_wav.java similarity index 97% rename from jdk/src/java.desktop/share/classes/sun/net/www/content/audio/x_wav.java rename to jdk/src/java.desktop/share/classes/sun/awt/www/content/audio/x_wav.java index 4aa765d38e7..2f4d1ffc7b9 100644 --- a/jdk/src/java.desktop/share/classes/sun/net/www/content/audio/x_wav.java +++ b/jdk/src/java.desktop/share/classes/sun/awt/www/content/audio/x_wav.java @@ -27,7 +27,7 @@ * Basic .wav audio handler. * @author Jeff Nisewanger */ -package sun.net.www.content.audio; +package sun.awt.www.content.audio; import java.net.*; import java.io.IOException; diff --git a/jdk/src/java.desktop/share/classes/sun/net/www/content/image/gif.java b/jdk/src/java.desktop/share/classes/sun/awt/www/content/image/gif.java similarity index 98% rename from jdk/src/java.desktop/share/classes/sun/net/www/content/image/gif.java rename to jdk/src/java.desktop/share/classes/sun/awt/www/content/image/gif.java index 78b6c6c09fa..d7262261dec 100644 --- a/jdk/src/java.desktop/share/classes/sun/net/www/content/image/gif.java +++ b/jdk/src/java.desktop/share/classes/sun/awt/www/content/image/gif.java @@ -23,7 +23,7 @@ * questions. */ -package sun.net.www.content.image; +package sun.awt.www.content.image; import java.net.*; import sun.awt.image.*; diff --git a/jdk/src/java.desktop/share/classes/sun/net/www/content/image/jpeg.java b/jdk/src/java.desktop/share/classes/sun/awt/www/content/image/jpeg.java similarity index 98% rename from jdk/src/java.desktop/share/classes/sun/net/www/content/image/jpeg.java rename to jdk/src/java.desktop/share/classes/sun/awt/www/content/image/jpeg.java index fdb034d9bf0..294b18da36d 100644 --- a/jdk/src/java.desktop/share/classes/sun/net/www/content/image/jpeg.java +++ b/jdk/src/java.desktop/share/classes/sun/awt/www/content/image/jpeg.java @@ -23,7 +23,7 @@ * questions. */ -package sun.net.www.content.image; +package sun.awt.www.content.image; import java.net.*; import sun.awt.image.*; diff --git a/jdk/src/java.desktop/share/classes/sun/net/www/content/image/png.java b/jdk/src/java.desktop/share/classes/sun/awt/www/content/image/png.java similarity index 98% rename from jdk/src/java.desktop/share/classes/sun/net/www/content/image/png.java rename to jdk/src/java.desktop/share/classes/sun/awt/www/content/image/png.java index 526d23eb2ff..5b444a2535d 100644 --- a/jdk/src/java.desktop/share/classes/sun/net/www/content/image/png.java +++ b/jdk/src/java.desktop/share/classes/sun/awt/www/content/image/png.java @@ -23,7 +23,7 @@ * questions. */ -package sun.net.www.content.image; +package sun.awt.www.content.image; import java.net.*; import java.io.IOException; diff --git a/jdk/src/java.desktop/share/classes/sun/net/www/content/image/x_xbitmap.java b/jdk/src/java.desktop/share/classes/sun/awt/www/content/image/x_xbitmap.java similarity index 98% rename from jdk/src/java.desktop/share/classes/sun/net/www/content/image/x_xbitmap.java rename to jdk/src/java.desktop/share/classes/sun/awt/www/content/image/x_xbitmap.java index 839b902ee9b..e5df4b3e8ba 100644 --- a/jdk/src/java.desktop/share/classes/sun/net/www/content/image/x_xbitmap.java +++ b/jdk/src/java.desktop/share/classes/sun/awt/www/content/image/x_xbitmap.java @@ -23,7 +23,7 @@ * questions. */ -package sun.net.www.content.image; +package sun.awt.www.content.image; import java.net.*; import sun.awt.image.*; diff --git a/jdk/src/java.desktop/share/classes/sun/net/www/content/image/x_xpixmap.java b/jdk/src/java.desktop/share/classes/sun/awt/www/content/image/x_xpixmap.java similarity index 98% rename from jdk/src/java.desktop/share/classes/sun/net/www/content/image/x_xpixmap.java rename to jdk/src/java.desktop/share/classes/sun/awt/www/content/image/x_xpixmap.java index d220844977c..820e41e760f 100644 --- a/jdk/src/java.desktop/share/classes/sun/net/www/content/image/x_xpixmap.java +++ b/jdk/src/java.desktop/share/classes/sun/awt/www/content/image/x_xpixmap.java @@ -23,7 +23,7 @@ * questions. */ -package sun.net.www.content.image; +package sun.awt.www.content.image; import java.net.*; import sun.awt.image.*; diff --git a/jdk/test/java/net/URLConnection/ContentHandlers/ContentHandlersTest.java b/jdk/test/java/net/URLConnection/ContentHandlers/ContentHandlersTest.java new file mode 100644 index 00000000000..49b2d7a6b64 --- /dev/null +++ b/jdk/test/java/net/URLConnection/ContentHandlers/ContentHandlersTest.java @@ -0,0 +1,371 @@ +/* + * Copyright (c) 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. + */ + +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.Reader; +import java.io.SequenceInputStream; +import java.io.StringWriter; +import java.io.Writer; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.function.Function; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static java.lang.String.format; +import static java.util.Arrays.asList; +import static java.util.Collections.emptyMap; +import static java.util.Collections.singleton; +import static java.util.Collections.singletonMap; + +/* + * @test + * @bug 8064925 + * @summary Basic test for ContentHandler. Ensures discovery paths for content + * handlers follow a particular order. + */ +public class ContentHandlersTest { + + public static void main(String[] args) throws Throwable { + step1_ContentHandlerFactory(); + step2_ServiceLoader(); + step3_UserDefined(); + step4_BuiltIn(); + } + + private static void step1_ContentHandlerFactory() throws IOException { + String factoryClassFqn = "net.java.openjdk.test.TestContentHandlerFactory"; + + Path tmp = Files.createDirectory(Paths.get("ContentHandlersTest-1")); + + Path src = templatesHome().resolve("test.template"); + Path dst = tmp.resolve("Test.java"); + Files.copy(src, dst); + + Path build = Files.createDirectory(tmp.resolve("build")); + + Path dst1 = fromTemplate(templatesHome().resolve("broken_factory.template"), + factoryClassFqn, tmp); + + javac(build, dst, dst1); + + Result r = java(emptyMap(), singleton(build), "Test", factoryClassFqn); + + if (r.exitValue == 0 || !r.output.startsWith( + stackTraceStringForBrokenFactory(factoryClassFqn))) { + throw new RuntimeException( + "Expected a different kind of failure: " + r.output); + } + } + + private static void step2_ServiceLoader() throws IOException { + String factoryClassFqn = "net.java.openjdk.test.TestContentHandlerFactory"; + + Path tmp = Files.createDirectory(Paths.get("ContentHandlersTest-2")); + + Path src = templatesHome().resolve("test.template"); + Path dst = tmp.resolve("Test.java"); + Files.copy(src, dst); + + Path dst1 = fromTemplate(templatesHome().resolve("broken_constructor_factory.template"), + factoryClassFqn, tmp); + + Path build = Files.createDirectory(tmp.resolve("build")); + + javac(build, dst); + + Path explodedJar = Files.createDirectory(tmp.resolve("exploded-jar")); + Path services = Files.createDirectories(explodedJar.resolve("META-INF") + .resolve("services")); + + Path s = services.resolve("java.net.ContentHandlerFactory"); + + try (FileWriter fw = new FileWriter(s.toFile())) { + fw.write(factoryClassFqn); + } + + javac(explodedJar, dst1); + jar(tmp.resolve("test.jar"), explodedJar); + + Files.copy(tmp.resolve("test.jar"), build.resolve("test.jar")); + + Result r = java(emptyMap(), asList(build.resolve("test.jar"), build), "Test"); + + if (r.exitValue == 0 || !verifyOutput(r.output, factoryClassFqn)) + throw new RuntimeException(r.output); + } + + private static void step3_UserDefined() throws IOException { + String packagePrefix = "net.java.openjdk.test"; + String fqn = packagePrefix + ".text.plain"; + + Path tmp = Files.createDirectory(Paths.get("ContentHandlersTest-3")); + + Path src = templatesHome().resolve("test.template"); + Path dst = tmp.resolve("Test.java"); + Files.copy(src, dst); + + Path dst1 = fromTemplate(templatesHome().resolve("plain.template"), + fqn, tmp); + + Path build = Files.createDirectory(tmp.resolve("build")); + + javac(build, dst); + + Path classes = Files.createDirectory(tmp.resolve("classes")); + + javac(classes, dst1); + + Map m = singletonMap("java.content.handler.pkgs", packagePrefix); + Result r = java(m, asList(build, classes), "Test"); + + if (r.exitValue != 0 || !r.output.contains(fqn)) + throw new RuntimeException(r.output); + } + + private static void step4_BuiltIn() throws IOException { + Path tmp = Files.createDirectory(Paths.get("ContentHandlersTest-4")); + + Path src = templatesHome().resolve("test.template"); + Path dst = tmp.resolve("Test.java"); + Files.copy(src, dst); + + Path build = Files.createDirectory(tmp.resolve("build")); + + javac(build, dst); + + Result r = java(emptyMap(), singleton(build), "Test"); + + if (r.exitValue != 0 || !r.output.contains("sun.net.www.content.text.PlainTextInputStream")) + throw new RuntimeException(r.output); + } + + private static String stackTraceStringForBrokenFactory(String fqn) { + return "Exception in thread \"main\" java.lang.RuntimeException: " + + "This is a broken factory. It is supposed to throw this exception."; + } + + private static Path fromTemplate(Path srcTemplate, + String factoryFqn, + Path dstFolder) throws IOException { + + String factorySimpleName, packageName; + int i = factoryFqn.lastIndexOf('.'); + if (i < 0) { + packageName = ""; + factorySimpleName = factoryFqn; + } else { + packageName = factoryFqn.substring(0, i); + factorySimpleName = factoryFqn.substring(i + 1); + } + + Path result = dstFolder.resolve(factorySimpleName + ".java"); + File dst = result.toFile(); + File src = srcTemplate.toFile(); + try (BufferedReader r = new BufferedReader(new FileReader(src)); + BufferedWriter w = new BufferedWriter(new FileWriter(dst))) { + + List lines = processTemplate(packageName, factorySimpleName, + r.lines()).collect(Collectors.toList()); + + Iterator it = lines.iterator(); + if (it.hasNext()) + w.write(it.next()); + while (it.hasNext()) { + w.newLine(); + w.write(it.next()); + } + } + return result; + } + + private static Stream processTemplate(String packageName, + String factorySimpleName, + Stream lines) { + Function pckg; + + if (packageName.isEmpty()) { + pckg = s -> s.contains("$package") ? "" : s; + } else { + pckg = s -> s.replaceAll("\\$package", packageName); + } + + Function factory + = s -> s.replaceAll("\\$className", factorySimpleName); + + return lines.map(pckg).map(factory); + } + + // IMO, that's the easiest way that gives you a fair amount of confidence in + // that j.u.ServiceLoader is loading a factory rather than Class.forName + private static boolean verifyOutput(String output, String fqn) { + String s1 = String.format("java.util.ServiceConfigurationError: " + + "java.net.ContentHandlerFactory: " + + "Provider %s could not be instantiated", fqn); + + return output.contains(s1); + } + + private static void jar(Path jarName, Path jarRoot) { + String jar = getJDKTool("jar"); + ProcessBuilder p = new ProcessBuilder(jar, "cf", jarName.toString(), + "-C", jarRoot.toString(), "."); + quickFail(run(p)); + } + + private static void javac(Path compilationOutput, Path... sourceFiles) { + String javac = getJDKTool("javac"); + List commands = new ArrayList<>(); + commands.addAll(asList(javac, "-d", compilationOutput.toString())); + List paths = asList(sourceFiles); + commands.addAll(paths.stream() + .map(Path::toString) + .collect(Collectors.toList())); + quickFail(run(new ProcessBuilder(commands))); + } + + private static void quickFail(Result r) { + if (r.exitValue != 0) + throw new RuntimeException(r.output); + } + + 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() + .stream() + .map(e -> "-D" + e.getKey() + "=" + e.getValue()) + .collect(Collectors.toList())); + + String cp = classpath.stream() + .map(Path::toString) + .collect(Collectors.joining(File.pathSeparator)); + commands.add("-cp"); + commands.add(cp); + commands.add(classname); + commands.addAll(Arrays.asList(args)); + + return run(new ProcessBuilder(commands)); + } + + private static Result run(ProcessBuilder b) { + Process p; + try { + p = b.start(); + } catch (IOException e) { + throw new RuntimeException( + format("Couldn't start process '%s'", b.command()), e); + } + + String output; + try { + output = toString(p.getInputStream(), p.getErrorStream()); + } catch (IOException e) { + throw new RuntimeException( + format("Couldn't read process output '%s'", b.command()), e); + } + + try { + p.waitFor(); + } catch (InterruptedException e) { + throw new RuntimeException( + format("Process hasn't finished '%s'", b.command()), e); + } + + return new Result(p.exitValue(), output); + } + + private static String getJDKTool(String name) { + String testJdk = System.getProperty("test.jdk"); + if (testJdk == null) + throw new RuntimeException("Please provide test.jdk property at a startup"); + return testJdk + File.separator + "bin" + File.separator + name; + } + + private static Path templatesHome() { + String testSrc = System.getProperty("test.src"); + if (testSrc == null) + throw new RuntimeException("Please provide test.src property at a startup"); + return Paths.get(testSrc); + } + + private static String toString(InputStream... src) throws IOException { + StringWriter dst = new StringWriter(); + Reader concatenated = + new InputStreamReader( + new SequenceInputStream( + Collections.enumeration(asList(src)))); + copy(concatenated, dst); + return dst.toString(); + } + + private static void copy(Reader src, Writer dst) throws IOException { + int len; + char[] buf = new char[1024]; + try { + while ((len = src.read(buf)) != -1) + dst.write(buf, 0, len); + } finally { + try { + src.close(); + } catch (IOException ignored1) { + } finally { + try { + dst.close(); + } catch (IOException ignored2) { + } + } + } + } + + private static class Result { + + final int exitValue; + final String output; + + private Result(int exitValue, String output) { + this.exitValue = exitValue; + this.output = output; + } + } +} diff --git a/jdk/test/java/net/URLConnection/ContentHandlers/broken_constructor_factory.template b/jdk/test/java/net/URLConnection/ContentHandlers/broken_constructor_factory.template new file mode 100644 index 00000000000..c3cfd7a6672 --- /dev/null +++ b/jdk/test/java/net/URLConnection/ContentHandlers/broken_constructor_factory.template @@ -0,0 +1,40 @@ +/* + * Copyright (c) 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. + */ + +package $package; + +import java.net.ContentHandler; +import java.net.ContentHandlerFactory; + +public class $className implements ContentHandlerFactory { + + public $className() { + throw new RuntimeException( + "This is a broken factory. It is supposed to throw this exception."); + } + + @Override + public ContentHandler createContentHandler(String mimetype) { + throw new RuntimeException( "This method is not supposed to be called."); + } +} diff --git a/jdk/test/java/net/URLConnection/ContentHandlers/broken_factory.template b/jdk/test/java/net/URLConnection/ContentHandlers/broken_factory.template new file mode 100644 index 00000000000..5be9dc29bd1 --- /dev/null +++ b/jdk/test/java/net/URLConnection/ContentHandlers/broken_factory.template @@ -0,0 +1,36 @@ +/* + * Copyright (c) 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. + */ + +package $package; + +import java.net.ContentHandler; +import java.net.ContentHandlerFactory; + +public class $className implements ContentHandlerFactory { + + @Override + public ContentHandler createContentHandler(String mimetype) { + throw new RuntimeException( + "This is a broken factory. It is supposed to throw this exception."); + } +} diff --git a/jdk/test/java/net/URLConnection/ContentHandlers/plain.template b/jdk/test/java/net/URLConnection/ContentHandlers/plain.template new file mode 100644 index 00000000000..775b6d43dbc --- /dev/null +++ b/jdk/test/java/net/URLConnection/ContentHandlers/plain.template @@ -0,0 +1,37 @@ +/* + * Copyright (c) 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. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package $package; + +import java.io.IOException; +import java.net.ContentHandler; +import java.net.URLConnection; + +public final class $className extends ContentHandler { + + @Override + public Object getContent(URLConnection urlc) throws IOException { + return this; + } +} diff --git a/jdk/test/java/net/URLConnection/ContentHandlers/test.template b/jdk/test/java/net/URLConnection/ContentHandlers/test.template new file mode 100644 index 00000000000..40142b64faf --- /dev/null +++ b/jdk/test/java/net/URLConnection/ContentHandlers/test.template @@ -0,0 +1,79 @@ +/* + * Copyright (c) 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. + */ + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.net.ContentHandlerFactory; +import java.net.URL; +import java.net.URLConnection; +import java.net.URLStreamHandler; +import java.net.URLStreamHandlerFactory; + +public class Test { + + public static void main(String[] args) throws Exception { + if (args.length > 0) { + String fqn = args[0]; + + @SuppressWarnings("unchecked") + Class c = + (Class) Class.forName(fqn); + + ContentHandlerFactory f = c.newInstance(); + + URLConnection.setContentHandlerFactory(f); + } + + // One does not simply use a ContentHandler... + // From an end user perspective ContentHandler is used indirectly + // and it's more like SPI rather than API. So there's a certain amount + // of preparations needs to be done beforehand. + + URLStreamHandlerFactory streamHandlerFactory = + (protocol) -> + new URLStreamHandler() { + @Override + protected URLConnection openConnection(URL u) { + return newUrlConnection(u); + } + }; + + URL.setURLStreamHandlerFactory(streamHandlerFactory); + + // Finally + Object content = new URL("whatever:").getContent(); + + System.out.println("Content class is: " + content.getClass()); + } + + private static URLConnection newUrlConnection(URL u) { + return new URLConnection(u) { + @Override public void connect() { } + + @Override + public InputStream getInputStream() { return null; } + + @Override public String getContentType() { return "text/plain"; } + }; + } +} From 5d91ae33528e0de3290c67a6e1d2c1008c6ec24e Mon Sep 17 00:00:00 2001 From: Weijun Wang Date: Mon, 13 Jul 2015 17:44:34 +0800 Subject: [PATCH 38/43] 8058290: JAAS Krb5LoginModule has suspect ticket-renewal logic, relies on clockskew grace Reviewed-by: mullan --- .../security/auth/module/Krb5LoginModule.java | 46 +++++--- jdk/test/sun/security/krb5/auto/KDC.java | 4 +- jdk/test/sun/security/krb5/auto/Renew.java | 106 ++++++++++++++++++ 3 files changed, 141 insertions(+), 15 deletions(-) create mode 100644 jdk/test/sun/security/krb5/auto/Renew.java diff --git a/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/module/Krb5LoginModule.java b/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/module/Krb5LoginModule.java index 5bd179db91a..242363243d7 100644 --- a/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/module/Krb5LoginModule.java +++ b/jdk/src/jdk.security.auth/share/classes/com/sun/security/auth/module/Krb5LoginModule.java @@ -122,8 +122,9 @@ import sun.misc.HexDumpEncoder; * must also be set to true; Otherwise a configuration error will * be returned. *
      {@code renewTGT}:
      - *
      Set this to true, if you want to renew - * the TGT. If this is set, {@code useTicketCache} must also be + *
      Set this to true, if you want to renew the TGT when it's more than + * half-way expired (the time until expiration is less than the time + * since start time). If this is set, {@code useTicketCache} must also be * set to true; otherwise a configuration error will be returned.
      *
      {@code doNotPrompt}:
      *
      Set this to true if you do not want to be @@ -649,18 +650,20 @@ public class Krb5LoginModule implements LoginModule { (principal, ticketCacheName); if (cred != null) { - // check to renew credentials - if (!isCurrent(cred)) { - if (renewTGT) { - cred = renewCredentials(cred); - } else { - // credentials have expired - cred = null; - if (debug) - System.out.println("Credentials are" + - " no longer valid"); + if (renewTGT && isOld(cred)) { + // renew if ticket is old. + Credentials newCred = renewCredentials(cred); + if (newCred != null) { + cred = newCred; } } + if (!isCurrent(cred)) { + // credentials have expired + cred = null; + if (debug) + System.out.println("Credentials are" + + " no longer valid"); + } } if (cred != null) { @@ -968,7 +971,7 @@ public class Krb5LoginModule implements LoginModule { } } - private boolean isCurrent(Credentials creds) + private static boolean isCurrent(Credentials creds) { Date endTime = creds.getEndTime(); if (endTime != null) { @@ -977,6 +980,23 @@ public class Krb5LoginModule implements LoginModule { return true; } + private static boolean isOld(Credentials creds) + { + Date endTime = creds.getEndTime(); + if (endTime != null) { + Date authTime = creds.getAuthTime(); + long now = System.currentTimeMillis(); + if (authTime != null) { + // pass the mid between auth and end + return now - authTime.getTime() > endTime.getTime() - now; + } else { + // will expire in less than 2 hours + return now <= endTime.getTime() - 1000*3600*2L; + } + } + return false; + } + private Credentials renewCredentials(Credentials creds) { Credentials lcreds; diff --git a/jdk/test/sun/security/krb5/auto/KDC.java b/jdk/test/sun/security/krb5/auto/KDC.java index d4a919f7a76..7488fa53ec4 100644 --- a/jdk/test/sun/security/krb5/auto/KDC.java +++ b/jdk/test/sun/security/krb5/auto/KDC.java @@ -811,7 +811,7 @@ public class KDC { new TransitedEncoding(1, new byte[0]), // TODO new KerberosTime(new Date()), body.from, - till, body.rtime, + till, etp.renewTill, body.addresses != null ? body.addresses : etp.caddr, null); @@ -834,7 +834,7 @@ public class KDC { tFlags, new KerberosTime(new Date()), body.from, - till, body.rtime, + till, etp.renewTill, service, body.addresses ); diff --git a/jdk/test/sun/security/krb5/auto/Renew.java b/jdk/test/sun/security/krb5/auto/Renew.java new file mode 100644 index 00000000000..a8327cddd9b --- /dev/null +++ b/jdk/test/sun/security/krb5/auto/Renew.java @@ -0,0 +1,106 @@ +/* + * Copyright (c) 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 + * @bug 8058290 + * @summary JAAS Krb5LoginModule has suspect ticket-renewal logic, + * relies on clockskew grace + * @modules java.base/sun.net.spi.nameservice + * java.base/sun.security.util + * java.security.jgss/sun.security.krb5 + * java.security.jgss/sun.security.krb5.internal + * java.security.jgss/sun.security.krb5.internal.ccache + * java.security.jgss/sun.security.krb5.internal.crypto + * java.security.jgss/sun.security.krb5.internal.ktab + * @compile -XDignore.symbol.file Renew.java + * @run main/othervm Renew 1 + * @run main/othervm Renew 2 + * @run main/othervm Renew 3 + */ + +import sun.security.krb5.Config; + +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.Arrays; +import java.util.Date; +import javax.security.auth.kerberos.KerberosTicket; + +public class Renew { + + public static void main(String[] args) throws Exception { + + // Three test cases: + // 1. renewTGT=false + // 2. renewTGT=true with a short life time, renew will happen + // 3. renewTGT=true with a long life time, renew won't happen + int test = Integer.parseInt(args[0]); + + OneKDC k = new OneKDC(null); + KDC.saveConfig(OneKDC.KRB5_CONF, k, + "renew_lifetime = 1d", + "ticket_lifetime = " + (test == 2? "10s": "8h")); + Config.refresh(); + k.writeJAASConf(); + + // KDC would save ccache in a file + System.setProperty("test.kdc.save.ccache", "cache.here"); + + Files.write(Paths.get(OneKDC.JAAS_CONF), Arrays.asList( + "first {", + " com.sun.security.auth.module.Krb5LoginModule required;", + "};", + "second {", + " com.sun.security.auth.module.Krb5LoginModule required", + " doNotPrompt=true", + " renewTGT=" + (test != 1), + " useTicketCache=true", + " ticketCache=cache.here;", + "};" + )); + + Context c; + + // The first login uses username and password + c = Context.fromUserPass(OneKDC.USER, OneKDC.PASS, false); + Date d1 = c.s().getPrivateCredentials(KerberosTicket.class).iterator().next().getAuthTime(); + + // 6s is longer than half of 10s + Thread.sleep(6000); + + // The second login uses the cache + c = Context.fromJAAS("second"); + Date d2 = c.s().getPrivateCredentials(KerberosTicket.class).iterator().next().getAuthTime(); + + if (test == 2) { + if (d1.equals(d2)) { + throw new Exception("Ticket not renewed"); + } + } else { + if (!d1.equals(d2)) { + throw new Exception("Ticket renewed"); + } + } + } +} From 5744f4fc302836671d9ec321e6b7631aafd90b7a Mon Sep 17 00:00:00 2001 From: Paul Sandoz Date: Tue, 9 Jun 2015 07:10:03 +0100 Subject: [PATCH 39/43] 8071597: Add Stream dropWhile and takeWhile operations Reviewed-by: briangoetz, smarks, chegar, forax --- .../java/util/stream/AbstractPipeline.java | 9 +- .../java/util/stream/DoublePipeline.java | 17 +- .../java/util/stream/DoubleStream.java | 138 +- .../classes/java/util/stream/IntPipeline.java | 16 +- .../classes/java/util/stream/IntStream.java | 131 +- .../java/util/stream/LongPipeline.java | 16 +- .../classes/java/util/stream/LongStream.java | 138 +- .../share/classes/java/util/stream/Node.java | 26 +- .../share/classes/java/util/stream/Nodes.java | 10 +- .../java/util/stream/PipelineHelper.java | 5 +- .../java/util/stream/ReferencePipeline.java | 16 +- .../classes/java/util/stream/SliceOps.java | 7 +- .../classes/java/util/stream/Stream.java | 130 +- .../classes/java/util/stream/WhileOps.java | 1394 +++++++++++++++++ .../util/stream/DefaultMethodStreams.java | 984 ++++++++++++ .../util/stream/StreamTestDataProvider.java | 4 +- .../java/util/stream/WhileOpStatefulTest.java | 304 ++++ .../tests/java/util/stream/WhileOpTest.java | 361 +++++ 18 files changed, 3665 insertions(+), 41 deletions(-) create mode 100644 jdk/src/java.base/share/classes/java/util/stream/WhileOps.java create mode 100644 jdk/test/java/util/stream/bootlib/java/util/stream/DefaultMethodStreams.java create mode 100644 jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/WhileOpStatefulTest.java create mode 100644 jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/WhileOpTest.java diff --git a/jdk/src/java.base/share/classes/java/util/stream/AbstractPipeline.java b/jdk/src/java.base/share/classes/java/util/stream/AbstractPipeline.java index d33b9083a01..84199462c80 100644 --- a/jdk/src/java.base/share/classes/java/util/stream/AbstractPipeline.java +++ b/jdk/src/java.base/share/classes/java/util/stream/AbstractPipeline.java @@ -489,15 +489,17 @@ abstract class AbstractPipeline> @Override @SuppressWarnings("unchecked") - final void copyIntoWithCancel(Sink wrappedSink, Spliterator spliterator) { + final boolean copyIntoWithCancel(Sink wrappedSink, Spliterator spliterator) { @SuppressWarnings({"rawtypes","unchecked"}) AbstractPipeline p = AbstractPipeline.this; while (p.depth > 0) { p = p.previousStage; } + wrappedSink.begin(spliterator.getExactSizeIfKnown()); - p.forEachWithCancel(spliterator, wrappedSink); + boolean cancelled = p.forEachWithCancel(spliterator, wrappedSink); wrappedSink.end(); + return cancelled; } @Override @@ -602,8 +604,9 @@ abstract class AbstractPipeline> * * @param spliterator the spliterator to pull elements from * @param sink the sink to push elements to + * @return true if the cancellation was requested */ - abstract void forEachWithCancel(Spliterator spliterator, Sink sink); + abstract boolean forEachWithCancel(Spliterator spliterator, Sink sink); /** * Make a node builder compatible with this stream shape. diff --git a/jdk/src/java.base/share/classes/java/util/stream/DoublePipeline.java b/jdk/src/java.base/share/classes/java/util/stream/DoublePipeline.java index eb1d97195e5..56a5f57cc57 100644 --- a/jdk/src/java.base/share/classes/java/util/stream/DoublePipeline.java +++ b/jdk/src/java.base/share/classes/java/util/stream/DoublePipeline.java @@ -40,6 +40,7 @@ import java.util.function.DoubleToIntFunction; import java.util.function.DoubleToLongFunction; import java.util.function.DoubleUnaryOperator; import java.util.function.IntFunction; +import java.util.function.LongPredicate; import java.util.function.ObjDoubleConsumer; import java.util.function.Supplier; @@ -153,10 +154,12 @@ abstract class DoublePipeline } @Override - final void forEachWithCancel(Spliterator spliterator, Sink sink) { + final boolean forEachWithCancel(Spliterator spliterator, Sink sink) { Spliterator.OfDouble spl = adapt(spliterator); DoubleConsumer adaptedSink = adapt(sink); - do { } while (!sink.cancellationRequested() && spl.tryAdvance(adaptedSink)); + boolean cancelled; + do { } while (!(cancelled = sink.cancellationRequested()) && spl.tryAdvance(adaptedSink)); + return cancelled; } @Override @@ -352,6 +355,16 @@ abstract class DoublePipeline } } + @Override + public final DoubleStream takeWhile(DoublePredicate predicate) { + return WhileOps.makeTakeWhileDouble(this, predicate); + } + + @Override + public final DoubleStream dropWhile(DoublePredicate predicate) { + return WhileOps.makeDropWhileDouble(this, predicate); + } + @Override public final DoubleStream sorted() { return SortedOps.makeDouble(this); diff --git a/jdk/src/java.base/share/classes/java/util/stream/DoubleStream.java b/jdk/src/java.base/share/classes/java/util/stream/DoubleStream.java index 8f272bf4b1d..862f81e9e64 100644 --- a/jdk/src/java.base/share/classes/java/util/stream/DoubleStream.java +++ b/jdk/src/java.base/share/classes/java/util/stream/DoubleStream.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 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 @@ -24,18 +24,13 @@ */ package java.util.stream; -import java.nio.charset.Charset; -import java.nio.file.Files; -import java.nio.file.Path; import java.util.Arrays; -import java.util.Collection; import java.util.DoubleSummaryStatistics; import java.util.Objects; import java.util.OptionalDouble; import java.util.PrimitiveIterator; import java.util.Spliterator; import java.util.Spliterators; -import java.util.concurrent.ConcurrentHashMap; import java.util.function.BiConsumer; import java.util.function.DoubleBinaryOperator; import java.util.function.DoubleConsumer; @@ -279,6 +274,137 @@ public interface DoubleStream extends BaseStream { */ DoubleStream skip(long n); + /** + * Returns, if this stream is ordered, a stream consisting of the longest + * prefix of elements taken from this stream that match the given predicate. + * Otherwise returns, if this stream is unordered, a stream consisting of a + * subset of elements taken from this stream that match the given predicate. + * + *

      If this stream is ordered then the longest prefix is a contiguous + * sequence of elements of this stream that match the given predicate. The + * first element of the sequence is the first element of this stream, and + * the element immediately following the last element of the sequence does + * not match the given predicate. + * + *

      If this stream is unordered, and some (but not all) elements of this + * stream match the given predicate, then the behavior of this operation is + * nondeterministic; it is free to take any subset of matching elements + * (which includes the empty set). + * + *

      Independent of whether this stream is ordered or unordered if all + * elements of this stream match the given predicate then this operation + * takes all elements (the result is the same is the input), or if no + * elements of the stream match the given predicate then no elements are + * taken (the result is an empty stream). + * + *

      This is a short-circuiting + * stateful intermediate operation. + * + * @implSpec + * The default implementation obtains the {@link #spliterator() spliterator} + * of this stream, wraps that spliterator so as to support the semantics + * of this operation on traversal, and returns a new stream associated with + * the wrapped spliterator. The returned stream preserves the execution + * characteristics of this stream (namely parallel or sequential execution + * as per {@link #isParallel()}) but the wrapped spliterator may choose to + * not support splitting. When the returned stream is closed, the close + * handlers for both the returned and this stream are invoked. + * + * @apiNote + * While {@code takeWhile()} is generally a cheap operation on sequential + * stream pipelines, it can be quite expensive on ordered parallel + * pipelines, since the operation is constrained to return not just any + * valid prefix, but the longest prefix of elements in the encounter order. + * Using an unordered stream source (such as + * {@link #generate(DoubleSupplier)}) or removing the ordering constraint + * with {@link #unordered()} may result in significant speedups of + * {@code takeWhile()} in parallel pipelines, if the semantics of your + * situation permit. If consistency with encounter order is required, and + * you are experiencing poor performance or memory utilization with + * {@code takeWhile()} in parallel pipelines, switching to sequential + * execution with {@link #sequential()} may improve performance. + * + * @param predicate a non-interfering, + * stateless + * predicate to apply to elements to determine the longest + * prefix of elements. + * @return the new stream + */ + default DoubleStream takeWhile(DoublePredicate predicate) { + Objects.requireNonNull(predicate); + // Reuses the unordered spliterator, which, when encounter is present, + // is safe to use as long as it configured not to split + return StreamSupport.doubleStream( + new WhileOps.UnorderedWhileSpliterator.OfDouble.Taking(spliterator(), true, predicate), + isParallel()).onClose(this::close); + } + + /** + * Returns, if this stream is ordered, a stream consisting of the remaining + * elements of this stream after dropping the longest prefix of elements + * that match the given predicate. Otherwise returns, if this stream is + * unordered, a stream consisting of the remaining elements of this stream + * after dropping a subset of elements that match the given predicate. + * + *

      If this stream is ordered then the longest prefix is a contiguous + * sequence of elements of this stream that match the given predicate. The + * first element of the sequence is the first element of this stream, and + * the element immediately following the last element of the sequence does + * not match the given predicate. + * + *

      If this stream is unordered, and some (but not all) elements of this + * stream match the given predicate, then the behavior of this operation is + * nondeterministic; it is free to drop any subset of matching elements + * (which includes the empty set). + * + *

      Independent of whether this stream is ordered or unordered if all + * elements of this stream match the given predicate then this operation + * drops all elements (the result is an empty stream), or if no elements of + * the stream match the given predicate then no elements are dropped (the + * result is the same is the input). + * + *

      This is a stateful + * intermediate operation. + * + * @implSpec + * The default implementation obtains the {@link #spliterator() spliterator} + * of this stream, wraps that spliterator so as to support the semantics + * of this operation on traversal, and returns a new stream associated with + * the wrapped spliterator. The returned stream preserves the execution + * characteristics of this stream (namely parallel or sequential execution + * as per {@link #isParallel()}) but the wrapped spliterator may choose to + * not support splitting. When the returned stream is closed, the close + * handlers for both the returned and this stream are invoked. + * + * @apiNote + * While {@code dropWhile()} is generally a cheap operation on sequential + * stream pipelines, it can be quite expensive on ordered parallel + * pipelines, since the operation is constrained to return not just any + * valid prefix, but the longest prefix of elements in the encounter order. + * Using an unordered stream source (such as + * {@link #generate(DoubleSupplier)}) or removing the ordering constraint + * with {@link #unordered()} may result in significant speedups of + * {@code dropWhile()} in parallel pipelines, if the semantics of your + * situation permit. If consistency with encounter order is required, and + * you are experiencing poor performance or memory utilization with + * {@code dropWhile()} in parallel pipelines, switching to sequential + * execution with {@link #sequential()} may improve performance. + * + * @param predicate a non-interfering, + * stateless + * predicate to apply to elements to determine the longest + * prefix of elements. + * @return the new stream + */ + default DoubleStream dropWhile(DoublePredicate predicate) { + Objects.requireNonNull(predicate); + // Reuses the unordered spliterator, which, when encounter is present, + // is safe to use as long as it configured not to split + return StreamSupport.doubleStream( + new WhileOps.UnorderedWhileSpliterator.OfDouble.Dropping(spliterator(), true, predicate), + isParallel()).onClose(this::close); + } + /** * Performs an action for each element of this stream. * diff --git a/jdk/src/java.base/share/classes/java/util/stream/IntPipeline.java b/jdk/src/java.base/share/classes/java/util/stream/IntPipeline.java index 9c0162f1ce3..7cf0622ce89 100644 --- a/jdk/src/java.base/share/classes/java/util/stream/IntPipeline.java +++ b/jdk/src/java.base/share/classes/java/util/stream/IntPipeline.java @@ -156,10 +156,12 @@ abstract class IntPipeline } @Override - final void forEachWithCancel(Spliterator spliterator, Sink sink) { + final boolean forEachWithCancel(Spliterator spliterator, Sink sink) { Spliterator.OfInt spl = adapt(spliterator); IntConsumer adaptedSink = adapt(sink); - do { } while (!sink.cancellationRequested() && spl.tryAdvance(adaptedSink)); + boolean cancelled; + do { } while (!(cancelled = sink.cancellationRequested()) && spl.tryAdvance(adaptedSink)); + return cancelled; } @Override @@ -386,6 +388,16 @@ abstract class IntPipeline return SliceOps.makeInt(this, n, -1); } + @Override + public final IntStream takeWhile(IntPredicate predicate) { + return WhileOps.makeTakeWhileInt(this, predicate); + } + + @Override + public final IntStream dropWhile(IntPredicate predicate) { + return WhileOps.makeDropWhileInt(this, predicate); + } + @Override public final IntStream sorted() { return SortedOps.makeInt(this); diff --git a/jdk/src/java.base/share/classes/java/util/stream/IntStream.java b/jdk/src/java.base/share/classes/java/util/stream/IntStream.java index 4bb1ab5b97e..675b6fd307a 100644 --- a/jdk/src/java.base/share/classes/java/util/stream/IntStream.java +++ b/jdk/src/java.base/share/classes/java/util/stream/IntStream.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 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 @@ -272,6 +272,135 @@ public interface IntStream extends BaseStream { */ IntStream skip(long n); + /** + * Returns, if this stream is ordered, a stream consisting of the longest + * prefix of elements taken from this stream that match the given predicate. + * Otherwise returns, if this stream is unordered, a stream consisting of a + * subset of elements taken from this stream that match the given predicate. + * + *

      If this stream is ordered then the longest prefix is a contiguous + * sequence of elements of this stream that match the given predicate. The + * first element of the sequence is the first element of this stream, and + * the element immediately following the last element of the sequence does + * not match the given predicate. + * + *

      If this stream is unordered, and some (but not all) elements of this + * stream match the given predicate, then the behavior of this operation is + * nondeterministic; it is free to take any subset of matching elements + * (which includes the empty set). + * + *

      Independent of whether this stream is ordered or unordered if all + * elements of this stream match the given predicate then this operation + * takes all elements (the result is the same is the input), or if no + * elements of the stream match the given predicate then no elements are + * taken (the result is an empty stream). + * + *

      This is a short-circuiting + * stateful intermediate operation. + * + * @implSpec + * The default implementation obtains the {@link #spliterator() spliterator} + * of this stream, wraps that spliterator so as to support the semantics + * of this operation on traversal, and returns a new stream associated with + * the wrapped spliterator. The returned stream preserves the execution + * characteristics of this stream (namely parallel or sequential execution + * as per {@link #isParallel()}) but the wrapped spliterator may choose to + * not support splitting. When the returned stream is closed, the close + * handlers for both the returned and this stream are invoked. + * + * @apiNote + * While {@code takeWhile()} is generally a cheap operation on sequential + * stream pipelines, it can be quite expensive on ordered parallel + * pipelines, since the operation is constrained to return not just any + * valid prefix, but the longest prefix of elements in the encounter order. + * Using an unordered stream source (such as {@link #generate(IntSupplier)}) + * or removing the ordering constraint with {@link #unordered()} may result + * in significant speedups of {@code takeWhile()} in parallel pipelines, if + * the semantics of your situation permit. If consistency with encounter + * order is required, and you are experiencing poor performance or memory + * utilization with {@code takeWhile()} in parallel pipelines, switching to + * sequential execution with {@link #sequential()} may improve performance. + * + * @param predicate a non-interfering, + * stateless + * predicate to apply to elements to determine the longest + * prefix of elements. + * @return the new stream + */ + default IntStream takeWhile(IntPredicate predicate) { + Objects.requireNonNull(predicate); + // Reuses the unordered spliterator, which, when encounter is present, + // is safe to use as long as it configured not to split + return StreamSupport.intStream( + new WhileOps.UnorderedWhileSpliterator.OfInt.Taking(spliterator(), true, predicate), + isParallel()).onClose(this::close); + } + + /** + * Returns, if this stream is ordered, a stream consisting of the remaining + * elements of this stream after dropping the longest prefix of elements + * that match the given predicate. Otherwise returns, if this stream is + * unordered, a stream consisting of the remaining elements of this stream + * after dropping a subset of elements that match the given predicate. + * + *

      If this stream is ordered then the longest prefix is a contiguous + * sequence of elements of this stream that match the given predicate. The + * first element of the sequence is the first element of this stream, and + * the element immediately following the last element of the sequence does + * not match the given predicate. + * + *

      If this stream is unordered, and some (but not all) elements of this + * stream match the given predicate, then the behavior of this operation is + * nondeterministic; it is free to drop any subset of matching elements + * (which includes the empty set). + * + *

      Independent of whether this stream is ordered or unordered if all + * elements of this stream match the given predicate then this operation + * drops all elements (the result is an empty stream), or if no elements of + * the stream match the given predicate then no elements are dropped (the + * result is the same is the input). + * + *

      This is a stateful + * intermediate operation. + * + * @implSpec + * The default implementation obtains the {@link #spliterator() spliterator} + * of this stream, wraps that spliterator so as to support the semantics + * of this operation on traversal, and returns a new stream associated with + * the wrapped spliterator. The returned stream preserves the execution + * characteristics of this stream (namely parallel or sequential execution + * as per {@link #isParallel()}) but the wrapped spliterator may choose to + * not support splitting. When the returned stream is closed, the close + * handlers for both the returned and this stream are invoked. + * + * @apiNote + * While {@code dropWhile()} is generally a cheap operation on sequential + * stream pipelines, it can be quite expensive on ordered parallel + * pipelines, since the operation is constrained to return not just any + * valid prefix, but the longest prefix of elements in the encounter order. + * Using an unordered stream source (such as {@link #generate(IntSupplier)}) + * or removing the ordering constraint with {@link #unordered()} may result + * in significant speedups of {@code dropWhile()} in parallel pipelines, if + * the semantics of your situation permit. If consistency with encounter + * order is required, and you are experiencing poor performance or memory + * utilization with {@code dropWhile()} in parallel pipelines, switching to + * sequential execution with {@link #sequential()} may improve performance. + * + * @param predicate a non-interfering, + * stateless + * predicate to apply to elements to determine the longest + * prefix of elements. + * @return the new stream + */ + default IntStream dropWhile(IntPredicate predicate) { + Objects.requireNonNull(predicate); + // Reuses the unordered spliterator, which, when encounter is present, + // is safe to use as long as it configured not to split + return StreamSupport.intStream( + new WhileOps.UnorderedWhileSpliterator.OfInt.Dropping(spliterator(), true, predicate), + isParallel()).onClose(this::close); + } + /** * Performs an action for each element of this stream. * diff --git a/jdk/src/java.base/share/classes/java/util/stream/LongPipeline.java b/jdk/src/java.base/share/classes/java/util/stream/LongPipeline.java index 7a84ff997e7..19097b7e630 100644 --- a/jdk/src/java.base/share/classes/java/util/stream/LongPipeline.java +++ b/jdk/src/java.base/share/classes/java/util/stream/LongPipeline.java @@ -154,10 +154,12 @@ abstract class LongPipeline } @Override - final void forEachWithCancel(Spliterator spliterator, Sink sink) { + final boolean forEachWithCancel(Spliterator spliterator, Sink sink) { Spliterator.OfLong spl = adapt(spliterator); LongConsumer adaptedSink = adapt(sink); - do { } while (!sink.cancellationRequested() && spl.tryAdvance(adaptedSink)); + boolean cancelled; + do { } while (!(cancelled = sink.cancellationRequested()) && spl.tryAdvance(adaptedSink)); + return cancelled; } @Override @@ -367,6 +369,16 @@ abstract class LongPipeline return SliceOps.makeLong(this, n, -1); } + @Override + public final LongStream takeWhile(LongPredicate predicate) { + return WhileOps.makeTakeWhileLong(this, predicate); + } + + @Override + public final LongStream dropWhile(LongPredicate predicate) { + return WhileOps.makeDropWhileLong(this, predicate); + } + @Override public final LongStream sorted() { return SortedOps.makeLong(this); diff --git a/jdk/src/java.base/share/classes/java/util/stream/LongStream.java b/jdk/src/java.base/share/classes/java/util/stream/LongStream.java index 4f9c72bef42..dc6009f65fd 100644 --- a/jdk/src/java.base/share/classes/java/util/stream/LongStream.java +++ b/jdk/src/java.base/share/classes/java/util/stream/LongStream.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 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 @@ -24,11 +24,7 @@ */ package java.util.stream; -import java.nio.charset.Charset; -import java.nio.file.Files; -import java.nio.file.Path; import java.util.Arrays; -import java.util.Collection; import java.util.LongSummaryStatistics; import java.util.Objects; import java.util.OptionalDouble; @@ -36,7 +32,6 @@ import java.util.OptionalLong; import java.util.PrimitiveIterator; import java.util.Spliterator; import java.util.Spliterators; -import java.util.concurrent.ConcurrentHashMap; import java.util.function.BiConsumer; import java.util.function.Function; import java.util.function.LongBinaryOperator; @@ -277,6 +272,137 @@ public interface LongStream extends BaseStream { */ LongStream skip(long n); + /** + * Returns, if this stream is ordered, a stream consisting of the longest + * prefix of elements taken from this stream that match the given predicate. + * Otherwise returns, if this stream is unordered, a stream consisting of a + * subset of elements taken from this stream that match the given predicate. + * + *

      If this stream is ordered then the longest prefix is a contiguous + * sequence of elements of this stream that match the given predicate. The + * first element of the sequence is the first element of this stream, and + * the element immediately following the last element of the sequence does + * not match the given predicate. + * + *

      If this stream is unordered, and some (but not all) elements of this + * stream match the given predicate, then the behavior of this operation is + * nondeterministic; it is free to take any subset of matching elements + * (which includes the empty set). + * + *

      Independent of whether this stream is ordered or unordered if all + * elements of this stream match the given predicate then this operation + * takes all elements (the result is the same is the input), or if no + * elements of the stream match the given predicate then no elements are + * taken (the result is an empty stream). + * + *

      This is a short-circuiting + * stateful intermediate operation. + * + * @implSpec + * The default implementation obtains the {@link #spliterator() spliterator} + * of this stream, wraps that spliterator so as to support the semantics + * of this operation on traversal, and returns a new stream associated with + * the wrapped spliterator. The returned stream preserves the execution + * characteristics of this stream (namely parallel or sequential execution + * as per {@link #isParallel()}) but the wrapped spliterator may choose to + * not support splitting. When the returned stream is closed, the close + * handlers for both the returned and this stream are invoked. + * + * @apiNote + * While {@code takeWhile()} is generally a cheap operation on sequential + * stream pipelines, it can be quite expensive on ordered parallel + * pipelines, since the operation is constrained to return not just any + * valid prefix, but the longest prefix of elements in the encounter order. + * Using an unordered stream source (such as + * {@link #generate(LongSupplier)}) or removing the ordering constraint with + * {@link #unordered()} may result in significant speedups of + * {@code takeWhile()} in parallel pipelines, if the semantics of your + * situation permit. If consistency with encounter order is required, and + * you are experiencing poor performance or memory utilization with + * {@code takeWhile()} in parallel pipelines, switching to sequential + * execution with {@link #sequential()} may improve performance. + * + * @param predicate a non-interfering, + * stateless + * predicate to apply to elements to determine the longest + * prefix of elements. + * @return the new stream + */ + default LongStream takeWhile(LongPredicate predicate) { + Objects.requireNonNull(predicate); + // Reuses the unordered spliterator, which, when encounter is present, + // is safe to use as long as it configured not to split + return StreamSupport.longStream( + new WhileOps.UnorderedWhileSpliterator.OfLong.Taking(spliterator(), true, predicate), + isParallel()).onClose(this::close); + } + + /** + * Returns, if this stream is ordered, a stream consisting of the remaining + * elements of this stream after dropping the longest prefix of elements + * that match the given predicate. Otherwise returns, if this stream is + * unordered, a stream consisting of the remaining elements of this stream + * after dropping a subset of elements that match the given predicate. + * + *

      If this stream is ordered then the longest prefix is a contiguous + * sequence of elements of this stream that match the given predicate. The + * first element of the sequence is the first element of this stream, and + * the element immediately following the last element of the sequence does + * not match the given predicate. + * + *

      If this stream is unordered, and some (but not all) elements of this + * stream match the given predicate, then the behavior of this operation is + * nondeterministic; it is free to drop any subset of matching elements + * (which includes the empty set). + * + *

      Independent of whether this stream is ordered or unordered if all + * elements of this stream match the given predicate then this operation + * drops all elements (the result is an empty stream), or if no elements of + * the stream match the given predicate then no elements are dropped (the + * result is the same is the input). + * + *

      This is a stateful + * intermediate operation. + * + * @implSpec + * The default implementation obtains the {@link #spliterator() spliterator} + * of this stream, wraps that spliterator so as to support the semantics + * of this operation on traversal, and returns a new stream associated with + * the wrapped spliterator. The returned stream preserves the execution + * characteristics of this stream (namely parallel or sequential execution + * as per {@link #isParallel()}) but the wrapped spliterator may choose to + * not support splitting. When the returned stream is closed, the close + * handlers for both the returned and this stream are invoked. + * + * @apiNote + * While {@code dropWhile()} is generally a cheap operation on sequential + * stream pipelines, it can be quite expensive on ordered parallel + * pipelines, since the operation is constrained to return not just any + * valid prefix, but the longest prefix of elements in the encounter order. + * Using an unordered stream source (such as + * {@link #generate(LongSupplier)}) or removing the ordering constraint with + * {@link #unordered()} may result in significant speedups of + * {@code dropWhile()} in parallel pipelines, if the semantics of your + * situation permit. If consistency with encounter order is required, and + * you are experiencing poor performance or memory utilization with + * {@code dropWhile()} in parallel pipelines, switching to sequential + * execution with {@link #sequential()} may improve performance. + * + * @param predicate a non-interfering, + * stateless + * predicate to apply to elements to determine the longest + * prefix of elements. + * @return the new stream + */ + default LongStream dropWhile(LongPredicate predicate) { + Objects.requireNonNull(predicate); + // Reuses the unordered spliterator, which, when encounter is present, + // is safe to use as long as it configured not to split + return StreamSupport.longStream( + new WhileOps.UnorderedWhileSpliterator.OfLong.Dropping(spliterator(), true, predicate), + isParallel()).onClose(this::close); + } + /** * Performs an action for each element of this stream. * diff --git a/jdk/src/java.base/share/classes/java/util/stream/Node.java b/jdk/src/java.base/share/classes/java/util/stream/Node.java index 2b4360bea57..131195944ee 100644 --- a/jdk/src/java.base/share/classes/java/util/stream/Node.java +++ b/jdk/src/java.base/share/classes/java/util/stream/Node.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 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 @@ -125,7 +125,11 @@ interface Node { Node.Builder nodeBuilder = Nodes.builder(size, generator); nodeBuilder.begin(size); for (int i = 0; i < from && spliterator.tryAdvance(e -> { }); i++) { } - for (int i = 0; (i < size) && spliterator.tryAdvance(nodeBuilder); i++) { } + if (to == count()) { + spliterator.forEachRemaining(nodeBuilder); + } else { + for (int i = 0; i < size && spliterator.tryAdvance(nodeBuilder); i++) { } + } nodeBuilder.end(); return nodeBuilder.build(); } @@ -360,7 +364,11 @@ interface Node { Node.Builder.OfInt nodeBuilder = Nodes.intBuilder(size); nodeBuilder.begin(size); for (int i = 0; i < from && spliterator.tryAdvance((IntConsumer) e -> { }); i++) { } - for (int i = 0; (i < size) && spliterator.tryAdvance((IntConsumer) nodeBuilder); i++) { } + if (to == count()) { + spliterator.forEachRemaining((IntConsumer) nodeBuilder); + } else { + for (int i = 0; i < size && spliterator.tryAdvance((IntConsumer) nodeBuilder); i++) { } + } nodeBuilder.end(); return nodeBuilder.build(); } @@ -433,7 +441,11 @@ interface Node { Node.Builder.OfLong nodeBuilder = Nodes.longBuilder(size); nodeBuilder.begin(size); for (int i = 0; i < from && spliterator.tryAdvance((LongConsumer) e -> { }); i++) { } - for (int i = 0; (i < size) && spliterator.tryAdvance((LongConsumer) nodeBuilder); i++) { } + if (to == count()) { + spliterator.forEachRemaining((LongConsumer) nodeBuilder); + } else { + for (int i = 0; i < size && spliterator.tryAdvance((LongConsumer) nodeBuilder); i++) { } + } nodeBuilder.end(); return nodeBuilder.build(); } @@ -508,7 +520,11 @@ interface Node { Node.Builder.OfDouble nodeBuilder = Nodes.doubleBuilder(size); nodeBuilder.begin(size); for (int i = 0; i < from && spliterator.tryAdvance((DoubleConsumer) e -> { }); i++) { } - for (int i = 0; (i < size) && spliterator.tryAdvance((DoubleConsumer) nodeBuilder); i++) { } + if (to == count()) { + spliterator.forEachRemaining((DoubleConsumer) nodeBuilder); + } else { + for (int i = 0; i < size && spliterator.tryAdvance((DoubleConsumer) nodeBuilder); i++) { } + } nodeBuilder.end(); return nodeBuilder.build(); } diff --git a/jdk/src/java.base/share/classes/java/util/stream/Nodes.java b/jdk/src/java.base/share/classes/java/util/stream/Nodes.java index c18540c4e6e..8a517b0f263 100644 --- a/jdk/src/java.base/share/classes/java/util/stream/Nodes.java +++ b/jdk/src/java.base/share/classes/java/util/stream/Nodes.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 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 @@ -69,6 +69,14 @@ final class Nodes { private static final Node.OfLong EMPTY_LONG_NODE = new EmptyNode.OfLong(); private static final Node.OfDouble EMPTY_DOUBLE_NODE = new EmptyNode.OfDouble(); + /** + * @return an array generator for an array whose elements are of type T. + */ + @SuppressWarnings("unchecked") + static IntFunction castingArray() { + return size -> (T[]) new Object[size]; + } + // General shape-based node creation methods /** diff --git a/jdk/src/java.base/share/classes/java/util/stream/PipelineHelper.java b/jdk/src/java.base/share/classes/java/util/stream/PipelineHelper.java index 090469def00..081f68d1a0e 100644 --- a/jdk/src/java.base/share/classes/java/util/stream/PipelineHelper.java +++ b/jdk/src/java.base/share/classes/java/util/stream/PipelineHelper.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 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 @@ -136,8 +136,9 @@ abstract class PipelineHelper { * * @param wrappedSink the destination {@code Sink} * @param spliterator the source {@code Spliterator} + * @return true if the cancellation was requested */ - abstract void copyIntoWithCancel(Sink wrappedSink, Spliterator spliterator); + abstract boolean copyIntoWithCancel(Sink wrappedSink, Spliterator spliterator); /** * Takes a {@code Sink} that accepts elements of the output type of the diff --git a/jdk/src/java.base/share/classes/java/util/stream/ReferencePipeline.java b/jdk/src/java.base/share/classes/java/util/stream/ReferencePipeline.java index 4402997958b..80b0714e6be 100644 --- a/jdk/src/java.base/share/classes/java/util/stream/ReferencePipeline.java +++ b/jdk/src/java.base/share/classes/java/util/stream/ReferencePipeline.java @@ -122,8 +122,10 @@ abstract class ReferencePipeline } @Override - final void forEachWithCancel(Spliterator spliterator, Sink sink) { - do { } while (!sink.cancellationRequested() && spliterator.tryAdvance(sink)); + final boolean forEachWithCancel(Spliterator spliterator, Sink sink) { + boolean cancelled; + do { } while (!(cancelled = sink.cancellationRequested()) && spliterator.tryAdvance(sink)); + return cancelled; } @Override @@ -411,6 +413,16 @@ abstract class ReferencePipeline return SliceOps.makeRef(this, n, -1); } + @Override + public final Stream takeWhile(Predicate predicate) { + return WhileOps.makeTakeWhileRef(this, predicate); + } + + @Override + public final Stream dropWhile(Predicate predicate) { + return WhileOps.makeDropWhileRef(this, predicate); + } + // Terminal operations from Stream @Override diff --git a/jdk/src/java.base/share/classes/java/util/stream/SliceOps.java b/jdk/src/java.base/share/classes/java/util/stream/SliceOps.java index bfe053fca25..bdb13b4ff60 100644 --- a/jdk/src/java.base/share/classes/java/util/stream/SliceOps.java +++ b/jdk/src/java.base/share/classes/java/util/stream/SliceOps.java @@ -96,11 +96,6 @@ final class SliceOps { } } - @SuppressWarnings("unchecked") - private static IntFunction castingArray() { - return size -> (T[]) new Object[size]; - } - /** * Appends a "slice" operation to the provided stream. The slice operation * may be may be skip-only, limit-only, or skip-and-limit. @@ -151,7 +146,7 @@ final class SliceOps { // cancellation will be more aggressive cancelling later tasks // if the target slice size has been reached from a given task, // cancellation should also clear local results if any - return new SliceTask<>(this, helper, spliterator, castingArray(), skip, limit). + return new SliceTask<>(this, helper, spliterator, Nodes.castingArray(), skip, limit). invoke().spliterator(); } } diff --git a/jdk/src/java.base/share/classes/java/util/stream/Stream.java b/jdk/src/java.base/share/classes/java/util/stream/Stream.java index e0e26ff385f..6e96ba88ad4 100644 --- a/jdk/src/java.base/share/classes/java/util/stream/Stream.java +++ b/jdk/src/java.base/share/classes/java/util/stream/Stream.java @@ -24,7 +24,6 @@ */ package java.util.stream; -import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.util.Arrays; @@ -480,6 +479,135 @@ public interface Stream extends BaseStream> { */ Stream skip(long n); + /** + * Returns, if this stream is ordered, a stream consisting of the longest + * prefix of elements taken from this stream that match the given predicate. + * Otherwise returns, if this stream is unordered, a stream consisting of a + * subset of elements taken from this stream that match the given predicate. + * + *

      If this stream is ordered then the longest prefix is a contiguous + * sequence of elements of this stream that match the given predicate. The + * first element of the sequence is the first element of this stream, and + * the element immediately following the last element of the sequence does + * not match the given predicate. + * + *

      If this stream is unordered, and some (but not all) elements of this + * stream match the given predicate, then the behavior of this operation is + * nondeterministic; it is free to take any subset of matching elements + * (which includes the empty set). + * + *

      Independent of whether this stream is ordered or unordered if all + * elements of this stream match the given predicate then this operation + * takes all elements (the result is the same is the input), or if no + * elements of the stream match the given predicate then no elements are + * taken (the result is an empty stream). + * + *

      This is a short-circuiting + * stateful intermediate operation. + * + * @implSpec + * The default implementation obtains the {@link #spliterator() spliterator} + * of this stream, wraps that spliterator so as to support the semantics + * of this operation on traversal, and returns a new stream associated with + * the wrapped spliterator. The returned stream preserves the execution + * characteristics of this stream (namely parallel or sequential execution + * as per {@link #isParallel()}) but the wrapped spliterator may choose to + * not support splitting. When the returned stream is closed, the close + * handlers for both the returned and this stream are invoked. + * + * @apiNote + * While {@code takeWhile()} is generally a cheap operation on sequential + * stream pipelines, it can be quite expensive on ordered parallel + * pipelines, since the operation is constrained to return not just any + * valid prefix, but the longest prefix of elements in the encounter order. + * Using an unordered stream source (such as {@link #generate(Supplier)}) or + * removing the ordering constraint with {@link #unordered()} may result in + * significant speedups of {@code takeWhile()} in parallel pipelines, if the + * semantics of your situation permit. If consistency with encounter order + * is required, and you are experiencing poor performance or memory + * utilization with {@code takeWhile()} in parallel pipelines, switching to + * sequential execution with {@link #sequential()} may improve performance. + * + * @param predicate a non-interfering, + * stateless + * predicate to apply to elements to determine the longest + * prefix of elements. + * @return the new stream + */ + default Stream takeWhile(Predicate predicate) { + Objects.requireNonNull(predicate); + // Reuses the unordered spliterator, which, when encounter is present, + // is safe to use as long as it configured not to split + return StreamSupport.stream( + new WhileOps.UnorderedWhileSpliterator.OfRef.Taking<>(spliterator(), true, predicate), + isParallel()).onClose(this::close); + } + + /** + * Returns, if this stream is ordered, a stream consisting of the remaining + * elements of this stream after dropping the longest prefix of elements + * that match the given predicate. Otherwise returns, if this stream is + * unordered, a stream consisting of the remaining elements of this stream + * after dropping a subset of elements that match the given predicate. + * + *

      If this stream is ordered then the longest prefix is a contiguous + * sequence of elements of this stream that match the given predicate. The + * first element of the sequence is the first element of this stream, and + * the element immediately following the last element of the sequence does + * not match the given predicate. + * + *

      If this stream is unordered, and some (but not all) elements of this + * stream match the given predicate, then the behavior of this operation is + * nondeterministic; it is free to drop any subset of matching elements + * (which includes the empty set). + * + *

      Independent of whether this stream is ordered or unordered if all + * elements of this stream match the given predicate then this operation + * drops all elements (the result is an empty stream), or if no elements of + * the stream match the given predicate then no elements are dropped (the + * result is the same is the input). + * + *

      This is a stateful + * intermediate operation. + * + * @implSpec + * The default implementation obtains the {@link #spliterator() spliterator} + * of this stream, wraps that spliterator so as to support the semantics + * of this operation on traversal, and returns a new stream associated with + * the wrapped spliterator. The returned stream preserves the execution + * characteristics of this stream (namely parallel or sequential execution + * as per {@link #isParallel()}) but the wrapped spliterator may choose to + * not support splitting. When the returned stream is closed, the close + * handlers for both the returned and this stream are invoked. + * + * @apiNote + * While {@code dropWhile()} is generally a cheap operation on sequential + * stream pipelines, it can be quite expensive on ordered parallel + * pipelines, since the operation is constrained to return not just any + * valid prefix, but the longest prefix of elements in the encounter order. + * Using an unordered stream source (such as {@link #generate(Supplier)}) or + * removing the ordering constraint with {@link #unordered()} may result in + * significant speedups of {@code dropWhile()} in parallel pipelines, if the + * semantics of your situation permit. If consistency with encounter order + * is required, and you are experiencing poor performance or memory + * utilization with {@code dropWhile()} in parallel pipelines, switching to + * sequential execution with {@link #sequential()} may improve performance. + * + * @param predicate a non-interfering, + * stateless + * predicate to apply to elements to determine the longest + * prefix of elements. + * @return the new stream + */ + default Stream dropWhile(Predicate predicate) { + Objects.requireNonNull(predicate); + // Reuses the unordered spliterator, which, when encounter is present, + // is safe to use as long as it configured not to split + return StreamSupport.stream( + new WhileOps.UnorderedWhileSpliterator.OfRef.Dropping<>(spliterator(), true, predicate), + isParallel()).onClose(this::close); + } + /** * Performs an action for each element of this stream. * diff --git a/jdk/src/java.base/share/classes/java/util/stream/WhileOps.java b/jdk/src/java.base/share/classes/java/util/stream/WhileOps.java new file mode 100644 index 00000000000..94705ec571b --- /dev/null +++ b/jdk/src/java.base/share/classes/java/util/stream/WhileOps.java @@ -0,0 +1,1394 @@ +/* + * Copyright (c) 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. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package java.util.stream; + +import java.util.Comparator; +import java.util.Objects; +import java.util.Spliterator; +import java.util.concurrent.CountedCompleter; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.function.Consumer; +import java.util.function.DoubleConsumer; +import java.util.function.DoublePredicate; +import java.util.function.IntConsumer; +import java.util.function.IntFunction; +import java.util.function.IntPredicate; +import java.util.function.LongConsumer; +import java.util.function.LongPredicate; +import java.util.function.Predicate; + +/** + * Factory for instances of a takeWhile and dropWhile operations + * that produce subsequences of their input stream. + * + * @since 1.9 + */ +final class WhileOps { + + static final int TAKE_FLAGS = StreamOpFlag.NOT_SIZED | StreamOpFlag.IS_SHORT_CIRCUIT; + + static final int DROP_FLAGS = StreamOpFlag.NOT_SIZED; + + /** + * Appends a "takeWhile" operation to the provided Stream. + * + * @param the type of both input and output elements + * @param upstream a reference stream with element type T + * @param predicate the predicate that returns false to halt taking. + */ + static Stream makeTakeWhileRef(AbstractPipeline upstream, + Predicate predicate) { + Objects.requireNonNull(predicate); + return new ReferencePipeline.StatefulOp(upstream, StreamShape.REFERENCE, TAKE_FLAGS) { + @Override + Spliterator opEvaluateParallelLazy(PipelineHelper helper, + Spliterator spliterator) { + if (StreamOpFlag.ORDERED.isKnown(helper.getStreamAndOpFlags())) { + return opEvaluateParallel(helper, spliterator, Nodes.castingArray()) + .spliterator(); + } + else { + return new UnorderedWhileSpliterator.OfRef.Taking<>( + helper.wrapSpliterator(spliterator), false, predicate); + } + } + + @Override + Node opEvaluateParallel(PipelineHelper helper, + Spliterator spliterator, + IntFunction generator) { + return new TakeWhileTask<>(this, helper, spliterator, generator) + .invoke(); + } + + @Override + Sink opWrapSink(int flags, Sink sink) { + return new Sink.ChainedReference(sink) { + boolean take = true; + + @Override + public void begin(long size) { + downstream.begin(-1); + } + + @Override + public void accept(T t) { + if (take = predicate.test(t)) { + downstream.accept(t); + } + } + + @Override + public boolean cancellationRequested() { + return !take || downstream.cancellationRequested(); + } + }; + } + }; + } + + /** + * Appends a "takeWhile" operation to the provided IntStream. + * + * @param upstream a reference stream with element type T + * @param predicate the predicate that returns false to halt taking. + */ + static IntStream makeTakeWhileInt(AbstractPipeline upstream, + IntPredicate predicate) { + Objects.requireNonNull(predicate); + return new IntPipeline.StatefulOp(upstream, StreamShape.INT_VALUE, TAKE_FLAGS) { + @Override + Spliterator opEvaluateParallelLazy(PipelineHelper helper, + Spliterator spliterator) { + if (StreamOpFlag.ORDERED.isKnown(helper.getStreamAndOpFlags())) { + return opEvaluateParallel(helper, spliterator, Integer[]::new) + .spliterator(); + } + else { + return new UnorderedWhileSpliterator.OfInt.Taking( + (Spliterator.OfInt) helper.wrapSpliterator(spliterator), false, predicate); + } + } + + @Override + Node opEvaluateParallel(PipelineHelper helper, + Spliterator spliterator, + IntFunction generator) { + return new TakeWhileTask<>(this, helper, spliterator, generator) + .invoke(); + } + + @Override + Sink opWrapSink(int flags, Sink sink) { + return new Sink.ChainedInt(sink) { + boolean take = true; + + @Override + public void begin(long size) { + downstream.begin(-1); + } + + @Override + public void accept(int t) { + if (take = predicate.test(t)) { + downstream.accept(t); + } + } + + @Override + public boolean cancellationRequested() { + return !take || downstream.cancellationRequested(); + } + }; + } + }; + } + + /** + * Appends a "takeWhile" operation to the provided LongStream. + * + * @param upstream a reference stream with element type T + * @param predicate the predicate that returns false to halt taking. + */ + static LongStream makeTakeWhileLong(AbstractPipeline upstream, + LongPredicate predicate) { + Objects.requireNonNull(predicate); + return new LongPipeline.StatefulOp(upstream, StreamShape.LONG_VALUE, TAKE_FLAGS) { + @Override + Spliterator opEvaluateParallelLazy(PipelineHelper helper, + Spliterator spliterator) { + if (StreamOpFlag.ORDERED.isKnown(helper.getStreamAndOpFlags())) { + return opEvaluateParallel(helper, spliterator, Long[]::new) + .spliterator(); + } + else { + return new UnorderedWhileSpliterator.OfLong.Taking( + (Spliterator.OfLong) helper.wrapSpliterator(spliterator), false, predicate); + } + } + + @Override + Node opEvaluateParallel(PipelineHelper helper, + Spliterator spliterator, + IntFunction generator) { + return new TakeWhileTask<>(this, helper, spliterator, generator) + .invoke(); + } + + @Override + Sink opWrapSink(int flags, Sink sink) { + return new Sink.ChainedLong(sink) { + boolean take = true; + + @Override + public void begin(long size) { + downstream.begin(-1); + } + + @Override + public void accept(long t) { + if (take = predicate.test(t)) { + downstream.accept(t); + } + } + + @Override + public boolean cancellationRequested() { + return !take || downstream.cancellationRequested(); + } + }; + } + }; + } + + /** + * Appends a "takeWhile" operation to the provided DoubleStream. + * + * @param upstream a reference stream with element type T + * @param predicate the predicate that returns false to halt taking. + */ + static DoubleStream makeTakeWhileDouble(AbstractPipeline upstream, + DoublePredicate predicate) { + Objects.requireNonNull(predicate); + return new DoublePipeline.StatefulOp(upstream, StreamShape.DOUBLE_VALUE, TAKE_FLAGS) { + @Override + Spliterator opEvaluateParallelLazy(PipelineHelper helper, + Spliterator spliterator) { + if (StreamOpFlag.ORDERED.isKnown(helper.getStreamAndOpFlags())) { + return opEvaluateParallel(helper, spliterator, Double[]::new) + .spliterator(); + } + else { + return new UnorderedWhileSpliterator.OfDouble.Taking( + (Spliterator.OfDouble) helper.wrapSpliterator(spliterator), false, predicate); + } + } + + @Override + Node opEvaluateParallel(PipelineHelper helper, + Spliterator spliterator, + IntFunction generator) { + return new TakeWhileTask<>(this, helper, spliterator, generator) + .invoke(); + } + + @Override + Sink opWrapSink(int flags, Sink sink) { + return new Sink.ChainedDouble(sink) { + boolean take = true; + + @Override + public void begin(long size) { + downstream.begin(-1); + } + + @Override + public void accept(double t) { + if (take = predicate.test(t)) { + downstream.accept(t); + } + } + + @Override + public boolean cancellationRequested() { + return !take || downstream.cancellationRequested(); + } + }; + } + }; + } + + /** + * A specialization for the dropWhile operation that controls if + * elements to be dropped are counted and passed downstream. + *

      + * This specialization is utilized by the {@link TakeWhileTask} for + * pipelines that are ordered. In such cases elements cannot be dropped + * until all elements have been collected. + * + * @param the type of both input and output elements + */ + interface DropWhileOp { + /** + * Accepts a {@code Sink} which will receive the results of this + * dropWhile operation, and return a {@code DropWhileSink} which + * accepts + * elements and which performs the dropWhile operation passing the + * results to the provided {@code Sink}. + * + * @param sink sink to which elements should be sent after processing + * @param retainAndCountDroppedElements true if elements to be dropped + * are counted and passed to the sink, otherwise such elements + * are actually dropped and not passed to the sink. + * @return a dropWhile sink + */ + DropWhileSink opWrapSink(Sink sink, boolean retainAndCountDroppedElements); + } + + /** + * A specialization for a dropWhile sink. + * + * @param the type of both input and output elements + */ + interface DropWhileSink extends Sink { + /** + * @return the could of elements that would have been dropped and + * instead were passed downstream. + */ + long getDropCount(); + } + + /** + * Appends a "dropWhile" operation to the provided Stream. + * + * @param the type of both input and output elements + * @param upstream a reference stream with element type T + * @param predicate the predicate that returns false to halt dropping. + */ + static Stream makeDropWhileRef(AbstractPipeline upstream, + Predicate predicate) { + Objects.requireNonNull(predicate); + + class Op extends ReferencePipeline.StatefulOp implements DropWhileOp { + public Op(AbstractPipeline upstream, StreamShape inputShape, int opFlags) { + super(upstream, inputShape, opFlags); + } + + @Override + Spliterator opEvaluateParallelLazy(PipelineHelper helper, + Spliterator spliterator) { + if (StreamOpFlag.ORDERED.isKnown(helper.getStreamAndOpFlags())) { + return opEvaluateParallel(helper, spliterator, Nodes.castingArray()) + .spliterator(); + } + else { + return new UnorderedWhileSpliterator.OfRef.Dropping<>( + helper.wrapSpliterator(spliterator), false, predicate); + } + } + + @Override + Node opEvaluateParallel(PipelineHelper helper, + Spliterator spliterator, + IntFunction generator) { + return new DropWhileTask<>(this, helper, spliterator, generator) + .invoke(); + } + + @Override + Sink opWrapSink(int flags, Sink sink) { + return opWrapSink(sink, false); + } + + public DropWhileSink opWrapSink(Sink sink, boolean retainAndCountDroppedElements) { + class OpSink extends Sink.ChainedReference implements DropWhileSink { + long dropCount; + boolean take; + + OpSink() { + super(sink); + } + + @Override + public void accept(T t) { + boolean takeElement = take || (take = !predicate.test(t)); + + // If ordered and element is dropped increment index + // for possible future truncation + if (retainAndCountDroppedElements && !takeElement) + dropCount++; + + // If ordered need to process element, otherwise + // skip if element is dropped + if (retainAndCountDroppedElements || takeElement) + downstream.accept(t); + } + + @Override + public long getDropCount() { + return dropCount; + } + } + return new OpSink(); + } + } + return new Op(upstream, StreamShape.REFERENCE, DROP_FLAGS); + } + + /** + * Appends a "dropWhile" operation to the provided IntStream. + * + * @param upstream a reference stream with element type T + * @param predicate the predicate that returns false to halt dropping. + */ + static IntStream makeDropWhileInt(AbstractPipeline upstream, + IntPredicate predicate) { + Objects.requireNonNull(predicate); + class Op extends IntPipeline.StatefulOp implements DropWhileOp { + public Op(AbstractPipeline upstream, StreamShape inputShape, int opFlags) { + super(upstream, inputShape, opFlags); + } + + @Override + Spliterator opEvaluateParallelLazy(PipelineHelper helper, + Spliterator spliterator) { + if (StreamOpFlag.ORDERED.isKnown(helper.getStreamAndOpFlags())) { + return opEvaluateParallel(helper, spliterator, Integer[]::new) + .spliterator(); + } + else { + return new UnorderedWhileSpliterator.OfInt.Dropping( + (Spliterator.OfInt) helper.wrapSpliterator(spliterator), false, predicate); + } + } + + @Override + Node opEvaluateParallel(PipelineHelper helper, + Spliterator spliterator, + IntFunction generator) { + return new DropWhileTask<>(this, helper, spliterator, generator) + .invoke(); + } + + @Override + Sink opWrapSink(int flags, Sink sink) { + return opWrapSink(sink, false); + } + + public DropWhileSink opWrapSink(Sink sink, boolean retainAndCountDroppedElements) { + class OpSink extends Sink.ChainedInt implements DropWhileSink { + long dropCount; + boolean take; + + OpSink() { + super(sink); + } + + @Override + public void accept(int t) { + boolean takeElement = take || (take = !predicate.test(t)); + + // If ordered and element is dropped increment index + // for possible future truncation + if (retainAndCountDroppedElements && !takeElement) + dropCount++; + + // If ordered need to process element, otherwise + // skip if element is dropped + if (retainAndCountDroppedElements || takeElement) + downstream.accept(t); + } + + @Override + public long getDropCount() { + return dropCount; + } + } + return new OpSink(); + } + } + return new Op(upstream, StreamShape.INT_VALUE, DROP_FLAGS); + } + + /** + * Appends a "dropWhile" operation to the provided LongStream. + * + * @param upstream a reference stream with element type T + * @param predicate the predicate that returns false to halt dropping. + */ + static LongStream makeDropWhileLong(AbstractPipeline upstream, + LongPredicate predicate) { + Objects.requireNonNull(predicate); + class Op extends LongPipeline.StatefulOp implements DropWhileOp { + public Op(AbstractPipeline upstream, StreamShape inputShape, int opFlags) { + super(upstream, inputShape, opFlags); + } + + @Override + Spliterator opEvaluateParallelLazy(PipelineHelper helper, + Spliterator spliterator) { + if (StreamOpFlag.ORDERED.isKnown(helper.getStreamAndOpFlags())) { + return opEvaluateParallel(helper, spliterator, Long[]::new) + .spliterator(); + } + else { + return new UnorderedWhileSpliterator.OfLong.Dropping( + (Spliterator.OfLong) helper.wrapSpliterator(spliterator), false, predicate); + } + } + + @Override + Node opEvaluateParallel(PipelineHelper helper, + Spliterator spliterator, + IntFunction generator) { + return new DropWhileTask<>(this, helper, spliterator, generator) + .invoke(); + } + + @Override + Sink opWrapSink(int flags, Sink sink) { + return opWrapSink(sink, false); + } + + public DropWhileSink opWrapSink(Sink sink, boolean retainAndCountDroppedElements) { + class OpSink extends Sink.ChainedLong implements DropWhileSink { + long dropCount; + boolean take; + + OpSink() { + super(sink); + } + + @Override + public void accept(long t) { + boolean takeElement = take || (take = !predicate.test(t)); + + // If ordered and element is dropped increment index + // for possible future truncation + if (retainAndCountDroppedElements && !takeElement) + dropCount++; + + // If ordered need to process element, otherwise + // skip if element is dropped + if (retainAndCountDroppedElements || takeElement) + downstream.accept(t); + } + + @Override + public long getDropCount() { + return dropCount; + } + } + return new OpSink(); + } + } + return new Op(upstream, StreamShape.LONG_VALUE, DROP_FLAGS); + } + + /** + * Appends a "dropWhile" operation to the provided DoubleStream. + * + * @param upstream a reference stream with element type T + * @param predicate the predicate that returns false to halt dropping. + */ + static DoubleStream makeDropWhileDouble(AbstractPipeline upstream, + DoublePredicate predicate) { + Objects.requireNonNull(predicate); + class Op extends DoublePipeline.StatefulOp implements DropWhileOp { + public Op(AbstractPipeline upstream, StreamShape inputShape, int opFlags) { + super(upstream, inputShape, opFlags); + } + + @Override + Spliterator opEvaluateParallelLazy(PipelineHelper helper, + Spliterator spliterator) { + if (StreamOpFlag.ORDERED.isKnown(helper.getStreamAndOpFlags())) { + return opEvaluateParallel(helper, spliterator, Double[]::new) + .spliterator(); + } + else { + return new UnorderedWhileSpliterator.OfDouble.Dropping( + (Spliterator.OfDouble) helper.wrapSpliterator(spliterator), false, predicate); + } + } + + @Override + Node opEvaluateParallel(PipelineHelper helper, + Spliterator spliterator, + IntFunction generator) { + return new DropWhileTask<>(this, helper, spliterator, generator) + .invoke(); + } + + @Override + Sink opWrapSink(int flags, Sink sink) { + return opWrapSink(sink, false); + } + + public DropWhileSink opWrapSink(Sink sink, boolean retainAndCountDroppedElements) { + class OpSink extends Sink.ChainedDouble implements DropWhileSink { + long dropCount; + boolean take; + + OpSink() { + super(sink); + } + + @Override + public void accept(double t) { + boolean takeElement = take || (take = !predicate.test(t)); + + // If ordered and element is dropped increment index + // for possible future truncation + if (retainAndCountDroppedElements && !takeElement) + dropCount++; + + // If ordered need to process element, otherwise + // skip if element is dropped + if (retainAndCountDroppedElements || takeElement) + downstream.accept(t); + } + + @Override + public long getDropCount() { + return dropCount; + } + } + return new OpSink(); + } + } + return new Op(upstream, StreamShape.DOUBLE_VALUE, DROP_FLAGS); + } + + // + + /** + * A spliterator supporting takeWhile and dropWhile operations over an + * underlying spliterator whose covered elements have no encounter order. + *

      + * Concrete subclasses of this spliterator support reference and primitive + * types for takeWhile and dropWhile. + *

      + * For the takeWhile operation if during traversal taking completes then + * taking is cancelled globally for the splitting and traversal of all + * related spliterators. + * Cancellation is governed by a shared {@link AtomicBoolean} instance. A + * spliterator in the process of taking when cancellation occurs will also + * be cancelled but not necessarily immediately. To reduce contention on + * the {@link AtomicBoolean} instance, cancellation make be acted on after + * a small number of additional elements have been traversed. + *

      + * For the dropWhile operation if during traversal dropping completes for + * some, but not all elements, then it is cancelled globally for the + * traversal of all related spliterators (splitting is not cancelled). + * Cancellation is governed in the same manner as for the takeWhile + * operation. + * + * @param the type of elements returned by this spliterator + * @param the type of the spliterator + */ + static abstract class UnorderedWhileSpliterator> implements Spliterator { + // Power of two constant minus one used for modulus of count + static final int CANCEL_CHECK_COUNT = (1 << 6) - 1; + + // The underlying spliterator + final T_SPLITR s; + // True if no splitting should be performed, if true then + // this spliterator may be used for an underlying spliterator whose + // covered elements have an encounter order + // See use in stream take/dropWhile default default methods + final boolean noSplitting; + // True when operations are cancelled for all related spliterators + // For taking, spliterators cannot split or traversed + // For dropping, spliterators cannot be traversed + final AtomicBoolean cancel; + // True while taking or dropping should be performed when traversing + boolean takeOrDrop = true; + // The count of elements traversed + int count; + + UnorderedWhileSpliterator(T_SPLITR s, boolean noSplitting) { + this.s = s; + this.noSplitting = noSplitting; + this.cancel = new AtomicBoolean(); + } + + UnorderedWhileSpliterator(T_SPLITR s, UnorderedWhileSpliterator parent) { + this.s = s; + this.noSplitting = parent.noSplitting; + this.cancel = parent.cancel; + } + + @Override + public long estimateSize() { + return s.estimateSize(); + } + + @Override + public int characteristics() { + // Size is not known + return s.characteristics() & ~(Spliterator.SIZED | Spliterator.SUBSIZED); + } + + @Override + public long getExactSizeIfKnown() { + return -1L; + } + + @Override + public Comparator getComparator() { + return s.getComparator(); + } + + @Override + public T_SPLITR trySplit() { + @SuppressWarnings("unchecked") + T_SPLITR ls = noSplitting ? null : (T_SPLITR) s.trySplit(); + return ls != null ? makeSpliterator(ls) : null; + } + + boolean checkCancelOnCount() { + return count != 0 || !cancel.get(); + } + + abstract T_SPLITR makeSpliterator(T_SPLITR s); + + static abstract class OfRef extends UnorderedWhileSpliterator> implements Consumer { + final Predicate p; + T t; + + OfRef(Spliterator s, boolean noSplitting, Predicate p) { + super(s, noSplitting); + this.p = p; + } + + OfRef(Spliterator s, OfRef parent) { + super(s, parent); + this.p = parent.p; + } + + @Override + public void accept(T t) { + count = (count + 1) & CANCEL_CHECK_COUNT; + this.t = t; + } + + static final class Taking extends OfRef { + Taking(Spliterator s, boolean noSplitting, Predicate p) { + super(s, noSplitting, p); + } + + Taking(Spliterator s, Taking parent) { + super(s, parent); + } + + @Override + public boolean tryAdvance(Consumer action) { + boolean test = true; + if (takeOrDrop && // If can take + checkCancelOnCount() && // and if not cancelled + s.tryAdvance(this) && // and if advanced one element + (test = p.test(t))) { // and test on element passes + action.accept(t); // then accept element + return true; + } + else { + // Taking is finished + takeOrDrop = false; + // Cancel all further traversal and splitting operations + // only if test of element failed (short-circuited) + if (!test) + cancel.set(true); + return false; + } + } + + @Override + public Spliterator trySplit() { + // Do not split if all operations are cancelled + return cancel.get() ? null : super.trySplit(); + } + + @Override + Spliterator makeSpliterator(Spliterator s) { + return new Taking<>(s, this); + } + } + + static final class Dropping extends OfRef { + Dropping(Spliterator s, boolean noSplitting, Predicate p) { + super(s, noSplitting, p); + } + + Dropping(Spliterator s, Dropping parent) { + super(s, parent); + } + + @Override + public boolean tryAdvance(Consumer action) { + if (takeOrDrop) { + takeOrDrop = false; + boolean adv; + boolean dropped = false; + while ((adv = s.tryAdvance(this)) && // If advanced one element + checkCancelOnCount() && // and if not cancelled + p.test(t)) { // and test on element passes + dropped = true; // then drop element + } + + // Report advanced element, if any + if (adv) { + // Cancel all further dropping if one or more elements + // were previously dropped + if (dropped) + cancel.set(true); + action.accept(t); + } + return adv; + } + else { + return s.tryAdvance(action); + } + } + + @Override + Spliterator makeSpliterator(Spliterator s) { + return new Dropping<>(s, this); + } + } + } + + static abstract class OfInt extends UnorderedWhileSpliterator implements IntConsumer, Spliterator.OfInt { + final IntPredicate p; + int t; + + OfInt(Spliterator.OfInt s, boolean noSplitting, IntPredicate p) { + super(s, noSplitting); + this.p = p; + } + + OfInt(Spliterator.OfInt s, UnorderedWhileSpliterator.OfInt parent) { + super(s, parent); + this.p = parent.p; + } + + @Override + public void accept(int t) { + count = (count + 1) & CANCEL_CHECK_COUNT; + this.t = t; + } + + static final class Taking extends UnorderedWhileSpliterator.OfInt { + Taking(Spliterator.OfInt s, boolean noSplitting, IntPredicate p) { + super(s, noSplitting, p); + } + + Taking(Spliterator.OfInt s, UnorderedWhileSpliterator.OfInt parent) { + super(s, parent); + } + + @Override + public boolean tryAdvance(IntConsumer action) { + boolean test = true; + if (takeOrDrop && // If can take + checkCancelOnCount() && // and if not cancelled + s.tryAdvance(this) && // and if advanced one element + (test = p.test(t))) { // and test on element passes + action.accept(t); // then accept element + return true; + } + else { + // Taking is finished + takeOrDrop = false; + // Cancel all further traversal and splitting operations + // only if test of element failed (short-circuited) + if (!test) + cancel.set(true); + return false; + } + } + + @Override + public Spliterator.OfInt trySplit() { + // Do not split if all operations are cancelled + return cancel.get() ? null : super.trySplit(); + } + + @Override + Spliterator.OfInt makeSpliterator(Spliterator.OfInt s) { + return new Taking(s, this); + } + } + + static final class Dropping extends UnorderedWhileSpliterator.OfInt { + Dropping(Spliterator.OfInt s, boolean noSplitting, IntPredicate p) { + super(s, noSplitting, p); + } + + Dropping(Spliterator.OfInt s, UnorderedWhileSpliterator.OfInt parent) { + super(s, parent); + } + + @Override + public boolean tryAdvance(IntConsumer action) { + if (takeOrDrop) { + takeOrDrop = false; + boolean adv; + boolean dropped = false; + while ((adv = s.tryAdvance(this)) && // If advanced one element + checkCancelOnCount() && // and if not cancelled + p.test(t)) { // and test on element passes + dropped = true; // then drop element + } + + // Report advanced element, if any + if (adv) { + // Cancel all further dropping if one or more elements + // were previously dropped + if (dropped) + cancel.set(true); + action.accept(t); + } + return adv; + } + else { + return s.tryAdvance(action); + } + } + + @Override + Spliterator.OfInt makeSpliterator(Spliterator.OfInt s) { + return new Dropping(s, this); + } + } + } + + static abstract class OfLong extends UnorderedWhileSpliterator implements LongConsumer, Spliterator.OfLong { + final LongPredicate p; + long t; + + OfLong(Spliterator.OfLong s, boolean noSplitting, LongPredicate p) { + super(s, noSplitting); + this.p = p; + } + + OfLong(Spliterator.OfLong s, UnorderedWhileSpliterator.OfLong parent) { + super(s, parent); + this.p = parent.p; + } + + @Override + public void accept(long t) { + count = (count + 1) & CANCEL_CHECK_COUNT; + this.t = t; + } + + static final class Taking extends UnorderedWhileSpliterator.OfLong { + Taking(Spliterator.OfLong s, boolean noSplitting, LongPredicate p) { + super(s, noSplitting, p); + } + + Taking(Spliterator.OfLong s, UnorderedWhileSpliterator.OfLong parent) { + super(s, parent); + } + + @Override + public boolean tryAdvance(LongConsumer action) { + boolean test = true; + if (takeOrDrop && // If can take + checkCancelOnCount() && // and if not cancelled + s.tryAdvance(this) && // and if advanced one element + (test = p.test(t))) { // and test on element passes + action.accept(t); // then accept element + return true; + } + else { + // Taking is finished + takeOrDrop = false; + // Cancel all further traversal and splitting operations + // only if test of element failed (short-circuited) + if (!test) + cancel.set(true); + return false; + } + } + + @Override + public Spliterator.OfLong trySplit() { + // Do not split if all operations are cancelled + return cancel.get() ? null : super.trySplit(); + } + + @Override + Spliterator.OfLong makeSpliterator(Spliterator.OfLong s) { + return new Taking(s, this); + } + } + + static final class Dropping extends UnorderedWhileSpliterator.OfLong { + Dropping(Spliterator.OfLong s, boolean noSplitting, LongPredicate p) { + super(s, noSplitting, p); + } + + Dropping(Spliterator.OfLong s, UnorderedWhileSpliterator.OfLong parent) { + super(s, parent); + } + + @Override + public boolean tryAdvance(LongConsumer action) { + if (takeOrDrop) { + takeOrDrop = false; + boolean adv; + boolean dropped = false; + while ((adv = s.tryAdvance(this)) && // If advanced one element + checkCancelOnCount() && // and if not cancelled + p.test(t)) { // and test on element passes + dropped = true; // then drop element + } + + // Report advanced element, if any + if (adv) { + // Cancel all further dropping if one or more elements + // were previously dropped + if (dropped) + cancel.set(true); + action.accept(t); + } + return adv; + } + else { + return s.tryAdvance(action); + } + } + + @Override + Spliterator.OfLong makeSpliterator(Spliterator.OfLong s) { + return new Dropping(s, this); + } + } + } + + static abstract class OfDouble extends UnorderedWhileSpliterator implements DoubleConsumer, Spliterator.OfDouble { + final DoublePredicate p; + double t; + + OfDouble(Spliterator.OfDouble s, boolean noSplitting, DoublePredicate p) { + super(s, noSplitting); + this.p = p; + } + + OfDouble(Spliterator.OfDouble s, UnorderedWhileSpliterator.OfDouble parent) { + super(s, parent); + this.p = parent.p; + } + + @Override + public void accept(double t) { + count = (count + 1) & CANCEL_CHECK_COUNT; + this.t = t; + } + + static final class Taking extends UnorderedWhileSpliterator.OfDouble { + Taking(Spliterator.OfDouble s, boolean noSplitting, DoublePredicate p) { + super(s, noSplitting, p); + } + + Taking(Spliterator.OfDouble s, UnorderedWhileSpliterator.OfDouble parent) { + super(s, parent); + } + + @Override + public boolean tryAdvance(DoubleConsumer action) { + boolean test = true; + if (takeOrDrop && // If can take + checkCancelOnCount() && // and if not cancelled + s.tryAdvance(this) && // and if advanced one element + (test = p.test(t))) { // and test on element passes + action.accept(t); // then accept element + return true; + } + else { + // Taking is finished + takeOrDrop = false; + // Cancel all further traversal and splitting operations + // only if test of element failed (short-circuited) + if (!test) + cancel.set(true); + return false; + } + } + + @Override + public Spliterator.OfDouble trySplit() { + // Do not split if all operations are cancelled + return cancel.get() ? null : super.trySplit(); + } + + @Override + Spliterator.OfDouble makeSpliterator(Spliterator.OfDouble s) { + return new Taking(s, this); + } + } + + static final class Dropping extends UnorderedWhileSpliterator.OfDouble { + Dropping(Spliterator.OfDouble s, boolean noSplitting, DoublePredicate p) { + super(s, noSplitting, p); + } + + Dropping(Spliterator.OfDouble s, UnorderedWhileSpliterator.OfDouble parent) { + super(s, parent); + } + + @Override + public boolean tryAdvance(DoubleConsumer action) { + if (takeOrDrop) { + takeOrDrop = false; + boolean adv; + boolean dropped = false; + while ((adv = s.tryAdvance(this)) && // If advanced one element + checkCancelOnCount() && // and if not cancelled + p.test(t)) { // and test on element passes + dropped = true; // then drop element + } + + // Report advanced element, if any + if (adv) { + // Cancel all further dropping if one or more elements + // were previously dropped + if (dropped) + cancel.set(true); + action.accept(t); + } + return adv; + } + else { + return s.tryAdvance(action); + } + } + + @Override + Spliterator.OfDouble makeSpliterator(Spliterator.OfDouble s) { + return new Dropping(s, this); + } + } + } + } + + + // + + /** + * {@code ForkJoinTask} implementing takeWhile computation. + *

      + * If the pipeline has encounter order then all tasks to the right of + * a task where traversal was short-circuited are cancelled. + * The results of completed (and cancelled) tasks are discarded. + * The result of merging a short-circuited left task and right task (which + * may or may not be short-circuited) is that left task. + *

      + * If the pipeline has no encounter order then all tasks to the right of + * a task where traversal was short-circuited are cancelled. + * The results of completed (and possibly cancelled) tasks are not + * discarded, as there is no need to throw away computed results. + * The result of merging does not change if a left task was + * short-circuited. + * No attempt is made, once a leaf task stopped taking, for it to cancel + * all other tasks, and further more, short-circuit the computation with its + * result. + * + * @param Input element type to the stream pipeline + * @param Output element type from the stream pipeline + */ + @SuppressWarnings("serial") + private static final class TakeWhileTask + extends AbstractShortCircuitTask, TakeWhileTask> { + private final AbstractPipeline op; + private final IntFunction generator; + private final boolean isOrdered; + private long thisNodeSize; + // True if a short-circuited + private boolean shortCircuited; + // True if completed, must be set after the local result + private volatile boolean completed; + + TakeWhileTask(AbstractPipeline op, + PipelineHelper helper, + Spliterator spliterator, + IntFunction generator) { + super(helper, spliterator); + this.op = op; + this.generator = generator; + this.isOrdered = StreamOpFlag.ORDERED.isKnown(helper.getStreamAndOpFlags()); + } + + TakeWhileTask(TakeWhileTask parent, Spliterator spliterator) { + super(parent, spliterator); + this.op = parent.op; + this.generator = parent.generator; + this.isOrdered = parent.isOrdered; + } + + @Override + protected TakeWhileTask makeChild(Spliterator spliterator) { + return new TakeWhileTask<>(this, spliterator); + } + + @Override + protected final Node getEmptyResult() { + return Nodes.emptyNode(op.getOutputShape()); + } + + @Override + protected final Node doLeaf() { + Node.Builder builder = helper.makeNodeBuilder(-1, generator); + Sink s = op.opWrapSink(helper.getStreamAndOpFlags(), builder); + + if (shortCircuited = helper.copyIntoWithCancel(helper.wrapSink(s), spliterator)) { + // Cancel later nodes if the predicate returned false + // during traversal + cancelLaterNodes(); + } + + Node node = builder.build(); + thisNodeSize = node.count(); + return node; + } + + @Override + public final void onCompletion(CountedCompleter caller) { + if (!isLeaf()) { + Node result; + shortCircuited = leftChild.shortCircuited | rightChild.shortCircuited; + if (isOrdered && canceled) { + thisNodeSize = 0; + result = getEmptyResult(); + } + else if (isOrdered && leftChild.shortCircuited) { + // If taking finished on the left node then + // use the left node result + thisNodeSize = leftChild.thisNodeSize; + result = leftChild.getLocalResult(); + } + else { + thisNodeSize = leftChild.thisNodeSize + rightChild.thisNodeSize; + result = merge(); + } + + setLocalResult(result); + } + + completed = true; + super.onCompletion(caller); + } + + Node merge() { + if (leftChild.thisNodeSize == 0) { + // If the left node size is 0 then + // use the right node result + return rightChild.getLocalResult(); + } + else if (rightChild.thisNodeSize == 0) { + // If the right node size is 0 then + // use the left node result + return leftChild.getLocalResult(); + } + else { + // Combine the left and right nodes + return Nodes.conc(op.getOutputShape(), + leftChild.getLocalResult(), rightChild.getLocalResult()); + } + } + + @Override + protected void cancel() { + super.cancel(); + if (isOrdered && completed) + // If the task is completed then clear the result, if any + // to aid GC + setLocalResult(getEmptyResult()); + } + } + + /** + * {@code ForkJoinTask} implementing dropWhile computation. + *

      + * If the pipeline has encounter order then each leaf task will not + * drop elements but will obtain a count of the elements that would have + * been otherwise dropped. That count is used as an index to track + * elements to be dropped. Merging will update the index so it corresponds + * to the index that is the end of the global prefix of elements to be + * dropped. The root is truncated according to that index. + *

      + * If the pipeline has no encounter order then each leaf task will drop + * elements. Leaf tasks are ordinarily merged. No truncation of the root + * node is required. + * No attempt is made, once a leaf task stopped dropping, for it to cancel + * all other tasks, and further more, short-circuit the computation with + * its result. + * + * @param Input element type to the stream pipeline + * @param Output element type from the stream pipeline + */ + @SuppressWarnings("serial") + private static final class DropWhileTask + extends AbstractTask, DropWhileTask> { + private final AbstractPipeline op; + private final IntFunction generator; + private final boolean isOrdered; + private long thisNodeSize; + // The index from which elements of the node should be taken + // i.e. the node should be truncated from [takeIndex, thisNodeSize) + // Equivalent to the count of dropped elements + private long index; + + DropWhileTask(AbstractPipeline op, + PipelineHelper helper, + Spliterator spliterator, + IntFunction generator) { + super(helper, spliterator); + assert op instanceof DropWhileOp; + this.op = op; + this.generator = generator; + this.isOrdered = StreamOpFlag.ORDERED.isKnown(helper.getStreamAndOpFlags()); + } + + DropWhileTask(DropWhileTask parent, Spliterator spliterator) { + super(parent, spliterator); + this.op = parent.op; + this.generator = parent.generator; + this.isOrdered = parent.isOrdered; + } + + @Override + protected DropWhileTask makeChild(Spliterator spliterator) { + return new DropWhileTask<>(this, spliterator); + } + + @Override + protected final Node doLeaf() { + boolean isChild = !isRoot(); + // If this not the root and pipeline is ordered and size is known + // then pre-size the builder + long sizeIfKnown = isChild && isOrdered && StreamOpFlag.SIZED.isPreserved(op.sourceOrOpFlags) + ? op.exactOutputSizeIfKnown(spliterator) + : -1; + Node.Builder builder = helper.makeNodeBuilder(sizeIfKnown, generator); + @SuppressWarnings("unchecked") + DropWhileOp dropOp = (DropWhileOp) op; + // If this leaf is the root then there is no merging on completion + // and there is no need to retain dropped elements + DropWhileSink s = dropOp.opWrapSink(builder, isOrdered && isChild); + helper.wrapAndCopyInto(s, spliterator); + + Node node = builder.build(); + thisNodeSize = node.count(); + index = s.getDropCount(); + return node; + } + + @Override + public final void onCompletion(CountedCompleter caller) { + if (!isLeaf()) { + if (isOrdered) { + index = leftChild.index; + // If a contiguous sequence of dropped elements + // include those of the right node, if any + if (index == leftChild.thisNodeSize) + index += rightChild.index; + } + + thisNodeSize = leftChild.thisNodeSize + rightChild.thisNodeSize; + Node result = merge(); + setLocalResult(isRoot() ? doTruncate(result) : result); + } + + super.onCompletion(caller); + } + + private Node merge() { + if (leftChild.thisNodeSize == 0) { + // If the left node size is 0 then + // use the right node result + return rightChild.getLocalResult(); + } + else if (rightChild.thisNodeSize == 0) { + // If the right node size is 0 then + // use the left node result + return leftChild.getLocalResult(); + } + else { + // Combine the left and right nodes + return Nodes.conc(op.getOutputShape(), + leftChild.getLocalResult(), rightChild.getLocalResult()); + } + } + + private Node doTruncate(Node input) { + return isOrdered + ? input.truncate(index, input.count(), generator) + : input; + } + } +} diff --git a/jdk/test/java/util/stream/bootlib/java/util/stream/DefaultMethodStreams.java b/jdk/test/java/util/stream/bootlib/java/util/stream/DefaultMethodStreams.java new file mode 100644 index 00000000000..c75db568ef2 --- /dev/null +++ b/jdk/test/java/util/stream/bootlib/java/util/stream/DefaultMethodStreams.java @@ -0,0 +1,984 @@ +/* + * Copyright (c) 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. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package java.util.stream; + +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.Comparator; +import java.util.DoubleSummaryStatistics; +import java.util.IntSummaryStatistics; +import java.util.Iterator; +import java.util.LongSummaryStatistics; +import java.util.Optional; +import java.util.OptionalDouble; +import java.util.OptionalInt; +import java.util.OptionalLong; +import java.util.PrimitiveIterator; +import java.util.Set; +import java.util.Spliterator; +import java.util.function.BiConsumer; +import java.util.function.BiFunction; +import java.util.function.BinaryOperator; +import java.util.function.Consumer; +import java.util.function.DoubleBinaryOperator; +import java.util.function.DoubleConsumer; +import java.util.function.DoubleFunction; +import java.util.function.DoublePredicate; +import java.util.function.DoubleToIntFunction; +import java.util.function.DoubleToLongFunction; +import java.util.function.DoubleUnaryOperator; +import java.util.function.Function; +import java.util.function.IntBinaryOperator; +import java.util.function.IntConsumer; +import java.util.function.IntFunction; +import java.util.function.IntPredicate; +import java.util.function.IntToDoubleFunction; +import java.util.function.IntToLongFunction; +import java.util.function.IntUnaryOperator; +import java.util.function.LongBinaryOperator; +import java.util.function.LongConsumer; +import java.util.function.LongFunction; +import java.util.function.LongPredicate; +import java.util.function.LongToDoubleFunction; +import java.util.function.LongToIntFunction; +import java.util.function.LongUnaryOperator; +import java.util.function.ObjDoubleConsumer; +import java.util.function.ObjIntConsumer; +import java.util.function.ObjLongConsumer; +import java.util.function.Predicate; +import java.util.function.Supplier; +import java.util.function.ToDoubleFunction; + +import java.util.function.ToIntFunction; +import java.util.function.ToLongFunction; + +import static java.util.stream.Collectors.*; + +public final class DefaultMethodStreams { + + static { + // Verify that default methods are not overridden + verify(DefaultMethodRefStream.class); + verify(DefaultMethodIntStream.class); + verify(DefaultMethodLongStream.class); + verify(DefaultMethodDoubleStream.class); + } + + static void verify(Class del) { + // Find the stream interface + Class s = Stream.of(del.getInterfaces()) + .filter(c -> BaseStream.class.isAssignableFrom(c)) + .findFirst().get(); + + // Get all default methods on the stream class + Set dms = Stream.of(s.getMethods()) + .filter(m -> !Modifier.isStatic(m.getModifiers())) + .filter(m -> !m.isBridge()) + .filter(Method::isDefault) + .map(Method::getName) + .collect(toSet()); + + // Get all methods on the delegating class + Set ims = Stream.of(del.getMethods()) + .filter(m -> !Modifier.isStatic(m.getModifiers())) + .filter(m -> m.getDeclaringClass() == del) + .map(Method::getName) + .collect(toSet()); + + if (ims.stream().anyMatch(dms::contains)) { + throw new AssertionError(String.format("%s overrides default methods of %s\n", del, s)); + } + } + + /** + * Creates a stream that for the next operation either delegates to + * a default method on {@link Stream}, if present for that operation, + * otherwise delegates to an underlying stream. + * + * @param s the underlying stream to be delegated to for non-default + * methods. + * @param the type of the stream elements + * @return the delegating stream + */ + public static Stream delegateTo(Stream s) { + return new DefaultMethodRefStream<>(s); + } + + /** + * Creates a stream that for the next operation either delegates to + * a default method on {@link IntStream}, if present for that operation, + * otherwise delegates to an underlying stream. + * + * @param s the underlying stream to be delegated to for non-default + * methods. + * @return the delegating stream + */ + public static IntStream delegateTo(IntStream s) { + return new DefaultMethodIntStream(s); + } + + /** + * Creates a stream that for the next operation either delegates to + * a default method on {@link LongStream}, if present for that operation, + * otherwise delegates to an underlying stream. + * + * @param s the underlying stream to be delegated to for non-default + * methods. + * @return the delegating stream + */ + public static LongStream delegateTo(LongStream s) { + return new DefaultMethodLongStream(s); + } + + /** + * Creates a stream that for the next operation either delegates to + * a default method on {@link DoubleStream}, if present for that operation, + * otherwise delegates to an underlying stream. + * + * @param s the underlying stream to be delegated to for non-default + * methods. + * @return the delegating stream + */ + public static DoubleStream delegateTo(DoubleStream s) { + return new DefaultMethodDoubleStream(s); + } + + /** + * A stream that delegates the next operation to a default method, if + * present, or to the same operation of an underlying stream. + * + * @param the type of the stream elements + */ + static final class DefaultMethodRefStream implements Stream { + final Stream s; + + DefaultMethodRefStream(Stream s) { + this.s = s; + } + + + // Delegating non-default methods + + @Override + public Stream filter(Predicate predicate) { + return s.filter(predicate); + } + + @Override + public Stream map(Function mapper) { + return s.map(mapper); + } + + @Override + public IntStream mapToInt(ToIntFunction mapper) { + return s.mapToInt(mapper); + } + + @Override + public LongStream mapToLong(ToLongFunction mapper) { + return s.mapToLong(mapper); + } + + @Override + public DoubleStream mapToDouble(ToDoubleFunction mapper) { + return s.mapToDouble(mapper); + } + + @Override + public Stream flatMap(Function> mapper) { + return s.flatMap(mapper); + } + + @Override + public IntStream flatMapToInt(Function mapper) { + return s.flatMapToInt(mapper); + } + + @Override + public LongStream flatMapToLong(Function mapper) { + return s.flatMapToLong(mapper); + } + + @Override + public DoubleStream flatMapToDouble(Function mapper) { + return s.flatMapToDouble(mapper); + } + + @Override + public Stream distinct() { + return s.distinct(); + } + + @Override + public Stream sorted() { + return s.sorted(); + } + + @Override + public Stream sorted(Comparator comparator) { + return s.sorted(comparator); + } + + @Override + public Stream peek(Consumer action) { + return s.peek(action); + } + + @Override + public Stream limit(long maxSize) { + return s.limit(maxSize); + } + + @Override + public Stream skip(long n) { + return s.skip(n); + } + + @Override + public void forEach(Consumer action) { + s.forEach(action); + } + + @Override + public void forEachOrdered(Consumer action) { + s.forEachOrdered(action); + } + + @Override + public Object[] toArray() { + return s.toArray(); + } + + @Override + public A[] toArray(IntFunction generator) { + return s.toArray(generator); + } + + @Override + public T reduce(T identity, BinaryOperator accumulator) { + return s.reduce(identity, accumulator); + } + + @Override + public Optional reduce(BinaryOperator accumulator) { + return s.reduce(accumulator); + } + + @Override + public U reduce(U identity, BiFunction accumulator, BinaryOperator combiner) { + return s.reduce(identity, accumulator, combiner); + } + + @Override + public R collect(Supplier supplier, BiConsumer accumulator, BiConsumer combiner) { + return s.collect(supplier, accumulator, combiner); + } + + @Override + public R collect(Collector collector) { + return s.collect(collector); + } + + @Override + public Optional min(Comparator comparator) { + return s.min(comparator); + } + + @Override + public Optional max(Comparator comparator) { + return s.max(comparator); + } + + @Override + public long count() { + return s.count(); + } + + @Override + public boolean anyMatch(Predicate predicate) { + return s.anyMatch(predicate); + } + + @Override + public boolean allMatch(Predicate predicate) { + return s.allMatch(predicate); + } + + @Override + public boolean noneMatch(Predicate predicate) { + return s.noneMatch(predicate); + } + + @Override + public Optional findFirst() { + return s.findFirst(); + } + + @Override + public Optional findAny() { + return s.findAny(); + } + + @Override + public Iterator iterator() { + return s.iterator(); + } + + @Override + public Spliterator spliterator() { + return s.spliterator(); + } + + @Override + public boolean isParallel() { + return s.isParallel(); + } + + @Override + public Stream sequential() { + return s.sequential(); + } + + @Override + public Stream parallel() { + return s.parallel(); + } + + @Override + public Stream unordered() { + return s.unordered(); + } + + @Override + public Stream onClose(Runnable closeHandler) { + return s.onClose(closeHandler); + } + + @Override + public void close() { + s.close(); + } + } + + static final class DefaultMethodIntStream implements IntStream { + final IntStream s; + + public DefaultMethodIntStream(IntStream s) { + this.s = s; + } + + + // Delegating non-default methods + + @Override + public IntStream filter(IntPredicate predicate) { + return s.filter(predicate); + } + + @Override + public IntStream map(IntUnaryOperator mapper) { + return s.map(mapper); + } + + @Override + public Stream mapToObj(IntFunction mapper) { + return s.mapToObj(mapper); + } + + @Override + public LongStream mapToLong(IntToLongFunction mapper) { + return s.mapToLong(mapper); + } + + @Override + public DoubleStream mapToDouble(IntToDoubleFunction mapper) { + return s.mapToDouble(mapper); + } + + @Override + public IntStream flatMap(IntFunction mapper) { + return s.flatMap(mapper); + } + + @Override + public IntStream distinct() { + return s.distinct(); + } + + @Override + public IntStream sorted() { + return s.sorted(); + } + + @Override + public IntStream peek(IntConsumer action) { + return s.peek(action); + } + + @Override + public IntStream limit(long maxSize) { + return s.limit(maxSize); + } + + @Override + public IntStream skip(long n) { + return s.skip(n); + } + + @Override + public void forEach(IntConsumer action) { + s.forEach(action); + } + + @Override + public void forEachOrdered(IntConsumer action) { + s.forEachOrdered(action); + } + + @Override + public int[] toArray() { + return s.toArray(); + } + + @Override + public int reduce(int identity, IntBinaryOperator op) { + return s.reduce(identity, op); + } + + @Override + public OptionalInt reduce(IntBinaryOperator op) { + return s.reduce(op); + } + + @Override + public R collect(Supplier supplier, ObjIntConsumer accumulator, BiConsumer combiner) { + return s.collect(supplier, accumulator, combiner); + } + + @Override + public int sum() { + return s.sum(); + } + + @Override + public OptionalInt min() { + return s.min(); + } + + @Override + public OptionalInt max() { + return s.max(); + } + + @Override + public long count() { + return s.count(); + } + + @Override + public OptionalDouble average() { + return s.average(); + } + + @Override + public IntSummaryStatistics summaryStatistics() { + return s.summaryStatistics(); + } + + @Override + public boolean anyMatch(IntPredicate predicate) { + return s.anyMatch(predicate); + } + + @Override + public boolean allMatch(IntPredicate predicate) { + return s.allMatch(predicate); + } + + @Override + public boolean noneMatch(IntPredicate predicate) { + return s.noneMatch(predicate); + } + + @Override + public OptionalInt findFirst() { + return s.findFirst(); + } + + @Override + public OptionalInt findAny() { + return s.findAny(); + } + + @Override + public LongStream asLongStream() { + return s.asLongStream(); + } + + @Override + public DoubleStream asDoubleStream() { + return s.asDoubleStream(); + } + + @Override + public Stream boxed() { + return s.boxed(); + } + + @Override + public IntStream sequential() { + return s.sequential(); + } + + @Override + public IntStream parallel() { + return s.parallel(); + } + + @Override + public PrimitiveIterator.OfInt iterator() { + return s.iterator(); + } + + @Override + public Spliterator.OfInt spliterator() { + return s.spliterator(); + } + + @Override + public boolean isParallel() { + return s.isParallel(); + } + + @Override + public IntStream unordered() { + return s.unordered(); + } + + @Override + public IntStream onClose(Runnable closeHandler) { + return s.onClose(closeHandler); + } + + @Override + public void close() { + s.close(); + } + } + + static final class DefaultMethodLongStream implements LongStream { + final LongStream s; + + public DefaultMethodLongStream(LongStream s) { + this.s = s; + } + + + // Delegating non-default methods + + @Override + public void forEach(LongConsumer action) { + s.forEach(action); + } + + @Override + public LongStream filter(LongPredicate predicate) { + return s.filter(predicate); + } + + @Override + public LongStream map(LongUnaryOperator mapper) { + return s.map(mapper); + } + + @Override + public Stream mapToObj(LongFunction mapper) { + return s.mapToObj(mapper); + } + + @Override + public IntStream mapToInt(LongToIntFunction mapper) { + return s.mapToInt(mapper); + } + + @Override + public DoubleStream mapToDouble(LongToDoubleFunction mapper) { + return s.mapToDouble(mapper); + } + + @Override + public LongStream flatMap(LongFunction mapper) { + return s.flatMap(mapper); + } + + @Override + public LongStream distinct() { + return s.distinct(); + } + + @Override + public LongStream sorted() { + return s.sorted(); + } + + @Override + public LongStream peek(LongConsumer action) { + return s.peek(action); + } + + @Override + public LongStream limit(long maxSize) { + return s.limit(maxSize); + } + + @Override + public LongStream skip(long n) { + return s.skip(n); + } + + @Override + public void forEachOrdered(LongConsumer action) { + s.forEachOrdered(action); + } + + @Override + public long[] toArray() { + return s.toArray(); + } + + @Override + public long reduce(long identity, LongBinaryOperator op) { + return s.reduce(identity, op); + } + + @Override + public OptionalLong reduce(LongBinaryOperator op) { + return s.reduce(op); + } + + @Override + public R collect(Supplier supplier, ObjLongConsumer accumulator, BiConsumer combiner) { + return s.collect(supplier, accumulator, combiner); + } + + @Override + public long sum() { + return s.sum(); + } + + @Override + public OptionalLong min() { + return s.min(); + } + + @Override + public OptionalLong max() { + return s.max(); + } + + @Override + public long count() { + return s.count(); + } + + @Override + public OptionalDouble average() { + return s.average(); + } + + @Override + public LongSummaryStatistics summaryStatistics() { + return s.summaryStatistics(); + } + + @Override + public boolean anyMatch(LongPredicate predicate) { + return s.anyMatch(predicate); + } + + @Override + public boolean allMatch(LongPredicate predicate) { + return s.allMatch(predicate); + } + + @Override + public boolean noneMatch(LongPredicate predicate) { + return s.noneMatch(predicate); + } + + @Override + public OptionalLong findFirst() { + return s.findFirst(); + } + + @Override + public OptionalLong findAny() { + return s.findAny(); + } + + @Override + public DoubleStream asDoubleStream() { + return s.asDoubleStream(); + } + + @Override + public Stream boxed() { + return s.boxed(); + } + + @Override + public LongStream sequential() { + return s.sequential(); + } + + @Override + public LongStream parallel() { + return s.parallel(); + } + + @Override + public PrimitiveIterator.OfLong iterator() { + return s.iterator(); + } + + @Override + public Spliterator.OfLong spliterator() { + return s.spliterator(); + } + + @Override + public boolean isParallel() { + return s.isParallel(); + } + + @Override + public LongStream unordered() { + return s.unordered(); + } + + @Override + public LongStream onClose(Runnable closeHandler) { + return s.onClose(closeHandler); + } + + @Override + public void close() { + s.close(); + } + } + + static final class DefaultMethodDoubleStream implements DoubleStream { + final DoubleStream s; + + public DefaultMethodDoubleStream(DoubleStream s) { + this.s = s; + } + + @Override + public DoubleStream filter(DoublePredicate predicate) { + return s.filter(predicate); + } + + @Override + public DoubleStream map(DoubleUnaryOperator mapper) { + return s.map(mapper); + } + + @Override + public Stream mapToObj(DoubleFunction mapper) { + return s.mapToObj(mapper); + } + + @Override + public IntStream mapToInt(DoubleToIntFunction mapper) { + return s.mapToInt(mapper); + } + + @Override + public LongStream mapToLong(DoubleToLongFunction mapper) { + return s.mapToLong(mapper); + } + + @Override + public DoubleStream flatMap(DoubleFunction mapper) { + return s.flatMap(mapper); + } + + @Override + public DoubleStream distinct() { + return s.distinct(); + } + + @Override + public DoubleStream sorted() { + return s.sorted(); + } + + @Override + public DoubleStream peek(DoubleConsumer action) { + return s.peek(action); + } + + @Override + public DoubleStream limit(long maxSize) { + return s.limit(maxSize); + } + + @Override + public DoubleStream skip(long n) { + return s.skip(n); + } + + @Override + public void forEach(DoubleConsumer action) { + s.forEach(action); + } + + @Override + public void forEachOrdered(DoubleConsumer action) { + s.forEachOrdered(action); + } + + @Override + public double[] toArray() { + return s.toArray(); + } + + @Override + public double reduce(double identity, DoubleBinaryOperator op) { + return s.reduce(identity, op); + } + + @Override + public OptionalDouble reduce(DoubleBinaryOperator op) { + return s.reduce(op); + } + + @Override + public R collect(Supplier supplier, ObjDoubleConsumer accumulator, BiConsumer combiner) { + return s.collect(supplier, accumulator, combiner); + } + + @Override + public double sum() { + return s.sum(); + } + + @Override + public OptionalDouble min() { + return s.min(); + } + + @Override + public OptionalDouble max() { + return s.max(); + } + + @Override + public long count() { + return s.count(); + } + + @Override + public OptionalDouble average() { + return s.average(); + } + + @Override + public DoubleSummaryStatistics summaryStatistics() { + return s.summaryStatistics(); + } + + @Override + public boolean anyMatch(DoublePredicate predicate) { + return s.anyMatch(predicate); + } + + @Override + public boolean allMatch(DoublePredicate predicate) { + return s.allMatch(predicate); + } + + @Override + public boolean noneMatch(DoublePredicate predicate) { + return s.noneMatch(predicate); + } + + @Override + public OptionalDouble findFirst() { + return s.findFirst(); + } + + @Override + public OptionalDouble findAny() { + return s.findAny(); + } + + @Override + public Stream boxed() { + return s.boxed(); + } + + @Override + public DoubleStream sequential() { + return s.sequential(); + } + + @Override + public DoubleStream parallel() { + return s.parallel(); + } + + @Override + public PrimitiveIterator.OfDouble iterator() { + return s.iterator(); + } + + @Override + public Spliterator.OfDouble spliterator() { + return s.spliterator(); + } + + @Override + public boolean isParallel() { + return s.isParallel(); + } + + @Override + public DoubleStream unordered() { + return s.unordered(); + } + + @Override + public DoubleStream onClose(Runnable closeHandler) { + return s.onClose(closeHandler); + } + + @Override + public void close() { + s.close(); + } + } +} \ No newline at end of file diff --git a/jdk/test/java/util/stream/bootlib/java/util/stream/StreamTestDataProvider.java b/jdk/test/java/util/stream/bootlib/java/util/stream/StreamTestDataProvider.java index cc98529df7f..6f772f391ee 100644 --- a/jdk/test/java/util/stream/bootlib/java/util/stream/StreamTestDataProvider.java +++ b/jdk/test/java/util/stream/bootlib/java/util/stream/StreamTestDataProvider.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 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 @@ -119,7 +119,7 @@ public class StreamTestDataProvider { // Simple combination of numbers and null values, probably excessive but may catch // errors for initialization/termination/sequence - // @@@ This is separate from the other data for now until nulls are consitently supported by + // @@@ This is separate from the other data for now until nulls are consistently supported by // all operations { List list = new ArrayList<>(); diff --git a/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/WhileOpStatefulTest.java b/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/WhileOpStatefulTest.java new file mode 100644 index 00000000000..4c39ae6022d --- /dev/null +++ b/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/WhileOpStatefulTest.java @@ -0,0 +1,304 @@ +/* + * Copyright (c) 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. + */ +package org.openjdk.tests.java.util.stream; + +import org.testng.annotations.Test; + +import java.util.HashMap; +import java.util.LinkedList; +import java.util.Map; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicLong; +import java.util.function.BooleanSupplier; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.function.Supplier; +import java.util.stream.DefaultMethodStreams; +import java.util.stream.DoubleStream; +import java.util.stream.IntStream; +import java.util.stream.LongStream; +import java.util.stream.OpTestCase; +import java.util.stream.Stream; + +import static java.util.stream.Collectors.toCollection; + +/* + * @test + * @bug 8071597 + */ +@Test +public class WhileOpStatefulTest extends OpTestCase { + static final long COUNT_PERIOD = 100; + + static final long EXECUTION_TIME_LIMIT = TimeUnit.SECONDS.toMillis(10); + + static final long TAKE_WHILE_COUNT_LIMIT = 100_000; + + static final int DROP_SOURCE_SIZE = 10_000; + + static final long DROP_WHILE_COUNT_LIMIT = 5000; + + @Test + public void testTimedTakeWithCount() { + testTakeWhileMulti( + s -> { + BooleanSupplier isWithinTakePeriod = + within(System.currentTimeMillis(), COUNT_PERIOD); + s.takeWhile(e -> isWithinTakePeriod.getAsBoolean()) + .mapToLong(e -> 1).reduce(0, Long::sum); + }, + s -> { + BooleanSupplier isWithinTakePeriod = + within(System.currentTimeMillis(), COUNT_PERIOD); + s.takeWhile(e -> isWithinTakePeriod.getAsBoolean()) + .mapToLong(e -> 1).reduce(0, Long::sum); + }, + s -> { + BooleanSupplier isWithinTakePeriod = + within(System.currentTimeMillis(), COUNT_PERIOD); + s.takeWhile(e -> isWithinTakePeriod.getAsBoolean()) + .map(e -> 1).reduce(0, Long::sum); + }, + s -> { + BooleanSupplier isWithinTakePeriod = + within(System.currentTimeMillis(), COUNT_PERIOD); + s.takeWhile(e -> isWithinTakePeriod.getAsBoolean()) + .mapToLong(e -> 1).reduce(0, Long::sum); + }); + } + + @Test + public void testCountTakeWithCount() { + testTakeWhileMulti( + s -> { + AtomicLong c = new AtomicLong(); + long rc = s.takeWhile(e -> c.getAndIncrement() < TAKE_WHILE_COUNT_LIMIT) + .mapToLong(e -> 1).reduce(0, Long::sum); + assertTrue(rc <= c.get()); + }, + s -> { + AtomicLong c = new AtomicLong(); + long rc = s.takeWhile(e -> c.getAndIncrement() < TAKE_WHILE_COUNT_LIMIT) + .mapToLong(e -> 1).reduce(0, Long::sum); + assertTrue(rc <= c.get()); + }, + s -> { + AtomicLong c = new AtomicLong(); + long rc = s.takeWhile(e -> c.getAndIncrement() < TAKE_WHILE_COUNT_LIMIT) + .map(e -> 1).reduce(0, Long::sum); + assertTrue(rc <= c.get()); + }, + s -> { + AtomicLong c = new AtomicLong(); + long rc = s.takeWhile(e -> c.getAndIncrement() < TAKE_WHILE_COUNT_LIMIT) + .mapToLong(e -> 1).reduce(0, Long::sum); + assertTrue(rc <= c.get()); + }); + } + + @Test + public void testCountTakeWithToArray() { + testTakeWhileMulti( + s -> { + AtomicLong c = new AtomicLong(); + Object[] ra = s.takeWhile(e -> c.getAndIncrement() < TAKE_WHILE_COUNT_LIMIT) + .toArray(); + assertTrue(ra.length <= c.get()); + }, + s -> { + AtomicLong c = new AtomicLong(); + int[] ra = s.takeWhile(e -> c.getAndIncrement() < TAKE_WHILE_COUNT_LIMIT) + .toArray(); + assertTrue(ra.length <= c.get()); + }, + s -> { + AtomicLong c = new AtomicLong(); + long[] ra = s.takeWhile(e -> c.getAndIncrement() < TAKE_WHILE_COUNT_LIMIT) + .toArray(); + assertTrue(ra.length <= c.get()); + }, + s -> { + AtomicLong c = new AtomicLong(); + double[] ra = s.takeWhile(e -> c.getAndIncrement() < TAKE_WHILE_COUNT_LIMIT) + .toArray(); + assertTrue(ra.length <= c.get()); + }); + } + + + @Test + public void testCountDropWithCount() { + testDropWhileMulti( + s -> { + AtomicLong c = new AtomicLong(); + long rc = s.dropWhile(e -> c.getAndIncrement() < DROP_WHILE_COUNT_LIMIT) + .mapToLong(e -> 1).reduce(0, Long::sum); + assertTrue(c.get() >= DROP_WHILE_COUNT_LIMIT); + assertTrue(rc <= DROP_SOURCE_SIZE); + }, + s -> { + AtomicLong c = new AtomicLong(); + long rc = s.dropWhile(e -> c.getAndIncrement() < DROP_WHILE_COUNT_LIMIT) + .mapToLong(e -> 1).reduce(0, Long::sum); + assertTrue(c.get() >= DROP_WHILE_COUNT_LIMIT); + assertTrue(rc <= DROP_SOURCE_SIZE); + }, + s -> { + AtomicLong c = new AtomicLong(); + long rc = s.dropWhile(e -> c.getAndIncrement() < DROP_WHILE_COUNT_LIMIT) + .map(e -> 1).reduce(0, Long::sum); + assertTrue(c.get() >= DROP_WHILE_COUNT_LIMIT); + assertTrue(rc <= DROP_SOURCE_SIZE); + }, + s -> { + AtomicLong c = new AtomicLong(); + long rc = s.dropWhile(e -> c.getAndIncrement() < DROP_WHILE_COUNT_LIMIT) + .mapToLong(e -> 1).reduce(0, Long::sum); + assertTrue(c.get() >= DROP_WHILE_COUNT_LIMIT); + assertTrue(rc <= DROP_SOURCE_SIZE); + }); + } + + @Test + public void testCountDropWithToArray() { + testDropWhileMulti( + s -> { + AtomicLong c = new AtomicLong(); + Object[] ra = s.dropWhile(e -> c.getAndIncrement() < DROP_WHILE_COUNT_LIMIT) + .toArray(); + assertTrue(c.get() >= DROP_WHILE_COUNT_LIMIT); + assertTrue(ra.length <= DROP_SOURCE_SIZE); + }, + s -> { + AtomicLong c = new AtomicLong(); + int[] ra = s.dropWhile(e -> c.getAndIncrement() < DROP_WHILE_COUNT_LIMIT) + .toArray(); + assertTrue(c.get() >= DROP_WHILE_COUNT_LIMIT); + assertTrue(ra.length <= DROP_SOURCE_SIZE); + }, + s -> { + AtomicLong c = new AtomicLong(); + long[] ra = s.dropWhile(e -> c.getAndIncrement() < DROP_WHILE_COUNT_LIMIT) + .toArray(); + assertTrue(c.get() >= DROP_WHILE_COUNT_LIMIT); + assertTrue(ra.length <= DROP_SOURCE_SIZE); + }, + s -> { + AtomicLong c = new AtomicLong(); + double[] ra = s.dropWhile(e -> c.getAndIncrement() < DROP_WHILE_COUNT_LIMIT) + .toArray(); + assertTrue(c.get() >= DROP_WHILE_COUNT_LIMIT); + assertTrue(ra.length <= DROP_SOURCE_SIZE); + }); + } + + + private void testTakeWhileMulti(Consumer> mRef, + Consumer mInt, + Consumer mLong, + Consumer mDouble) { + Map>> sources = new HashMap<>(); + sources.put("Stream.generate()", () -> Stream.generate(() -> 1)); + sources.put("Stream.iterate()", () -> Stream.iterate(1, x -> 1)); + sources.put("Stream.iterate().unordered()", () -> Stream.iterate(1, x -> 1)); + testWhileMulti(sources, mRef, mInt, mLong, mDouble); + } + + private void testDropWhileMulti(Consumer> mRef, + Consumer mInt, + Consumer mLong, + Consumer mDouble) { + Map>> sources = new HashMap<>(); + sources.put("IntStream.range().boxed()", + () -> IntStream.range(0, DROP_SOURCE_SIZE).boxed()); + sources.put("IntStream.range().boxed().unordered()", + () -> IntStream.range(0, DROP_SOURCE_SIZE).boxed().unordered()); + sources.put("LinkedList.stream()", + () -> IntStream.range(0, DROP_SOURCE_SIZE).boxed() + .collect(toCollection(LinkedList::new)) + .stream()); + sources.put("LinkedList.stream().unordered()", + () -> IntStream.range(0, DROP_SOURCE_SIZE).boxed() + .collect(toCollection(LinkedList::new)) + .stream() + .unordered()); + testWhileMulti(sources, mRef, mInt, mLong, mDouble); + } + + private void testWhileMulti(Map>> sources, + Consumer> mRef, + Consumer mInt, + Consumer mLong, + Consumer mDouble) { + Map, Stream>> transforms = new HashMap<>(); + transforms.put("Stream.sequential()", s -> { + BooleanSupplier isWithinExecutionPeriod = within(System.currentTimeMillis(), + EXECUTION_TIME_LIMIT); + return s.peek(e -> { + if (!isWithinExecutionPeriod.getAsBoolean()) { + throw new RuntimeException(); + } + }); + }); + transforms.put("Stream.parallel()", s -> { + BooleanSupplier isWithinExecutionPeriod = within(System.currentTimeMillis(), + EXECUTION_TIME_LIMIT); + return s.parallel() + .peek(e -> { + if (!isWithinExecutionPeriod.getAsBoolean()) { + throw new RuntimeException(); + } + }); + }); + + Map>> actions = new HashMap<>(); + actions.put("Ref", mRef); + actions.put("Int", s -> mInt.accept(s.mapToInt(e -> e))); + actions.put("Long", s -> mLong.accept(s.mapToLong(e -> e))); + actions.put("Double", s -> mDouble.accept(s.mapToDouble(e -> e))); + actions.put("Ref using defaults", s -> mRef.accept(DefaultMethodStreams.delegateTo(s))); + actions.put("Int using defaults", s -> mInt.accept(DefaultMethodStreams.delegateTo(s.mapToInt(e -> e)))); + actions.put("Long using defaults", s -> mLong.accept(DefaultMethodStreams.delegateTo(s.mapToLong(e -> e)))); + actions.put("Double using defaults", s -> mDouble.accept(DefaultMethodStreams.delegateTo(s.mapToDouble(e -> e)))); + + for (Map.Entry>> s : sources.entrySet()) { + setContext("source", s.getKey()); + + for (Map.Entry, Stream>> t : transforms.entrySet()) { + setContext("transform", t.getKey()); + + for (Map.Entry>> a : actions.entrySet()) { + setContext("shape", a.getKey()); + + Stream stream = s.getValue().get(); + stream = t.getValue().apply(stream); + a.getValue().accept(stream); + } + } + } + } + + static BooleanSupplier within(long start, long durationInMillis) { + return () -> (System.currentTimeMillis() - start) < durationInMillis; + } +} diff --git a/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/WhileOpTest.java b/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/WhileOpTest.java new file mode 100644 index 00000000000..b710791fb4e --- /dev/null +++ b/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/WhileOpTest.java @@ -0,0 +1,361 @@ +/* + * Copyright (c) 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. + */ +package org.openjdk.tests.java.util.stream; + +import org.testng.annotations.Test; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.function.Function; +import java.util.function.Predicate; +import java.util.stream.DefaultMethodStreams; +import java.util.stream.DoubleStream; +import java.util.stream.IntStream; +import java.util.stream.LambdaTestHelpers; +import java.util.stream.LongStream; +import java.util.stream.OpTestCase; +import java.util.stream.Stream; +import java.util.stream.StreamTestDataProvider; +import java.util.stream.TestData; + +/* + * @test + * @bug 8071597 + */ +@Test +public class WhileOpTest extends OpTestCase { + + @Test(dataProvider = "StreamTestData", dataProviderClass = StreamTestDataProvider.class) + public void testTakeWhileOps(String name, TestData.OfRef data) { + for (int size : sizes(data.size())) { + setContext("takeWhile", size); + + testWhileMulti(data, + whileResultAsserter(data, WhileOp.Take, e -> e < size), + s -> s.takeWhile(e -> e < size), + s -> s.takeWhile(e -> e < size), + s -> s.takeWhile(e -> e < size), + s -> s.takeWhile(e -> e < size)); + + + testWhileMulti(data, + whileResultAsserter(data, WhileOp.Take, e -> e < size / 2), + s -> s.takeWhile(e -> e < size).takeWhile(e -> e < size / 2), + s -> s.takeWhile(e -> e < size).takeWhile(e -> e < size / 2), + s -> s.takeWhile(e -> e < size).takeWhile(e -> e < size / 2), + s -> s.takeWhile(e -> e < size).takeWhile(e -> e < size / 2)); + } + } + + @Test(dataProvider = "StreamTestData", dataProviderClass = StreamTestDataProvider.class) + public void testDropWhileOps(String name, TestData.OfRef data) { + for (int size : sizes(data.size())) { + setContext("dropWhile", size); + + testWhileMulti(data, + whileResultAsserter(data, WhileOp.Drop, e -> e < size), + s -> s.dropWhile(e -> e < size), + s -> s.dropWhile(e -> e < size), + s -> s.dropWhile(e -> e < size), + s -> s.dropWhile(e -> e < size)); + + testWhileMulti(data, + whileResultAsserter(data, WhileOp.Drop, e -> e < size), + s -> s.dropWhile(e -> e < size / 2).dropWhile(e -> e < size), + s -> s.dropWhile(e -> e < size / 2).dropWhile(e -> e < size), + s -> s.dropWhile(e -> e < size / 2).dropWhile(e -> e < size), + s -> s.dropWhile(e -> e < size / 2).dropWhile(e -> e < size)); + } + } + + @Test(dataProvider = "StreamTestData", dataProviderClass = StreamTestDataProvider.class) + public void testDropTakeWhileOps(String name, TestData.OfRef data) { + for (int size : sizes(data.size())) { + setContext("dropWhile", size); + + testWhileMulti(data, + whileResultAsserter(data, WhileOp.Undefined, null), + s -> s.dropWhile(e -> e < size / 2).takeWhile(e -> e < size), + s -> s.dropWhile(e -> e < size / 2).takeWhile(e -> e < size), + s -> s.dropWhile(e -> e < size / 2).takeWhile(e -> e < size), + s -> s.dropWhile(e -> e < size / 2).takeWhile(e -> e < size)); + } + } + + /** + * While operation type to be asserted on + */ + enum WhileOp { + /** + * The takeWhile operation + */ + Take, + /** + * The dropWhile operation + */ + Drop, + /** + * The operation(s) are undefined + */ + Undefined + } + + /** + * Create a result asserter for takeWhile or dropWhile operations. + *

      + * If the stream pipeline consists of the takeWhile operation + * ({@link WhileOp#Take}) or the dropWhile operation ({@link WhileOp#Drop}) + * then specific assertions can be made on the actual result based on the + * input elements, {@code inputData}, and whether those elements match the + * predicate, {@code p}, of the operation. + *

      + * If the input elements have an encounter order then the actual result + * is asserted against the result of operating sequentially on input + * elements given the predicate and in accordance with the operation + * semantics. (The actual result whether produced sequentially or in + * parallel should the same.) + *

      + * If the input elements have no encounter order then an actual result + * is, for practical purposes, considered non-deterministic. + * Consider an input list of lists that contains all possible permutations + * of the input elements, and a output list of lists that is the result of + * applying the pipeline with the operation sequentially to each input + * list. + * Any list in the output lists is a valid result. It's not practical to + * test in such a manner. + * For a takeWhile operation the following assertions can be made if + * only some of the input elements match the predicate (i.e. taking will + * short-circuit the pipeline): + *

        + *
      1. The set of output elements is a subset of the set of matching + * input elements
      2. + *
      3. The set of output elements and the set of non-matching input + * element are disjoint
      4. + *
      + * For a dropWhile operation the following assertions can be made: + *
        + *
      1. The set of non-matching input elements is a subset of the set of + * output elements
      2. + *
      3. The set of matching output elements is a subset of the set of + * matching input elements
      4. + *
      + * + * @param inputData the elements input into the stream pipeline + * @param op the operation of the stream pipeline, one of takeWhile, + * dropWhile, or an undefined set of operations (possibly including + * two or more takeWhile and/or dropWhile operations, or because + * the predicate is not stateless). + * @param p the stateless predicate applied to the operation, ignored if + * the + * operation is {@link WhileOp#Undefined}. + * @param the type of elements + * @return a result asserter + */ + private ResultAsserter> whileResultAsserter(Iterable inputData, + WhileOp op, + Predicate p) { + return (act, exp, ord, par) -> { + if (par & !ord) { + List input = new ArrayList<>(); + inputData.forEach(input::add); + + List output = new ArrayList<>(); + act.forEach(output::add); + + if (op == WhileOp.Take) { + List matchingInput = new ArrayList<>(); + List nonMatchingInput = new ArrayList<>(); + input.forEach(t -> { + if (p.test(t)) + matchingInput.add(t); + else + nonMatchingInput.add(t); + }); + + // If some, not all, elements are taken + if (matchingInput.size() < input.size()) { + assertTrue(output.size() <= matchingInput.size(), + "Output is larger than the matching input"); + + // The output must be a subset of the matching input + assertTrue(matchingInput.containsAll(output), + "Output is not a subset of the matching input"); + + // The output must not contain any non matching elements + for (T nonMatching : nonMatchingInput) { + assertFalse(output.contains(nonMatching), + "Output and non-matching input are not disjoint"); + } + } + } + else if (op == WhileOp.Drop) { + List matchingInput = new ArrayList<>(); + List nonMatchingInput = new ArrayList<>(); + input.forEach(t -> { + if (p.test(t)) + matchingInput.add(t); + else + nonMatchingInput.add(t); + }); + + // The non matching input must be a subset of output + assertTrue(output.containsAll(nonMatchingInput), + "Non-matching input is not a subset of the output"); + + // The matching output must be a subset of the matching input + List matchingOutput = new ArrayList<>(); + output.forEach(i -> { + if (p.test(i)) + matchingOutput.add(i); + }); + assertTrue(matchingInput.containsAll(matchingOutput), + "Matching output is not a subset of matching input"); + } + + // Note: if there is a combination of takeWhile and dropWhile then specific + // assertions cannot be performed. + // All that can be reliably asserted is the output is a subset of the input + + assertTrue(input.containsAll(output)); + } + else { + // For specific operations derive expected result from the input + if (op == WhileOp.Take) { + List takeInput = new ArrayList<>(); + for (T t : inputData) { + if (p.test(t)) + takeInput.add(t); + else + break; + } + + LambdaTestHelpers.assertContents(act, takeInput); + } + else if (op == WhileOp.Drop) { + List dropInput = new ArrayList<>(); + for (T t : inputData) { + if (dropInput.size() > 0 || !p.test(t)) + dropInput.add(t); + } + + LambdaTestHelpers.assertContents(act, dropInput); + } + + LambdaTestHelpers.assertContents(act, exp); + } + }; + } + + private Collection sizes(int s) { + Set sizes = new LinkedHashSet<>(); + + sizes.add(0); + sizes.add(1); + sizes.add(s / 4); + sizes.add(s / 2); + sizes.add(3 * s / 4); + sizes.add(Math.max(0, s - 1)); + sizes.add(s); + sizes.add(Integer.MAX_VALUE); + + return sizes; + } + + private void testWhileMulti(TestData.OfRef data, + ResultAsserter> ra, + Function, Stream> mRef, + Function mInt, + Function mLong, + Function mDouble) { + Map, Stream>> ms = new HashMap<>(); + ms.put("Ref", mRef); + ms.put("Int", s -> mInt.apply(s.mapToInt(e -> e)).mapToObj(e -> e)); + ms.put("Long", s -> mLong.apply(s.mapToLong(e -> e)).mapToObj(e -> (int) e)); + ms.put("Double", s -> mDouble.apply(s.mapToDouble(e -> e)).mapToObj(e -> (int) e)); + ms.put("Ref using defaults", s -> mRef.apply(DefaultMethodStreams.delegateTo(s))); + ms.put("Int using defaults", s -> mInt.apply(DefaultMethodStreams.delegateTo(s.mapToInt(e -> e))).mapToObj(e -> e)); + ms.put("Long using defaults", s -> mLong.apply(DefaultMethodStreams.delegateTo(s.mapToLong(e -> e))).mapToObj(e -> (int) e)); + ms.put("Double using defaults", s -> mDouble.apply(DefaultMethodStreams.delegateTo(s.mapToDouble(e -> e))).mapToObj(e -> (int) e)); + + testWhileMulti(data, ra, ms); + } + + private final void testWhileMulti(TestData.OfRef data, + ResultAsserter> ra, + Map, Stream>> ms) { + for (Map.Entry, Stream>> e : ms.entrySet()) { + setContext("shape", e.getKey()); + + withData(data) + .stream(e.getValue()) + .resultAsserter(ra) + .exercise(); + } + } + + @Test + public void testRefDefaultClose() { + AtomicBoolean isClosed = new AtomicBoolean(); + Stream s = Stream.of(1, 2, 3).onClose(() -> isClosed.set(true)); + try (Stream ds = DefaultMethodStreams.delegateTo(s).takeWhile(e -> e < 3)) { + ds.count(); + } + assertTrue(isClosed.get()); + } + + @Test + public void testIntDefaultClose() { + AtomicBoolean isClosed = new AtomicBoolean(); + IntStream s = IntStream.of(1, 2, 3).onClose(() -> isClosed.set(true)); + try (IntStream ds = DefaultMethodStreams.delegateTo(s).takeWhile(e -> e < 3)) { + ds.count(); + } + assertTrue(isClosed.get()); + } + + @Test + public void testLongDefaultClose() { + AtomicBoolean isClosed = new AtomicBoolean(); + LongStream s = LongStream.of(1, 2, 3).onClose(() -> isClosed.set(true)); + try (LongStream ds = DefaultMethodStreams.delegateTo(s).takeWhile(e -> e < 3)) { + ds.count(); + } + assertTrue(isClosed.get()); + } + + @Test + public void testDoubleDefaultClose() { + AtomicBoolean isClosed = new AtomicBoolean(); + DoubleStream s = DoubleStream.of(1, 2, 3).onClose(() -> isClosed.set(true)); + try (DoubleStream ds = DefaultMethodStreams.delegateTo(s).takeWhile(e -> e < 3)) { + ds.count(); + } + assertTrue(isClosed.get()); + } +} From 9b9fde193fe6b2ea00703166a26e794cc7d943fc Mon Sep 17 00:00:00 2001 From: Ivan Gerasimov Date: Tue, 14 Jul 2015 02:03:35 +0300 Subject: [PATCH 40/43] 6854417: TESTBUG: java/util/regex/RegExTest.java fails intermittently Reviewed-by: sherman --- jdk/test/java/util/regex/RegExTest.java | 31 +++++++++++++++++-------- 1 file changed, 21 insertions(+), 10 deletions(-) diff --git a/jdk/test/java/util/regex/RegExTest.java b/jdk/test/java/util/regex/RegExTest.java index 875f5b718ba..b1c776138a7 100644 --- a/jdk/test/java/util/regex/RegExTest.java +++ b/jdk/test/java/util/regex/RegExTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 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 @@ -32,11 +32,11 @@ * 6358731 6178785 6284152 6231989 6497148 6486934 6233084 6504326 6635133 * 6350801 6676425 6878475 6919132 6931676 6948903 6990617 7014645 7039066 * 7067045 7014640 7189363 8007395 8013252 8013254 8012646 8023647 6559590 - * 8027645 8035076 8039124 8035975 8074678 + * 8027645 8035076 8039124 8035975 8074678 6854417 * @library /lib/testlibrary * @build jdk.testlibrary.* * @run main RegExTest - * @key intermittent randomness + * @key randomness */ import java.util.function.Function; @@ -3554,15 +3554,26 @@ public class RegExTest { // Create a short pattern to search for int patternLength = generator.nextInt(7) + 4; StringBuffer patternBuffer = new StringBuffer(patternLength); - for (int x=0; x Date: Tue, 14 Jul 2015 00:53:09 +0000 Subject: [PATCH 41/43] 8130461: HandshakeStatus.NEED_UNWRAP_AGAIN applies only to DTLS Reviewed-by: wetmore --- .../share/classes/javax/net/ssl/SSLEngineResult.java | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/jdk/src/java.base/share/classes/javax/net/ssl/SSLEngineResult.java b/jdk/src/java.base/share/classes/javax/net/ssl/SSLEngineResult.java index e2865e65e5a..e0ec97349df 100644 --- a/jdk/src/java.base/share/classes/javax/net/ssl/SSLEngineResult.java +++ b/jdk/src/java.base/share/classes/javax/net/ssl/SSLEngineResult.java @@ -156,8 +156,10 @@ public class SSLEngineResult { * This value is used to indicate that not-yet-interpreted data * has been previously received from the remote side, and does * not need to be received again. + *

      + * This handshake status only applies to DTLS. * - * @since 1.9 + * @since 9 */ NEED_UNWRAP_AGAIN; } @@ -219,7 +221,7 @@ public class SSLEngineResult { * arguments are null, or if {@code bytesConsumed} or * {@code bytesProduced} is negative * - * @since 1.9 + * @since 9 */ public SSLEngineResult(Status status, HandshakeStatus handshakeStatus, int bytesConsumed, int bytesProduced, long sequenceNumber) { @@ -302,7 +304,7 @@ public class SSLEngineResult { * * @see java.lang.Long#compareUnsigned(long, long) * - * @since 1.9 + * @since 9 */ final public long sequenceNumber() { return sequenceNumber; From 9ed9f4f4a93bde45818747b0bfa757aff1f06a5a Mon Sep 17 00:00:00 2001 From: Artem Smotrakov Date: Tue, 14 Jul 2015 16:46:28 +0100 Subject: [PATCH 42/43] 8130041: TsacertOptionTest.java intermittently fails on Mac Reviewed-by: vinnie --- jdk/test/sun/security/tools/jarsigner/TsacertOptionTest.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/jdk/test/sun/security/tools/jarsigner/TsacertOptionTest.java b/jdk/test/sun/security/tools/jarsigner/TsacertOptionTest.java index 67368ae2f74..62c03948414 100644 --- a/jdk/test/sun/security/tools/jarsigner/TsacertOptionTest.java +++ b/jdk/test/sun/security/tools/jarsigner/TsacertOptionTest.java @@ -120,6 +120,9 @@ public class TsacertOptionTest { // specify -tsadigestalg option because // TSA server uses SHA-1 digest algorithm OutputAnalyzer analyzer = ProcessTools.executeCommand(JARSIGNER, + "-J-Dhttp.proxyHost=", + "-J-Dhttp.proxyPort=", + "-J-Djava.net.useSystemProxies=", "-verbose", "-keystore", KEYSTORE, "-storepass", PASSWORD, From f570f46d3b8ebf224ef0759029051be96cd291ae Mon Sep 17 00:00:00 2001 From: Vinnie Ryan Date: Tue, 14 Jul 2015 20:14:29 +0100 Subject: [PATCH 43/43] 8131184: Add test sun/security/pkcs11/rsa/TestKeyPairGenerator.java to the problem list Reviewed-by: mullan --- jdk/test/ProblemList.txt | 3 +++ 1 file changed, 3 insertions(+) diff --git a/jdk/test/ProblemList.txt b/jdk/test/ProblemList.txt index 22078493fab..3002878cac3 100644 --- a/jdk/test/ProblemList.txt +++ b/jdk/test/ProblemList.txt @@ -298,6 +298,9 @@ sun/security/pkcs11/tls/TestPremaster.java windows-all # 8051770 sun/security/provider/SecureRandom/StrongSecureRandom.java macosx-10.10 +# 8074580 +sun/security/pkcs11/rsa/TestKeyPairGenerator.java generic-all + ############################################################################ # jdk_sound