From 5fa349cc42405ce58f77d5d946ac39389059b2c7 Mon Sep 17 00:00:00 2001 From: "Daniel D. Daugherty" Date: Wed, 5 Dec 2007 09:00:00 -0800 Subject: [PATCH 001/258] 6664627: Merge changes made only in hotspot 11 forward to jdk 7 Reviewed-by: jcoomes --- .../src/cpu/sparc/vm/stubGenerator_sparc.cpp | 1 + .../src/cpu/sparc/vm/vtableStubs_sparc.cpp | 57 +++++------------ .../src/cpu/x86/vm/stubGenerator_x86_32.cpp | 1 + .../src/cpu/x86/vm/stubGenerator_x86_64.cpp | 7 +++ hotspot/src/cpu/x86/vm/vtableStubs_x86_32.cpp | 34 +++++------ hotspot/src/cpu/x86/vm/vtableStubs_x86_64.cpp | 61 +++++++++---------- hotspot/src/share/vm/oops/klassVtable.cpp | 41 ++++++------- hotspot/src/share/vm/oops/klassVtable.hpp | 2 +- .../src/share/vm/runtime/sharedRuntime.cpp | 5 ++ .../src/share/vm/runtime/sharedRuntime.hpp | 1 + hotspot/src/share/vm/runtime/stubRoutines.cpp | 1 + hotspot/src/share/vm/runtime/stubRoutines.hpp | 2 + 12 files changed, 101 insertions(+), 112 deletions(-) diff --git a/hotspot/src/cpu/sparc/vm/stubGenerator_sparc.cpp b/hotspot/src/cpu/sparc/vm/stubGenerator_sparc.cpp index 03c74085734..290cedb9bb0 100644 --- a/hotspot/src/cpu/sparc/vm/stubGenerator_sparc.cpp +++ b/hotspot/src/cpu/sparc/vm/stubGenerator_sparc.cpp @@ -2911,6 +2911,7 @@ class StubGenerator: public StubCodeGenerator { // These entry points require SharedInfo::stack0 to be set up in non-core builds StubRoutines::_throw_AbstractMethodError_entry = generate_throw_exception("AbstractMethodError throw_exception", CAST_FROM_FN_PTR(address, SharedRuntime::throw_AbstractMethodError), false); + StubRoutines::_throw_IncompatibleClassChangeError_entry= generate_throw_exception("IncompatibleClassChangeError throw_exception", CAST_FROM_FN_PTR(address, SharedRuntime::throw_IncompatibleClassChangeError), false); StubRoutines::_throw_ArithmeticException_entry = generate_throw_exception("ArithmeticException throw_exception", CAST_FROM_FN_PTR(address, SharedRuntime::throw_ArithmeticException), true); StubRoutines::_throw_NullPointerException_entry = generate_throw_exception("NullPointerException throw_exception", CAST_FROM_FN_PTR(address, SharedRuntime::throw_NullPointerException), true); StubRoutines::_throw_NullPointerException_at_call_entry= generate_throw_exception("NullPointerException at call throw_exception", CAST_FROM_FN_PTR(address, SharedRuntime::throw_NullPointerException_at_call), false); diff --git a/hotspot/src/cpu/sparc/vm/vtableStubs_sparc.cpp b/hotspot/src/cpu/sparc/vm/vtableStubs_sparc.cpp index a1a5a82c838..c1ed4b351c5 100644 --- a/hotspot/src/cpu/sparc/vm/vtableStubs_sparc.cpp +++ b/hotspot/src/cpu/sparc/vm/vtableStubs_sparc.cpp @@ -175,17 +175,12 @@ VtableStub* VtableStubs::create_itable_stub(int vtable_index) { // %%%% Could load both offset and interface in one ldx, if they were // in the opposite order. This would save a load. __ ld_ptr(L0, base + itableOffsetEntry::interface_offset_in_bytes(), L1); -#ifdef ASSERT - Label ok; - // Check that entry is non-null and an Oop - __ bpr(Assembler::rc_nz, false, Assembler::pt, L1, ok); - __ delayed()->nop(); - __ stop("null entry point found in itable's offset table"); - __ bind(ok); - __ verify_oop(L1); -#endif // ASSERT - __ cmp(G5_interface, L1); + // If the entry is NULL then we've reached the end of the table + // without finding the expected interface, so throw an exception + Label throw_icce; + __ bpr(Assembler::rc_z, false, Assembler::pn, L1, throw_icce); + __ delayed()->cmp(G5_interface, L1); __ brx(Assembler::notEqual, true, Assembler::pn, search); __ delayed()->add(L0, itableOffsetEntry::size() * wordSize, L0); @@ -223,24 +218,30 @@ VtableStub* VtableStubs::create_itable_stub(int vtable_index) { __ JMP(G3_scratch, 0); __ delayed()->nop(); + __ bind(throw_icce); + Address icce(G3_scratch, StubRoutines::throw_IncompatibleClassChangeError_entry()); + __ jump_to(icce, 0); + __ delayed()->restore(); + masm->flush(); + + guarantee(__ pc() <= s->code_end(), "overflowed buffer"); + s->set_exception_points(npe_addr, ame_addr); return s; } int VtableStub::pd_code_size_limit(bool is_vtable_stub) { - if (TraceJumps || DebugVtables || CountCompiledCalls || VerifyOops) return 999; + if (TraceJumps || DebugVtables || CountCompiledCalls || VerifyOops) return 1000; else { const int slop = 2*BytesPerInstWord; // sethi;add (needed for long offsets) if (is_vtable_stub) { const int basic = 5*BytesPerInstWord; // ld;ld;ld,jmp,nop return basic + slop; } else { -#ifdef ASSERT - return 999; -#endif // ASSERT - const int basic = 17*BytesPerInstWord; // save, ld, ld, sll, and, add, add, ld, cmp, br, add, ld, add, ld, ld, jmp, restore + // save, ld, ld, sll, and, add, add, ld, cmp, br, add, ld, add, ld, ld, jmp, restore, sethi, jmpl, restore + const int basic = (20 LP64_ONLY(+ 6)) * BytesPerInstWord; return (basic + slop); } } @@ -252,29 +253,3 @@ int VtableStub::pd_code_alignment() { const unsigned int icache_line_size = 32; return icache_line_size; } - - -//Reconciliation History -// 1.2 97/12/09 17:13:31 vtableStubs_i486.cpp -// 1.4 98/01/21 19:18:37 vtableStubs_i486.cpp -// 1.5 98/02/13 16:33:55 vtableStubs_i486.cpp -// 1.7 98/03/05 17:17:28 vtableStubs_i486.cpp -// 1.9 98/05/18 09:26:17 vtableStubs_i486.cpp -// 1.10 98/05/26 16:28:13 vtableStubs_i486.cpp -// 1.11 98/05/27 08:51:35 vtableStubs_i486.cpp -// 1.12 98/06/15 15:04:12 vtableStubs_i486.cpp -// 1.13 98/07/28 18:44:22 vtableStubs_i486.cpp -// 1.15 98/08/28 11:31:19 vtableStubs_i486.cpp -// 1.16 98/09/02 12:58:31 vtableStubs_i486.cpp -// 1.17 98/09/04 12:15:52 vtableStubs_i486.cpp -// 1.18 98/11/19 11:55:24 vtableStubs_i486.cpp -// 1.19 99/01/12 14:57:56 vtableStubs_i486.cpp -// 1.20 99/01/19 17:42:52 vtableStubs_i486.cpp -// 1.22 99/01/21 10:29:25 vtableStubs_i486.cpp -// 1.30 99/06/02 15:27:39 vtableStubs_i486.cpp -// 1.26 99/06/24 14:25:07 vtableStubs_i486.cpp -// 1.23 99/02/22 14:37:52 vtableStubs_i486.cpp -// 1.28 99/06/29 18:06:17 vtableStubs_i486.cpp -// 1.29 99/07/22 17:03:44 vtableStubs_i486.cpp -// 1.30 99/08/11 09:33:27 vtableStubs_i486.cpp -//End diff --git a/hotspot/src/cpu/x86/vm/stubGenerator_x86_32.cpp b/hotspot/src/cpu/x86/vm/stubGenerator_x86_32.cpp index 98c1ce59a60..5ea4177f90b 100644 --- a/hotspot/src/cpu/x86/vm/stubGenerator_x86_32.cpp +++ b/hotspot/src/cpu/x86/vm/stubGenerator_x86_32.cpp @@ -2151,6 +2151,7 @@ class StubGenerator: public StubCodeGenerator { // These entry points require SharedInfo::stack0 to be set up in non-core builds // and need to be relocatable, so they each fabricate a RuntimeStub internally. StubRoutines::_throw_AbstractMethodError_entry = generate_throw_exception("AbstractMethodError throw_exception", CAST_FROM_FN_PTR(address, SharedRuntime::throw_AbstractMethodError), false); + StubRoutines::_throw_IncompatibleClassChangeError_entry= generate_throw_exception("IncompatibleClassChangeError throw_exception", CAST_FROM_FN_PTR(address, SharedRuntime::throw_IncompatibleClassChangeError), false); StubRoutines::_throw_ArithmeticException_entry = generate_throw_exception("ArithmeticException throw_exception", CAST_FROM_FN_PTR(address, SharedRuntime::throw_ArithmeticException), true); StubRoutines::_throw_NullPointerException_entry = generate_throw_exception("NullPointerException throw_exception", CAST_FROM_FN_PTR(address, SharedRuntime::throw_NullPointerException), true); StubRoutines::_throw_NullPointerException_at_call_entry= generate_throw_exception("NullPointerException at call throw_exception", CAST_FROM_FN_PTR(address, SharedRuntime::throw_NullPointerException_at_call), false); diff --git a/hotspot/src/cpu/x86/vm/stubGenerator_x86_64.cpp b/hotspot/src/cpu/x86/vm/stubGenerator_x86_64.cpp index 738beafa314..720222b31e9 100644 --- a/hotspot/src/cpu/x86/vm/stubGenerator_x86_64.cpp +++ b/hotspot/src/cpu/x86/vm/stubGenerator_x86_64.cpp @@ -2832,6 +2832,13 @@ class StubGenerator: public StubCodeGenerator { throw_AbstractMethodError), false); + StubRoutines::_throw_IncompatibleClassChangeError_entry = + generate_throw_exception("IncompatibleClassChangeError throw_exception", + CAST_FROM_FN_PTR(address, + SharedRuntime:: + throw_IncompatibleClassChangeError), + false); + StubRoutines::_throw_ArithmeticException_entry = generate_throw_exception("ArithmeticException throw_exception", CAST_FROM_FN_PTR(address, diff --git a/hotspot/src/cpu/x86/vm/vtableStubs_x86_32.cpp b/hotspot/src/cpu/x86/vm/vtableStubs_x86_32.cpp index fcf84f7b494..09d37901e61 100644 --- a/hotspot/src/cpu/x86/vm/vtableStubs_x86_32.cpp +++ b/hotspot/src/cpu/x86/vm/vtableStubs_x86_32.cpp @@ -138,29 +138,21 @@ VtableStub* VtableStubs::create_itable_stub(int vtable_index) { __ round_to(rbx, BytesPerLong); } - Label hit, next, entry; + Label hit, next, entry, throw_icce; - __ jmp(entry); + __ jmpb(entry); __ bind(next); __ addl(rbx, itableOffsetEntry::size() * wordSize); __ bind(entry); -#ifdef ASSERT - // Check that the entry is non-null - if (DebugVtables) { - Label L; - __ pushl(rbx); - __ movl(rbx, Address(rbx, itableOffsetEntry::interface_offset_in_bytes())); - __ testl(rbx, rbx); - __ jcc(Assembler::notZero, L); - __ stop("null entry point found in itable's offset table"); - __ bind(L); - __ popl(rbx); - } -#endif - __ cmpl(rax, Address(rbx, itableOffsetEntry::interface_offset_in_bytes())); + // If the entry is NULL then we've reached the end of the table + // without finding the expected interface, so throw an exception + __ movl(rdx, Address(rbx, itableOffsetEntry::interface_offset_in_bytes())); + __ testl(rdx, rdx); + __ jcc(Assembler::zero, throw_icce); + __ cmpl(rax, rdx); __ jcc(Assembler::notEqual, next); // We found a hit, move offset into rbx, @@ -194,7 +186,15 @@ VtableStub* VtableStubs::create_itable_stub(int vtable_index) { address ame_addr = __ pc(); __ jmp(Address(method, methodOopDesc::from_compiled_offset())); + __ bind(throw_icce); + // Restore saved register + __ popl(rdx); + __ jump(RuntimeAddress(StubRoutines::throw_IncompatibleClassChangeError_entry())); + masm->flush(); + + guarantee(__ pc() <= s->code_end(), "overflowed buffer"); + s->set_exception_points(npe_addr, ame_addr); return s; } @@ -207,7 +207,7 @@ int VtableStub::pd_code_size_limit(bool is_vtable_stub) { return (DebugVtables ? 210 : 16) + (CountCompiledCalls ? 6 : 0); } else { // Itable stub size - return (DebugVtables ? 140 : 55) + (CountCompiledCalls ? 6 : 0); + return (DebugVtables ? 144 : 64) + (CountCompiledCalls ? 6 : 0); } } diff --git a/hotspot/src/cpu/x86/vm/vtableStubs_x86_64.cpp b/hotspot/src/cpu/x86/vm/vtableStubs_x86_64.cpp index fb6e87bb796..c68f7f363e9 100644 --- a/hotspot/src/cpu/x86/vm/vtableStubs_x86_64.cpp +++ b/hotspot/src/cpu/x86/vm/vtableStubs_x86_64.cpp @@ -153,7 +153,7 @@ VtableStub* VtableStubs::create_itable_stub(int vtable_index) { // Round up to align_object_offset boundary __ round_to_q(rbx, BytesPerLong); } - Label hit, next, entry; + Label hit, next, entry, throw_icce; __ jmpb(entry); @@ -162,22 +162,13 @@ VtableStub* VtableStubs::create_itable_stub(int vtable_index) { __ bind(entry); -#ifdef ASSERT - // Check that the entry is non-null - if (DebugVtables) { - Label L; - __ pushq(rbx); - __ movq(rbx, Address(rbx, itableOffsetEntry::interface_offset_in_bytes())); - __ testq(rbx, rbx); - __ jcc(Assembler::notZero, L); - __ stop("null entry point found in itable's offset table"); - __ bind(L); - __ popq(rbx); - } -#endif - - __ cmpq(rax, Address(rbx, itableOffsetEntry::interface_offset_in_bytes())); - __ jcc(Assembler::notEqual, next); + // If the entry is NULL then we've reached the end of the table + // without finding the expected interface, so throw an exception + __ movq(j_rarg1, Address(rbx, itableOffsetEntry::interface_offset_in_bytes())); + __ testq(j_rarg1, j_rarg1); + __ jcc(Assembler::zero, throw_icce); + __ cmpq(rax, j_rarg1); + __ jccb(Assembler::notEqual, next); // We found a hit, move offset into j_rarg1 __ movl(j_rarg1, Address(rbx, itableOffsetEntry::offset_offset_in_bytes())); @@ -203,23 +194,31 @@ VtableStub* VtableStubs::create_itable_stub(int vtable_index) { #ifdef ASSERT - if (DebugVtables) { - Label L2; - __ cmpq(method, (int)NULL); - __ jcc(Assembler::equal, L2); - __ cmpq(Address(method, methodOopDesc::from_compiled_offset()), (int)NULL_WORD); - __ jcc(Assembler::notZero, L2); - __ stop("compiler entrypoint is null"); - __ bind(L2); - } + if (DebugVtables) { + Label L2; + __ cmpq(method, (int)NULL); + __ jcc(Assembler::equal, L2); + __ cmpq(Address(method, methodOopDesc::from_compiled_offset()), (int)NULL_WORD); + __ jcc(Assembler::notZero, L2); + __ stop("compiler entrypoint is null"); + __ bind(L2); + } #endif // ASSERT - // rbx: methodOop - // j_rarg0: receiver - address ame_addr = __ pc(); - __ jmp(Address(method, methodOopDesc::from_compiled_offset())); + // rbx: methodOop + // j_rarg0: receiver + address ame_addr = __ pc(); + __ jmp(Address(method, methodOopDesc::from_compiled_offset())); + + __ bind(throw_icce); + // Restore saved register + __ popq(j_rarg1); + __ jump(RuntimeAddress(StubRoutines::throw_IncompatibleClassChangeError_entry())); __ flush(); + + guarantee(__ pc() <= s->code_end(), "overflowed buffer"); + s->set_exception_points(npe_addr, ame_addr); return s; } @@ -230,7 +229,7 @@ int VtableStub::pd_code_size_limit(bool is_vtable_stub) { return (DebugVtables ? 512 : 24) + (CountCompiledCalls ? 13 : 0); } else { // Itable stub size - return (DebugVtables ? 636 : 64) + (CountCompiledCalls ? 13 : 0); + return (DebugVtables ? 636 : 72) + (CountCompiledCalls ? 13 : 0); } } diff --git a/hotspot/src/share/vm/oops/klassVtable.cpp b/hotspot/src/share/vm/oops/klassVtable.cpp index 1b105cd2d87..84ce0c58a62 100644 --- a/hotspot/src/share/vm/oops/klassVtable.cpp +++ b/hotspot/src/share/vm/oops/klassVtable.cpp @@ -735,7 +735,7 @@ klassItable::klassItable(instanceKlassHandle klass) { } } - // This lenght of the itable was either zero, or it has not yet been initialized. + // The length of the itable was either zero, or it has not yet been initialized. _table_offset = 0; _size_offset_table = 0; _size_method_table = 0; @@ -870,16 +870,19 @@ static int initialize_count = 0; // Initialization void klassItable::initialize_itable(bool checkconstraints, TRAPS) { - // Cannot be setup doing bootstrapping - if (Universe::is_bootstrapping()) return; + // Cannot be setup doing bootstrapping, interfaces don't have + // itables, and klass with only ones entry have empty itables + if (Universe::is_bootstrapping() || + _klass->is_interface() || + _klass->itable_length() == itableOffsetEntry::size()) return; - int num_interfaces = nof_interfaces(); + // There's alway an extra itable entry so we can null-terminate it. + guarantee(size_offset_table() >= 1, "too small"); + int num_interfaces = size_offset_table() - 1; if (num_interfaces > 0) { - if (TraceItables) tty->print_cr("%3d: Initializing itables for %s", ++initialize_count, _klass->name()->as_C_string()); + if (TraceItables) tty->print_cr("%3d: Initializing itables for %s", ++initialize_count, + _klass->name()->as_C_string()); - // In debug mode, we got an extra NULL/NULL entry - debug_only(num_interfaces--); - assert(num_interfaces > 0, "to few interfaces in offset itable"); // Interate through all interfaces int i; @@ -890,12 +893,10 @@ void klassItable::initialize_itable(bool checkconstraints, TRAPS) { initialize_itable_for_interface(ioe->offset(), interf_h, checkconstraints, CHECK); } -#ifdef ASSERT - // Check that the last entry is empty - itableOffsetEntry* ioe = offset_entry(i); - assert(ioe->interface_klass() == NULL && ioe->offset() == 0, "terminator entry missing"); -#endif } + // Check that the last entry is empty + itableOffsetEntry* ioe = offset_entry(size_offset_table() - 1); + guarantee(ioe->interface_klass() == NULL && ioe->offset() == 0, "terminator entry missing"); } @@ -972,7 +973,7 @@ void klassItable::initialize_itable_for_interface(int method_table_offset, Klass } } -// Update entry for specic methodOop +// Update entry for specific methodOop void klassItable::initialize_with_method(methodOop m) { itableMethodEntry* ime = method_entry(0); for(int i = 0; i < _size_method_table; i++) { @@ -1085,12 +1086,8 @@ int klassItable::compute_itable_size(objArrayHandle transitive_interfaces) { CountInterfacesClosure cic; visit_all_interfaces(transitive_interfaces(), &cic); - // Add one extra entry in debug mode, so we can null-terminate the table - int nof_methods = cic.nof_methods(); - int nof_interfaces = cic.nof_interfaces(); - debug_only(if (nof_interfaces > 0) nof_interfaces++); - - int itable_size = calc_itable_size(nof_interfaces, nof_methods); + // There's alway an extra itable entry so we can null-terminate it. + int itable_size = calc_itable_size(cic.nof_interfaces() + 1, cic.nof_methods()); // Statistics update_stats(itable_size * HeapWordSize); @@ -1110,8 +1107,8 @@ void klassItable::setup_itable_offset_table(instanceKlassHandle klass) { int nof_methods = cic.nof_methods(); int nof_interfaces = cic.nof_interfaces(); - // Add one extra entry in debug mode, so we can null-terminate the table - debug_only(if (nof_interfaces > 0) nof_interfaces++); + // Add one extra entry so we can null-terminate the table + nof_interfaces++; assert(compute_itable_size(objArrayHandle(klass->transitive_interfaces())) == calc_itable_size(nof_interfaces, nof_methods), diff --git a/hotspot/src/share/vm/oops/klassVtable.hpp b/hotspot/src/share/vm/oops/klassVtable.hpp index 221e1d21d66..2ef1848f59e 100644 --- a/hotspot/src/share/vm/oops/klassVtable.hpp +++ b/hotspot/src/share/vm/oops/klassVtable.hpp @@ -259,7 +259,7 @@ class klassItable : public ResourceObj { itableMethodEntry* method_entry(int i) { assert(0 <= i && i <= _size_method_table, "index out of bounds"); return &((itableMethodEntry*)method_start())[i]; } - int nof_interfaces() { return _size_offset_table; } + int size_offset_table() { return _size_offset_table; } // Initialization void initialize_itable(bool checkconstraints, TRAPS); diff --git a/hotspot/src/share/vm/runtime/sharedRuntime.cpp b/hotspot/src/share/vm/runtime/sharedRuntime.cpp index e9a5685889d..cda256b74a3 100644 --- a/hotspot/src/share/vm/runtime/sharedRuntime.cpp +++ b/hotspot/src/share/vm/runtime/sharedRuntime.cpp @@ -467,6 +467,11 @@ JRT_ENTRY(void, SharedRuntime::throw_AbstractMethodError(JavaThread* thread)) throw_and_post_jvmti_exception(thread, vmSymbols::java_lang_AbstractMethodError()); JRT_END +JRT_ENTRY(void, SharedRuntime::throw_IncompatibleClassChangeError(JavaThread* thread)) + // These errors occur only at call sites + throw_and_post_jvmti_exception(thread, vmSymbols::java_lang_IncompatibleClassChangeError(), "vtable stub"); +JRT_END + JRT_ENTRY(void, SharedRuntime::throw_ArithmeticException(JavaThread* thread)) throw_and_post_jvmti_exception(thread, vmSymbols::java_lang_ArithmeticException(), "/ by zero"); JRT_END diff --git a/hotspot/src/share/vm/runtime/sharedRuntime.hpp b/hotspot/src/share/vm/runtime/sharedRuntime.hpp index b91837f36e4..b2138d0a703 100644 --- a/hotspot/src/share/vm/runtime/sharedRuntime.hpp +++ b/hotspot/src/share/vm/runtime/sharedRuntime.hpp @@ -104,6 +104,7 @@ class SharedRuntime: AllStatic { STACK_OVERFLOW }; static void throw_AbstractMethodError(JavaThread* thread); + static void throw_IncompatibleClassChangeError(JavaThread* thread); static void throw_ArithmeticException(JavaThread* thread); static void throw_NullPointerException(JavaThread* thread); static void throw_NullPointerException_at_call(JavaThread* thread); diff --git a/hotspot/src/share/vm/runtime/stubRoutines.cpp b/hotspot/src/share/vm/runtime/stubRoutines.cpp index 63b30d86d7d..bdad678b0cb 100644 --- a/hotspot/src/share/vm/runtime/stubRoutines.cpp +++ b/hotspot/src/share/vm/runtime/stubRoutines.cpp @@ -40,6 +40,7 @@ address StubRoutines::_call_stub_entry = NULL; address StubRoutines::_catch_exception_entry = NULL; address StubRoutines::_forward_exception_entry = NULL; address StubRoutines::_throw_AbstractMethodError_entry = NULL; +address StubRoutines::_throw_IncompatibleClassChangeError_entry = NULL; address StubRoutines::_throw_ArithmeticException_entry = NULL; address StubRoutines::_throw_NullPointerException_entry = NULL; address StubRoutines::_throw_NullPointerException_at_call_entry = NULL; diff --git a/hotspot/src/share/vm/runtime/stubRoutines.hpp b/hotspot/src/share/vm/runtime/stubRoutines.hpp index 17246a8bcaa..67741916488 100644 --- a/hotspot/src/share/vm/runtime/stubRoutines.hpp +++ b/hotspot/src/share/vm/runtime/stubRoutines.hpp @@ -84,6 +84,7 @@ class StubRoutines: AllStatic { static address _forward_exception_entry; static address _catch_exception_entry; static address _throw_AbstractMethodError_entry; + static address _throw_IncompatibleClassChangeError_entry; static address _throw_ArithmeticException_entry; static address _throw_NullPointerException_entry; static address _throw_NullPointerException_at_call_entry; @@ -184,6 +185,7 @@ class StubRoutines: AllStatic { static address forward_exception_entry() { return _forward_exception_entry; } // Implicit exceptions static address throw_AbstractMethodError_entry() { return _throw_AbstractMethodError_entry; } + static address throw_IncompatibleClassChangeError_entry(){ return _throw_IncompatibleClassChangeError_entry; } static address throw_ArithmeticException_entry() { return _throw_ArithmeticException_entry; } static address throw_NullPointerException_entry() { return _throw_NullPointerException_entry; } static address throw_NullPointerException_at_call_entry(){ return _throw_NullPointerException_at_call_entry; } From 10c473e425fc6f4b4348488984b1013bc955224e Mon Sep 17 00:00:00 2001 From: Tom Rodriguez Date: Wed, 5 Dec 2007 09:01:00 -0800 Subject: [PATCH 002/258] 6395208: Elide autoboxing for calls to HashMap.get(int) and HashMap.get(long) Reviewed-by: kvn, rasbold --- hotspot/src/share/vm/ci/ciObjArray.cpp | 43 ++++ hotspot/src/share/vm/ci/ciObjArray.hpp | 2 + hotspot/src/share/vm/classfile/vmSymbols.hpp | 6 + hotspot/src/share/vm/includeDB_core | 15 +- hotspot/src/share/vm/opto/addnode.cpp | 22 ++ hotspot/src/share/vm/opto/addnode.hpp | 5 + hotspot/src/share/vm/opto/c2_globals.hpp | 6 + hotspot/src/share/vm/opto/cfgnode.hpp | 6 + hotspot/src/share/vm/opto/ifnode.cpp | 158 +++++++++++++ hotspot/src/share/vm/opto/loopnode.cpp | 55 +---- hotspot/src/share/vm/opto/loopnode.hpp | 1 - hotspot/src/share/vm/opto/memnode.cpp | 224 +++++++++++++++++++ hotspot/src/share/vm/opto/memnode.hpp | 3 + hotspot/src/share/vm/opto/parse2.cpp | 43 +++- hotspot/src/share/vm/opto/type.hpp | 2 + hotspot/src/share/vm/runtime/arguments.cpp | 16 ++ 16 files changed, 540 insertions(+), 67 deletions(-) create mode 100644 hotspot/src/share/vm/ci/ciObjArray.cpp diff --git a/hotspot/src/share/vm/ci/ciObjArray.cpp b/hotspot/src/share/vm/ci/ciObjArray.cpp new file mode 100644 index 00000000000..fe47238625c --- /dev/null +++ b/hotspot/src/share/vm/ci/ciObjArray.cpp @@ -0,0 +1,43 @@ +/* + * Copyright 1999-2007 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + * + */ + +#include "incls/_precompiled.incl" +#include "incls/_ciObjArray.cpp.incl" + +// ciObjArray +// +// This class represents an objArrayOop in the HotSpot virtual +// machine. + +ciObject* ciObjArray::obj_at(int index) { + VM_ENTRY_MARK; + objArrayOop array = get_objArrayOop(); + if (index < 0 || index >= array->length()) return NULL; + oop o = array->obj_at(index); + if (o == NULL) { + return ciNullObject::make(); + } else { + return CURRENT_ENV->get_object(o); + } +} diff --git a/hotspot/src/share/vm/ci/ciObjArray.hpp b/hotspot/src/share/vm/ci/ciObjArray.hpp index c43700fac23..602ff55e4de 100644 --- a/hotspot/src/share/vm/ci/ciObjArray.hpp +++ b/hotspot/src/share/vm/ci/ciObjArray.hpp @@ -43,4 +43,6 @@ protected: public: // What kind of ciObject is this? bool is_obj_array() { return true; } + + ciObject* obj_at(int index); }; diff --git a/hotspot/src/share/vm/classfile/vmSymbols.hpp b/hotspot/src/share/vm/classfile/vmSymbols.hpp index e0119432ddc..9ba9b0c7c10 100644 --- a/hotspot/src/share/vm/classfile/vmSymbols.hpp +++ b/hotspot/src/share/vm/classfile/vmSymbols.hpp @@ -58,12 +58,17 @@ template(java_lang_ThreadDeath, "java/lang/ThreadDeath") \ template(java_lang_Boolean, "java/lang/Boolean") \ template(java_lang_Character, "java/lang/Character") \ + template(java_lang_Character_CharacterCache, "java/lang/Character$CharacterCache") \ template(java_lang_Float, "java/lang/Float") \ template(java_lang_Double, "java/lang/Double") \ template(java_lang_Byte, "java/lang/Byte") \ + template(java_lang_Byte_Cache, "java/lang/Byte$ByteCache") \ template(java_lang_Short, "java/lang/Short") \ + template(java_lang_Short_ShortCache, "java/lang/Short$ShortCache") \ template(java_lang_Integer, "java/lang/Integer") \ + template(java_lang_Integer_IntegerCache, "java/lang/Integer$IntegerCache") \ template(java_lang_Long, "java/lang/Long") \ + template(java_lang_Long_LongCache, "java/lang/Long$LongCache") \ template(java_lang_Shutdown, "java/lang/Shutdown") \ template(java_lang_ref_Reference, "java/lang/ref/Reference") \ template(java_lang_ref_SoftReference, "java/lang/ref/SoftReference") \ @@ -274,6 +279,7 @@ template(exclusive_owner_thread_name, "exclusiveOwnerThread") \ template(park_blocker_name, "parkBlocker") \ template(park_event_name, "nativeParkEventPointer") \ + template(cache_field_name, "cache") \ template(value_name, "value") \ \ /* non-intrinsic name/signature pairs: */ \ diff --git a/hotspot/src/share/vm/includeDB_core b/hotspot/src/share/vm/includeDB_core index cbf8e561a73..aa7e7196523 100644 --- a/hotspot/src/share/vm/includeDB_core +++ b/hotspot/src/share/vm/includeDB_core @@ -19,7 +19,7 @@ // Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, // CA 95054 USA or visit www.sun.com if you need additional information or // have any questions. -// +// // // NOTE: DO NOT CHANGE THIS COPYRIGHT TO NEW STYLE - IT WILL BREAK makeDeps! @@ -46,13 +46,13 @@ // as dependencies. Header files named H.inline.hpp generally contain // bodies for inline functions declared in H.hpp. // -// NOTE: Files that use the token "generate_platform_dependent_include" +// NOTE: Files that use the token "generate_platform_dependent_include" // are expected to contain macro references like , , ... and // makedeps has a dependency on these platform files looking like: -// foo_.trailing_string +// foo_.trailing_string // (where "trailing_string" can be any legal filename strings but typically // is "hpp" or "inline.hpp"). -// +// // The dependency in makedeps (and enforced) is that an underscore // will precedure the macro invocation. Note that this restriction // is only enforced on filenames that have the dependency token @@ -720,6 +720,11 @@ ciObjArray.hpp ciArray.hpp ciObjArray.hpp ciClassList.hpp ciObjArray.hpp objArrayOop.hpp +ciObjArray.cpp ciObjArray.hpp +ciObjArray.cpp ciNullObject.hpp +ciObjArray.cpp ciUtilities.hpp +ciObjArray.cpp objArrayOop.hpp + ciObjArrayKlass.cpp ciInstanceKlass.hpp ciObjArrayKlass.cpp ciObjArrayKlass.hpp ciObjArrayKlass.cpp ciObjArrayKlassKlass.hpp @@ -1935,7 +1940,7 @@ icache_.hpp generate_platform_dependent_include init.cpp bytecodes.hpp init.cpp collectedHeap.hpp -init.cpp handles.inline.hpp +init.cpp handles.inline.hpp init.cpp icBuffer.hpp init.cpp icache.hpp init.cpp init.hpp diff --git a/hotspot/src/share/vm/opto/addnode.cpp b/hotspot/src/share/vm/opto/addnode.cpp index 42a17c997dc..7b29f422911 100644 --- a/hotspot/src/share/vm/opto/addnode.cpp +++ b/hotspot/src/share/vm/opto/addnode.cpp @@ -608,6 +608,28 @@ Node* AddPNode::Ideal_base_and_offset(Node* ptr, PhaseTransform* phase, return NULL; } +//------------------------------unpack_offsets---------------------------------- +// Collect the AddP offset values into the elements array, giving up +// if there are more than length. +int AddPNode::unpack_offsets(Node* elements[], int length) { + int count = 0; + Node* addr = this; + Node* base = addr->in(AddPNode::Base); + while (addr->is_AddP()) { + if (addr->in(AddPNode::Base) != base) { + // give up + return -1; + } + elements[count++] = addr->in(AddPNode::Offset); + if (count == length) { + // give up + return -1; + } + addr = addr->in(AddPNode::Address); + } + return count; +} + //------------------------------match_edge------------------------------------- // Do we Match on this edge index or not? Do not match base pointer edge uint AddPNode::match_edge(uint idx) const { diff --git a/hotspot/src/share/vm/opto/addnode.hpp b/hotspot/src/share/vm/opto/addnode.hpp index 5170f50e17d..acd210c9333 100644 --- a/hotspot/src/share/vm/opto/addnode.hpp +++ b/hotspot/src/share/vm/opto/addnode.hpp @@ -144,6 +144,11 @@ public: static Node* Ideal_base_and_offset(Node* ptr, PhaseTransform* phase, // second return value: intptr_t& offset); + + // Collect the AddP offset values into the elements array, giving up + // if there are more than length. + int unpack_offsets(Node* elements[], int length); + // Do not match base-ptr edge virtual uint match_edge(uint idx) const; static const Type *mach_bottom_type(const MachNode* n); // used by ad_.hpp diff --git a/hotspot/src/share/vm/opto/c2_globals.hpp b/hotspot/src/share/vm/opto/c2_globals.hpp index 360300255d7..4cfbcca2c98 100644 --- a/hotspot/src/share/vm/opto/c2_globals.hpp +++ b/hotspot/src/share/vm/opto/c2_globals.hpp @@ -367,6 +367,12 @@ notproduct(bool, PrintEliminateLocks, false, \ "Print out when locks are eliminated") \ \ + diagnostic(bool, EliminateAutoBox, false, \ + "Private flag to control optimizations for autobox elimination") \ + \ + product(intx, AutoBoxCacheMax, 128, \ + "Sets max value cached by the java.lang.Integer autobox cache") \ + \ product(bool, DoEscapeAnalysis, false, \ "Perform escape analysis") \ \ diff --git a/hotspot/src/share/vm/opto/cfgnode.hpp b/hotspot/src/share/vm/opto/cfgnode.hpp index e01e25258ec..b198a5bf7ab 100644 --- a/hotspot/src/share/vm/opto/cfgnode.hpp +++ b/hotspot/src/share/vm/opto/cfgnode.hpp @@ -310,8 +310,14 @@ public: virtual const RegMask &out_RegMask() const; void dominated_by(Node* prev_dom, PhaseIterGVN* igvn); int is_range_check(Node* &range, Node* &index, jint &offset); + Node* fold_compares(PhaseGVN* phase); static Node* up_one_dom(Node* curr, bool linear_only = false); + // Takes the type of val and filters it through the test represented + // by if_proj and returns a more refined type if one is produced. + // Returns NULL is it couldn't improve the type. + static const TypeInt* filtered_int_type(PhaseGVN* phase, Node* val, Node* if_proj); + #ifndef PRODUCT virtual void dump_spec(outputStream *st) const; #endif diff --git a/hotspot/src/share/vm/opto/ifnode.cpp b/hotspot/src/share/vm/opto/ifnode.cpp index 48031ef3d5a..073d4202f68 100644 --- a/hotspot/src/share/vm/opto/ifnode.cpp +++ b/hotspot/src/share/vm/opto/ifnode.cpp @@ -543,6 +543,159 @@ Node* IfNode::up_one_dom(Node *curr, bool linear_only) { return NULL; // Dead loop? Or hit root? } + +//------------------------------filtered_int_type-------------------------------- +// Return a possibly more restrictive type for val based on condition control flow for an if +const TypeInt* IfNode::filtered_int_type(PhaseGVN* gvn, Node *val, Node* if_proj) { + assert(if_proj && + (if_proj->Opcode() == Op_IfTrue || if_proj->Opcode() == Op_IfFalse), "expecting an if projection"); + if (if_proj->in(0) && if_proj->in(0)->is_If()) { + IfNode* iff = if_proj->in(0)->as_If(); + if (iff->in(1) && iff->in(1)->is_Bool()) { + BoolNode* bol = iff->in(1)->as_Bool(); + if (bol->in(1) && bol->in(1)->is_Cmp()) { + const CmpNode* cmp = bol->in(1)->as_Cmp(); + if (cmp->in(1) == val) { + const TypeInt* cmp2_t = gvn->type(cmp->in(2))->isa_int(); + if (cmp2_t != NULL) { + jint lo = cmp2_t->_lo; + jint hi = cmp2_t->_hi; + BoolTest::mask msk = if_proj->Opcode() == Op_IfTrue ? bol->_test._test : bol->_test.negate(); + switch (msk) { + case BoolTest::ne: + // Can't refine type + return NULL; + case BoolTest::eq: + return cmp2_t; + case BoolTest::lt: + lo = TypeInt::INT->_lo; + if (hi - 1 < hi) { + hi = hi - 1; + } + break; + case BoolTest::le: + lo = TypeInt::INT->_lo; + break; + case BoolTest::gt: + if (lo + 1 > lo) { + lo = lo + 1; + } + hi = TypeInt::INT->_hi; + break; + case BoolTest::ge: + // lo unchanged + hi = TypeInt::INT->_hi; + break; + } + const TypeInt* rtn_t = TypeInt::make(lo, hi, cmp2_t->_widen); + return rtn_t; + } + } + } + } + } + return NULL; +} + +//------------------------------fold_compares---------------------------- +// See if a pair of CmpIs can be converted into a CmpU. In some cases +// the direction of this if is determined by the preciding if so it +// can be eliminate entirely. Given an if testing (CmpI n c) check +// for an immediately control dependent if that is testing (CmpI n c2) +// and has one projection leading to this if and the other projection +// leading to a region that merges one of this ifs control +// projections. +// +// If +// / | +// / | +// / | +// If | +// /\ | +// / \ | +// / \ | +// / Region +// +Node* IfNode::fold_compares(PhaseGVN* phase) { + if (!EliminateAutoBox || Opcode() != Op_If) return NULL; + + Node* this_cmp = in(1)->in(1); + if (this_cmp != NULL && this_cmp->Opcode() == Op_CmpI && + this_cmp->in(2)->is_Con() && this_cmp->in(2) != phase->C->top()) { + Node* ctrl = in(0); + BoolNode* this_bool = in(1)->as_Bool(); + Node* n = this_cmp->in(1); + int hi = this_cmp->in(2)->get_int(); + if (ctrl != NULL && ctrl->is_Proj() && ctrl->outcnt() == 1 && + ctrl->in(0)->is_If() && + ctrl->in(0)->outcnt() == 2 && + ctrl->in(0)->in(1)->is_Bool() && + ctrl->in(0)->in(1)->in(1)->Opcode() == Op_CmpI && + ctrl->in(0)->in(1)->in(1)->in(2)->is_Con() && + ctrl->in(0)->in(1)->in(1)->in(1) == n) { + IfNode* dom_iff = ctrl->in(0)->as_If(); + Node* otherproj = dom_iff->proj_out(!ctrl->as_Proj()->_con); + if (otherproj->outcnt() == 1 && otherproj->unique_out()->is_Region() && + this_bool->_test._test != BoolTest::ne && this_bool->_test._test != BoolTest::eq) { + // Identify which proj goes to the region and which continues on + RegionNode* region = otherproj->unique_out()->as_Region(); + Node* success = NULL; + Node* fail = NULL; + for (int i = 0; i < 2; i++) { + Node* proj = proj_out(i); + if (success == NULL && proj->outcnt() == 1 && proj->unique_out() == region) { + success = proj; + } else if (fail == NULL) { + fail = proj; + } else { + success = fail = NULL; + } + } + if (success != NULL && fail != NULL && !region->has_phi()) { + int lo = dom_iff->in(1)->in(1)->in(2)->get_int(); + BoolNode* dom_bool = dom_iff->in(1)->as_Bool(); + Node* dom_cmp = dom_bool->in(1); + const TypeInt* failtype = filtered_int_type(phase, n, ctrl); + if (failtype != NULL) { + const TypeInt* type2 = filtered_int_type(phase, n, fail); + if (type2 != NULL) { + failtype = failtype->join(type2)->is_int(); + } else { + failtype = NULL; + } + } + + if (failtype != NULL && + dom_bool->_test._test != BoolTest::ne && dom_bool->_test._test != BoolTest::eq) { + int bound = failtype->_hi - failtype->_lo + 1; + if (failtype->_hi != max_jint && failtype->_lo != min_jint && bound > 1) { + // Merge the two compares into a single unsigned compare by building (CmpU (n - lo) hi) + BoolTest::mask cond = fail->as_Proj()->_con ? BoolTest::lt : BoolTest::ge; + Node* adjusted = phase->transform(new (phase->C, 3) SubINode(n, phase->intcon(failtype->_lo))); + Node* newcmp = phase->transform(new (phase->C, 3) CmpUNode(adjusted, phase->intcon(bound))); + Node* newbool = phase->transform(new (phase->C, 2) BoolNode(newcmp, cond)); + phase->hash_delete(dom_iff); + dom_iff->set_req(1, phase->intcon(ctrl->as_Proj()->_con)); + phase->is_IterGVN()->_worklist.push(dom_iff); + phase->hash_delete(this); + set_req(1, newbool); + return this; + } + if (failtype->_lo > failtype->_hi) { + // previous if determines the result of this if so + // replace Bool with constant + phase->hash_delete(this); + set_req(1, phase->intcon(success->as_Proj()->_con)); + return this; + } + } + } + } + } + } + return NULL; +} + //------------------------------remove_useless_bool---------------------------- // Check for people making a useless boolean: things like // if( (x < y ? true : false) ) { ... } @@ -744,6 +897,11 @@ Node *IfNode::Ideal(PhaseGVN *phase, bool can_reshape) { // Normal equivalent-test check. if( !dom ) return NULL; // Dead loop? + Node* result = fold_compares(phase); + if (result != NULL) { + return result; + } + // Search up the dominator tree for an If with an identical test while( dom->Opcode() != op || // Not same opcode? dom->in(1) != in(1) || // Not same input 1? diff --git a/hotspot/src/share/vm/opto/loopnode.cpp b/hotspot/src/share/vm/opto/loopnode.cpp index 938862f0fa4..96140fae598 100644 --- a/hotspot/src/share/vm/opto/loopnode.cpp +++ b/hotspot/src/share/vm/opto/loopnode.cpp @@ -651,7 +651,7 @@ const TypeInt* PhaseIdealLoop::filtered_type_from_dominators( Node* val, Node *u while (if_cnt < if_limit) { if ((pred->Opcode() == Op_IfTrue || pred->Opcode() == Op_IfFalse)) { if_cnt++; - const TypeInt* if_t = filtered_type_at_if(val, pred); + const TypeInt* if_t = IfNode::filtered_int_type(&_igvn, val, pred); if (if_t != NULL) { if (rtn_t == NULL) { rtn_t = if_t; @@ -674,59 +674,6 @@ const TypeInt* PhaseIdealLoop::filtered_type_from_dominators( Node* val, Node *u } -//------------------------------filtered_type_at_if-------------------------------- -// Return a possibly more restrictive type for val based on condition control flow for an if -const TypeInt* PhaseIdealLoop::filtered_type_at_if( Node* val, Node *if_proj) { - assert(if_proj && - (if_proj->Opcode() == Op_IfTrue || if_proj->Opcode() == Op_IfFalse), "expecting an if projection"); - if (if_proj->in(0) && if_proj->in(0)->is_If()) { - IfNode* iff = if_proj->in(0)->as_If(); - if (iff->in(1) && iff->in(1)->is_Bool()) { - BoolNode* bol = iff->in(1)->as_Bool(); - if (bol->in(1) && bol->in(1)->is_Cmp()) { - const CmpNode* cmp = bol->in(1)->as_Cmp(); - if (cmp->in(1) == val) { - const TypeInt* cmp2_t = _igvn.type(cmp->in(2))->isa_int(); - if (cmp2_t != NULL) { - jint lo = cmp2_t->_lo; - jint hi = cmp2_t->_hi; - BoolTest::mask msk = if_proj->Opcode() == Op_IfTrue ? bol->_test._test : bol->_test.negate(); - switch (msk) { - case BoolTest::ne: - // Can't refine type - return NULL; - case BoolTest::eq: - return cmp2_t; - case BoolTest::lt: - lo = TypeInt::INT->_lo; - if (hi - 1 < hi) { - hi = hi - 1; - } - break; - case BoolTest::le: - lo = TypeInt::INT->_lo; - break; - case BoolTest::gt: - if (lo + 1 > lo) { - lo = lo + 1; - } - hi = TypeInt::INT->_hi; - break; - case BoolTest::ge: - // lo unchanged - hi = TypeInt::INT->_hi; - break; - } - const TypeInt* rtn_t = TypeInt::make(lo, hi, cmp2_t->_widen); - return rtn_t; - } - } - } - } - } - return NULL; -} - //------------------------------dump_spec-------------------------------------- // Dump special per-node info #ifndef PRODUCT diff --git a/hotspot/src/share/vm/opto/loopnode.hpp b/hotspot/src/share/vm/opto/loopnode.hpp index 21ddf801586..60944afeee8 100644 --- a/hotspot/src/share/vm/opto/loopnode.hpp +++ b/hotspot/src/share/vm/opto/loopnode.hpp @@ -850,7 +850,6 @@ private: const TypeInt* filtered_type( Node *n ) { return filtered_type(n, NULL); } // Helpers for filtered type const TypeInt* filtered_type_from_dominators( Node* val, Node *val_ctrl); - const TypeInt* filtered_type_at_if( Node* val, Node *if_proj); // Helper functions void register_new_node( Node *n, Node *blk ); diff --git a/hotspot/src/share/vm/opto/memnode.cpp b/hotspot/src/share/vm/opto/memnode.cpp index 26904be5853..b65a03bbf3b 100644 --- a/hotspot/src/share/vm/opto/memnode.cpp +++ b/hotspot/src/share/vm/opto/memnode.cpp @@ -634,6 +634,46 @@ uint LoadNode::hash() const { Node* MemNode::can_see_stored_value(Node* st, PhaseTransform* phase) const { Node* ld_adr = in(MemNode::Address); + const TypeInstPtr* tp = phase->type(ld_adr)->isa_instptr(); + Compile::AliasType* atp = tp != NULL ? phase->C->alias_type(tp) : NULL; + if (EliminateAutoBox && atp != NULL && atp->index() >= Compile::AliasIdxRaw && + atp->field() != NULL && !atp->field()->is_volatile()) { + uint alias_idx = atp->index(); + bool final = atp->field()->is_final(); + Node* result = NULL; + Node* current = st; + // Skip through chains of MemBarNodes checking the MergeMems for + // new states for the slice of this load. Stop once any other + // kind of node is encountered. Loads from final memory can skip + // through any kind of MemBar but normal loads shouldn't skip + // through MemBarAcquire since the could allow them to move out of + // a synchronized region. + while (current->is_Proj()) { + int opc = current->in(0)->Opcode(); + if ((final && opc == Op_MemBarAcquire) || + opc == Op_MemBarRelease || opc == Op_MemBarCPUOrder) { + Node* mem = current->in(0)->in(TypeFunc::Memory); + if (mem->is_MergeMem()) { + MergeMemNode* merge = mem->as_MergeMem(); + Node* new_st = merge->memory_at(alias_idx); + if (new_st == merge->base_memory()) { + // Keep searching + current = merge->base_memory(); + continue; + } + // Save the new memory state for the slice and fall through + // to exit. + result = new_st; + } + } + break; + } + if (result != NULL) { + st = result; + } + } + + // Loop around twice in the case Load -> Initialize -> Store. // (See PhaseIterGVN::add_users_to_worklist, which knows about this case.) for (int trip = 0; trip <= 1; trip++) { @@ -723,6 +763,168 @@ Node *LoadNode::Identity( PhaseTransform *phase ) { return this; } + +// Returns true if the AliasType refers to the field that holds the +// cached box array. Currently only handles the IntegerCache case. +static bool is_autobox_cache(Compile::AliasType* atp) { + if (atp != NULL && atp->field() != NULL) { + ciField* field = atp->field(); + ciSymbol* klass = field->holder()->name(); + if (field->name() == ciSymbol::cache_field_name() && + field->holder()->uses_default_loader() && + klass == ciSymbol::java_lang_Integer_IntegerCache()) { + return true; + } + } + return false; +} + +// Fetch the base value in the autobox array +static bool fetch_autobox_base(Compile::AliasType* atp, int& cache_offset) { + if (atp != NULL && atp->field() != NULL) { + ciField* field = atp->field(); + ciSymbol* klass = field->holder()->name(); + if (field->name() == ciSymbol::cache_field_name() && + field->holder()->uses_default_loader() && + klass == ciSymbol::java_lang_Integer_IntegerCache()) { + assert(field->is_constant(), "what?"); + ciObjArray* array = field->constant_value().as_object()->as_obj_array(); + // Fetch the box object at the base of the array and get its value + ciInstance* box = array->obj_at(0)->as_instance(); + ciInstanceKlass* ik = box->klass()->as_instance_klass(); + if (ik->nof_nonstatic_fields() == 1) { + // This should be true nonstatic_field_at requires calling + // nof_nonstatic_fields so check it anyway + ciConstant c = box->field_value(ik->nonstatic_field_at(0)); + cache_offset = c.as_int(); + } + return true; + } + } + return false; +} + +// Returns true if the AliasType refers to the value field of an +// autobox object. Currently only handles Integer. +static bool is_autobox_object(Compile::AliasType* atp) { + if (atp != NULL && atp->field() != NULL) { + ciField* field = atp->field(); + ciSymbol* klass = field->holder()->name(); + if (field->name() == ciSymbol::value_name() && + field->holder()->uses_default_loader() && + klass == ciSymbol::java_lang_Integer()) { + return true; + } + } + return false; +} + + +// We're loading from an object which has autobox behaviour. +// If this object is result of a valueOf call we'll have a phi +// merging a newly allocated object and a load from the cache. +// We want to replace this load with the original incoming +// argument to the valueOf call. +Node* LoadNode::eliminate_autobox(PhaseGVN* phase) { + Node* base = in(Address)->in(AddPNode::Base); + if (base->is_Phi() && base->req() == 3) { + AllocateNode* allocation = NULL; + int allocation_index = -1; + int load_index = -1; + for (uint i = 1; i < base->req(); i++) { + allocation = AllocateNode::Ideal_allocation(base->in(i), phase); + if (allocation != NULL) { + allocation_index = i; + load_index = 3 - allocation_index; + break; + } + } + LoadNode* load = NULL; + if (allocation != NULL && base->in(load_index)->is_Load()) { + load = base->in(load_index)->as_Load(); + } + if (load != NULL && in(Memory)->is_Phi() && in(Memory)->in(0) == base->in(0)) { + // Push the loads from the phi that comes from valueOf up + // through it to allow elimination of the loads and the recovery + // of the original value. + Node* mem_phi = in(Memory); + Node* offset = in(Address)->in(AddPNode::Offset); + + Node* in1 = clone(); + Node* in1_addr = in1->in(Address)->clone(); + in1_addr->set_req(AddPNode::Base, base->in(allocation_index)); + in1_addr->set_req(AddPNode::Address, base->in(allocation_index)); + in1_addr->set_req(AddPNode::Offset, offset); + in1->set_req(0, base->in(allocation_index)); + in1->set_req(Address, in1_addr); + in1->set_req(Memory, mem_phi->in(allocation_index)); + + Node* in2 = clone(); + Node* in2_addr = in2->in(Address)->clone(); + in2_addr->set_req(AddPNode::Base, base->in(load_index)); + in2_addr->set_req(AddPNode::Address, base->in(load_index)); + in2_addr->set_req(AddPNode::Offset, offset); + in2->set_req(0, base->in(load_index)); + in2->set_req(Address, in2_addr); + in2->set_req(Memory, mem_phi->in(load_index)); + + in1_addr = phase->transform(in1_addr); + in1 = phase->transform(in1); + in2_addr = phase->transform(in2_addr); + in2 = phase->transform(in2); + + PhiNode* result = PhiNode::make_blank(base->in(0), this); + result->set_req(allocation_index, in1); + result->set_req(load_index, in2); + return result; + } + } else if (base->is_Load()) { + // Eliminate the load of Integer.value for integers from the cache + // array by deriving the value from the index into the array. + // Capture the offset of the load and then reverse the computation. + Node* load_base = base->in(Address)->in(AddPNode::Base); + if (load_base != NULL) { + Compile::AliasType* atp = phase->C->alias_type(load_base->adr_type()); + intptr_t cache_offset; + int shift = -1; + Node* cache = NULL; + if (is_autobox_cache(atp)) { + shift = exact_log2(type2aelembytes[T_OBJECT]); + cache = AddPNode::Ideal_base_and_offset(load_base->in(Address), phase, cache_offset); + } + if (cache != NULL && base->in(Address)->is_AddP()) { + Node* elements[4]; + int count = base->in(Address)->as_AddP()->unpack_offsets(elements, ARRAY_SIZE(elements)); + int cache_low; + if (count > 0 && fetch_autobox_base(atp, cache_low)) { + int offset = arrayOopDesc::base_offset_in_bytes(memory_type()) - (cache_low << shift); + // Add up all the offsets making of the address of the load + Node* result = elements[0]; + for (int i = 1; i < count; i++) { + result = phase->transform(new (phase->C, 3) AddXNode(result, elements[i])); + } + // Remove the constant offset from the address and then + // remove the scaling of the offset to recover the original index. + result = phase->transform(new (phase->C, 3) AddXNode(result, phase->MakeConX(-offset))); + if (result->Opcode() == Op_LShiftX && result->in(2) == phase->intcon(shift)) { + // Peel the shift off directly but wrap it in a dummy node + // since Ideal can't return existing nodes + result = new (phase->C, 3) RShiftXNode(result->in(1), phase->intcon(0)); + } else { + result = new (phase->C, 3) RShiftXNode(result, phase->intcon(shift)); + } +#ifdef _LP64 + result = new (phase->C, 2) ConvL2INode(phase->transform(result)); +#endif + return result; + } + } + } + } + return NULL; +} + + //------------------------------Ideal------------------------------------------ // If the load is from Field memory and the pointer is non-null, we can // zero out the control input. @@ -755,6 +957,17 @@ Node *LoadNode::Ideal(PhaseGVN *phase, bool can_reshape) { } } + if (EliminateAutoBox && can_reshape && in(Address)->is_AddP()) { + Node* base = in(Address)->in(AddPNode::Base); + if (base != NULL) { + Compile::AliasType* atp = phase->C->alias_type(adr_type()); + if (is_autobox_object(atp)) { + Node* result = eliminate_autobox(phase); + if (result != NULL) return result; + } + } + } + // Check for prior store with a different base or offset; make Load // independent. Skip through any number of them. Bail out if the stores // are in an endless dead cycle and report no progress. This is a key @@ -858,6 +1071,17 @@ const Type *LoadNode::Value( PhaseTransform *phase ) const { // This can happen if a interface-typed array narrows to a class type. jt = _type; } + + if (EliminateAutoBox) { + // The pointers in the autobox arrays are always non-null + Node* base = in(Address)->in(AddPNode::Base); + if (base != NULL) { + Compile::AliasType* atp = phase->C->alias_type(base->adr_type()); + if (is_autobox_cache(atp)) { + return jt->join(TypePtr::NOTNULL)->is_ptr(); + } + } + } return jt; } } diff --git a/hotspot/src/share/vm/opto/memnode.hpp b/hotspot/src/share/vm/opto/memnode.hpp index 989e255a9b2..34f36a27118 100644 --- a/hotspot/src/share/vm/opto/memnode.hpp +++ b/hotspot/src/share/vm/opto/memnode.hpp @@ -141,6 +141,9 @@ public: // zero out the control input. virtual Node *Ideal(PhaseGVN *phase, bool can_reshape); + // Recover original value from boxed values + Node *eliminate_autobox(PhaseGVN *phase); + // Compute a new Type for this node. Basically we just do the pre-check, // then call the virtual add() to set the type. virtual const Type *Value( PhaseTransform *phase ) const; diff --git a/hotspot/src/share/vm/opto/parse2.cpp b/hotspot/src/share/vm/opto/parse2.cpp index 2a5b0da07e8..ae8615d0152 100644 --- a/hotspot/src/share/vm/opto/parse2.cpp +++ b/hotspot/src/share/vm/opto/parse2.cpp @@ -885,6 +885,9 @@ inline void Parse::repush_if_args() { void Parse::do_ifnull(BoolTest::mask btest) { int target_bci = iter().get_dest(); + Block* branch_block = successor_for_bci(target_bci); + Block* next_block = successor_for_bci(iter().next_bci()); + float cnt; float prob = branch_prediction(cnt, btest, target_bci); if (prob == PROB_UNKNOWN) { @@ -902,13 +905,16 @@ void Parse::do_ifnull(BoolTest::mask btest) { uncommon_trap(Deoptimization::Reason_unreached, Deoptimization::Action_reinterpret, NULL, "cold"); + if (EliminateAutoBox) { + // Mark the successor blocks as parsed + branch_block->next_path_num(); + next_block->next_path_num(); + } return; } // If this is a backwards branch in the bytecodes, add Safepoint maybe_add_safepoint(target_bci); - Block* branch_block = successor_for_bci(target_bci); - Block* next_block = successor_for_bci(iter().next_bci()); explicit_null_checks_inserted++; Node* a = null(); @@ -935,6 +941,10 @@ void Parse::do_ifnull(BoolTest::mask btest) { if (stopped()) { // Path is dead? explicit_null_checks_elided++; + if (EliminateAutoBox) { + // Mark the successor block as parsed + branch_block->next_path_num(); + } } else { // Path is live. // Update method data profile_taken_branch(target_bci); @@ -950,6 +960,10 @@ void Parse::do_ifnull(BoolTest::mask btest) { if (stopped()) { // Path is dead? explicit_null_checks_elided++; + if (EliminateAutoBox) { + // Mark the successor block as parsed + next_block->next_path_num(); + } } else { // Path is live. // Update method data profile_not_taken_branch(); @@ -962,6 +976,9 @@ void Parse::do_ifnull(BoolTest::mask btest) { void Parse::do_if(BoolTest::mask btest, Node* c) { int target_bci = iter().get_dest(); + Block* branch_block = successor_for_bci(target_bci); + Block* next_block = successor_for_bci(iter().next_bci()); + float cnt; float prob = branch_prediction(cnt, btest, target_bci); float untaken_prob = 1.0 - prob; @@ -980,6 +997,11 @@ void Parse::do_if(BoolTest::mask btest, Node* c) { uncommon_trap(Deoptimization::Reason_unreached, Deoptimization::Action_reinterpret, NULL, "cold"); + if (EliminateAutoBox) { + // Mark the successor blocks as parsed + branch_block->next_path_num(); + next_block->next_path_num(); + } return; } @@ -1018,15 +1040,17 @@ void Parse::do_if(BoolTest::mask btest, Node* c) { untaken_branch = tmp; } - Block* branch_block = successor_for_bci(target_bci); - Block* next_block = successor_for_bci(iter().next_bci()); - // Branch is taken: { PreserveJVMState pjvms(this); taken_branch = _gvn.transform(taken_branch); set_control(taken_branch); - if (!stopped()) { + if (stopped()) { + if (EliminateAutoBox) { + // Mark the successor block as parsed + branch_block->next_path_num(); + } + } else { // Update method data profile_taken_branch(target_bci); adjust_map_after_if(taken_btest, c, prob, branch_block, next_block); @@ -1039,7 +1063,12 @@ void Parse::do_if(BoolTest::mask btest, Node* c) { set_control(untaken_branch); // Branch not taken. - if (!stopped()) { + if (stopped()) { + if (EliminateAutoBox) { + // Mark the successor block as parsed + next_block->next_path_num(); + } + } else { // Update method data profile_not_taken_branch(); adjust_map_after_if(untaken_btest, c, untaken_prob, diff --git a/hotspot/src/share/vm/opto/type.hpp b/hotspot/src/share/vm/opto/type.hpp index cca1e6404bd..4a697311f61 100644 --- a/hotspot/src/share/vm/opto/type.hpp +++ b/hotspot/src/share/vm/opto/type.hpp @@ -1070,6 +1070,7 @@ inline bool Type::is_floatingpoint() const { #define LShiftXNode LShiftLNode // For object size computation: #define AddXNode AddLNode +#define RShiftXNode RShiftLNode // For card marks and hashcodes #define URShiftXNode URShiftLNode // Opcodes @@ -1108,6 +1109,7 @@ inline bool Type::is_floatingpoint() const { #define LShiftXNode LShiftINode // For object size computation: #define AddXNode AddINode +#define RShiftXNode RShiftINode // For card marks and hashcodes #define URShiftXNode URShiftINode // Opcodes diff --git a/hotspot/src/share/vm/runtime/arguments.cpp b/hotspot/src/share/vm/runtime/arguments.cpp index 5d0329ad046..ae4711132c2 100644 --- a/hotspot/src/share/vm/runtime/arguments.cpp +++ b/hotspot/src/share/vm/runtime/arguments.cpp @@ -1254,6 +1254,22 @@ void Arguments::set_bytecode_flags() { // Aggressive optimization flags -XX:+AggressiveOpts void Arguments::set_aggressive_opts_flags() { +#ifdef COMPILER2 + if (AggressiveOpts || !FLAG_IS_DEFAULT(AutoBoxCacheMax)) { + if (FLAG_IS_DEFAULT(EliminateAutoBox)) { + FLAG_SET_DEFAULT(EliminateAutoBox, true); + } + if (FLAG_IS_DEFAULT(AutoBoxCacheMax)) { + FLAG_SET_DEFAULT(AutoBoxCacheMax, 20000); + } + + // Feed the cache size setting into the JDK + char buffer[1024]; + sprintf(buffer, "java.lang.Integer.IntegerCache.high=%d", AutoBoxCacheMax); + add_property(buffer); + } +#endif + if (AggressiveOpts) { NOT_WINDOWS( // No measured benefit on Windows From 4abbae1fc2bcaf506b450d0acd0bcc4099c59763 Mon Sep 17 00:00:00 2001 From: Paul Hohensee Date: Wed, 5 Dec 2007 09:02:00 -0800 Subject: [PATCH 003/258] 6621621: HashMap front cache should be enabled only with AggressiveOpts Reviewed-by: sbohne, xlu --- hotspot/src/share/vm/classfile/vmSymbols.hpp | 4 +++- hotspot/src/share/vm/runtime/thread.cpp | 19 +++++++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/hotspot/src/share/vm/classfile/vmSymbols.hpp b/hotspot/src/share/vm/classfile/vmSymbols.hpp index 9ba9b0c7c10..75e7f1860d6 100644 --- a/hotspot/src/share/vm/classfile/vmSymbols.hpp +++ b/hotspot/src/share/vm/classfile/vmSymbols.hpp @@ -96,10 +96,11 @@ template(java_util_Vector, "java/util/Vector") \ template(java_util_AbstractList, "java/util/AbstractList") \ template(java_util_Hashtable, "java/util/Hashtable") \ + template(java_util_HashMap, "java/util/HashMap") \ template(java_lang_Compiler, "java/lang/Compiler") \ template(sun_misc_Signal, "sun/misc/Signal") \ template(java_lang_AssertionStatusDirectives, "java/lang/AssertionStatusDirectives") \ - template(sun_jkernel_DownloadManager, "sun/jkernel/DownloadManager") \ + template(sun_jkernel_DownloadManager, "sun/jkernel/DownloadManager") \ template(getBootClassPathEntryForClass_name, "getBootClassPathEntryForClass") \ \ /* class file format tags */ \ @@ -281,6 +282,7 @@ template(park_event_name, "nativeParkEventPointer") \ template(cache_field_name, "cache") \ template(value_name, "value") \ + template(frontCacheEnabled_name, "frontCacheEnabled") \ \ /* non-intrinsic name/signature pairs: */ \ template(register_method_name, "register") \ diff --git a/hotspot/src/share/vm/runtime/thread.cpp b/hotspot/src/share/vm/runtime/thread.cpp index 607772a0242..ee8daea5e5d 100644 --- a/hotspot/src/share/vm/runtime/thread.cpp +++ b/hotspot/src/share/vm/runtime/thread.cpp @@ -2925,6 +2925,25 @@ jint Threads::create_vm(JavaVMInitArgs* args, bool* canTryAgain) { warning("java.lang.String not initialized"); } + if (AggressiveOpts) { + // Forcibly initialize java/util/HashMap and mutate the private + // static final "frontCacheEnabled" field before we start creating instances +#ifdef ASSERT + klassOop tmp_k = SystemDictionary::find(vmSymbolHandles::java_util_HashMap(), Handle(), Handle(), CHECK_0); + assert(tmp_k == NULL, "java/util/HashMap should not be loaded yet"); +#endif + klassOop k_o = SystemDictionary::resolve_or_null(vmSymbolHandles::java_util_HashMap(), Handle(), Handle(), CHECK_0); + KlassHandle k = KlassHandle(THREAD, k_o); + guarantee(k.not_null(), "Must find java/util/HashMap"); + instanceKlassHandle ik = instanceKlassHandle(THREAD, k()); + ik->initialize(CHECK_0); + fieldDescriptor fd; + // Possible we might not find this field; if so, don't break + if (ik->find_local_field(vmSymbols::frontCacheEnabled_name(), vmSymbols::bool_signature(), &fd)) { + k()->bool_field_put(fd.offset(), true); + } + } + // Initialize java_lang.System (needed before creating the thread) if (InitializeJavaLangSystem) { initialize_class(vmSymbolHandles::java_lang_System(), CHECK_0); From b3b837074b789df6229626d953e7d78d48a9a4a4 Mon Sep 17 00:00:00 2001 From: Chuck Rasbold Date: Wed, 5 Dec 2007 09:03:00 -0800 Subject: [PATCH 004/258] 6614036: REGRESSION: Java server x86 VM intermittently crash with SIGSEGV (0xb) Restore destination address in x86 32-bit checkcast_arraycopy stub Reviewed-by: jrose, kvn, never --- hotspot/src/cpu/x86/vm/stubGenerator_x86_32.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/hotspot/src/cpu/x86/vm/stubGenerator_x86_32.cpp b/hotspot/src/cpu/x86/vm/stubGenerator_x86_32.cpp index 5ea4177f90b..9d17fce5ff3 100644 --- a/hotspot/src/cpu/x86/vm/stubGenerator_x86_32.cpp +++ b/hotspot/src/cpu/x86/vm/stubGenerator_x86_32.cpp @@ -1416,8 +1416,8 @@ class StubGenerator: public StubCodeGenerator { // ======== end loop ======== // It was a real error; we must depend on the caller to finish the job. - // Register rdx = -1 * number of *remaining* oops, r14 = *total* oops. - // Emit GC store barriers for the oops we have copied (r14 + rdx), + // Register "count" = -1 * number of *remaining* oops, length_arg = *total* oops. + // Emit GC store barriers for the oops we have copied (length_arg + count), // and report their number to the caller. __ addl(count, length_arg); // transfers = (length - remaining) __ movl(rax, count); // save the value @@ -1430,6 +1430,7 @@ class StubGenerator: public StubCodeGenerator { // Come here on success only. __ BIND(L_do_card_marks); __ movl(count, length_arg); + __ movl(to, to_arg); // reload gen_write_ref_array_post_barrier(to, count); __ xorl(rax, rax); // return 0 on success From 4576d7abf7f4441c37ed9f96497ee8b63c67b422 Mon Sep 17 00:00:00 2001 From: Paul Hohensee Date: Wed, 5 Dec 2007 09:04:00 -0800 Subject: [PATCH 005/258] 6629887: 64-bit windows should not restrict default heap size to 1400m Reviewed-by: jmasa, sbohne, ikrylov, xlu --- hotspot/src/os/linux/vm/os_linux.cpp | 14 ++++++++++++++ hotspot/src/os/windows/vm/os_windows.cpp | 5 +++++ hotspot/src/os_cpu/linux_x86/vm/os_linux_x86.cpp | 15 --------------- 3 files changed, 19 insertions(+), 15 deletions(-) diff --git a/hotspot/src/os/linux/vm/os_linux.cpp b/hotspot/src/os/linux/vm/os_linux.cpp index a327fd91592..6d793d895fb 100644 --- a/hotspot/src/os/linux/vm/os_linux.cpp +++ b/hotspot/src/os/linux/vm/os_linux.cpp @@ -116,6 +116,20 @@ julong os::physical_memory() { return Linux::physical_memory(); } +julong os::allocatable_physical_memory(julong size) { +#ifdef _LP64 + return size; +#else + julong result = MIN2(size, (julong)3800*M); + if (!is_allocatable(result)) { + // See comments under solaris for alignment considerations + julong reasonable_size = (julong)2*G - 2 * os::vm_page_size(); + result = MIN2(size, reasonable_size); + } + return result; +#endif // _LP64 +} + //////////////////////////////////////////////////////////////////////////////// // environment support diff --git a/hotspot/src/os/windows/vm/os_windows.cpp b/hotspot/src/os/windows/vm/os_windows.cpp index 7f229338590..54e802a9d85 100644 --- a/hotspot/src/os/windows/vm/os_windows.cpp +++ b/hotspot/src/os/windows/vm/os_windows.cpp @@ -621,7 +621,12 @@ julong os::physical_memory() { } julong os::allocatable_physical_memory(julong size) { +#ifdef _LP64 + return size; +#else + // Limit to 1400m because of the 2gb address space wall return MIN2(size, (julong)1400*M); +#endif } // VC6 lacks DWORD_PTR diff --git a/hotspot/src/os_cpu/linux_x86/vm/os_linux_x86.cpp b/hotspot/src/os_cpu/linux_x86/vm/os_linux_x86.cpp index 972ee017c40..57631b5cde5 100644 --- a/hotspot/src/os_cpu/linux_x86/vm/os_linux_x86.cpp +++ b/hotspot/src/os_cpu/linux_x86/vm/os_linux_x86.cpp @@ -157,23 +157,8 @@ frame os::current_frame() { } } - // Utility functions -julong os::allocatable_physical_memory(julong size) { -#ifdef AMD64 - return size; -#else - julong result = MIN2(size, (julong)3800*M); - if (!is_allocatable(result)) { - // See comments under solaris for alignment considerations - julong reasonable_size = (julong)2*G - 2 * os::vm_page_size(); - result = MIN2(size, reasonable_size); - } - return result; -#endif // AMD64 -} - // From IA32 System Programming Guide enum { trap_page_fault = 0xE From 1bfa153ebe8db7bf90e2054e9d00d282036f9568 Mon Sep 17 00:00:00 2001 From: John Coomes Date: Thu, 6 Dec 2007 13:59:28 -0800 Subject: [PATCH 006/258] 6635560: segv in reference processor on t1000 Revert back to using the default page size for the card table Reviewed-by: pbk, phh --- hotspot/src/share/vm/memory/cardTableModRefBS.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/hotspot/src/share/vm/memory/cardTableModRefBS.cpp b/hotspot/src/share/vm/memory/cardTableModRefBS.cpp index db7ffffc74e..d06cd8bf7c2 100644 --- a/hotspot/src/share/vm/memory/cardTableModRefBS.cpp +++ b/hotspot/src/share/vm/memory/cardTableModRefBS.cpp @@ -51,7 +51,7 @@ CardTableModRefBS::CardTableModRefBS(MemRegion whole_heap, _whole_heap(whole_heap), _guard_index(cards_required(whole_heap.word_size()) - 1), _last_valid_index(_guard_index - 1), - _page_size(os::page_size_for_region(_guard_index + 1, _guard_index + 1, 1)), + _page_size(os::vm_page_size()), _byte_map_size(compute_byte_map_size()) { _kind = BarrierSet::CardTableModRef; From 218615259df442a1f5dd232383ca3701421c09e5 Mon Sep 17 00:00:00 2001 From: Coleen Phillimore Date: Thu, 17 Jan 2008 13:38:17 -0800 Subject: [PATCH 007/258] 6646946: Kernel installation failed on Japanese and Chinese XP SP2 (VM part) Convert strings from Download Manager into native encoding in the VM Reviewed-by: sbohne, never, phh, kamg, xlu --- .../src/share/vm/classfile/javaClasses.cpp | 32 ++++++++++++++++++- .../src/share/vm/classfile/javaClasses.hpp | 1 + .../share/vm/classfile/systemDictionary.cpp | 4 ++- 3 files changed, 35 insertions(+), 2 deletions(-) diff --git a/hotspot/src/share/vm/classfile/javaClasses.cpp b/hotspot/src/share/vm/classfile/javaClasses.cpp index 115f45231e7..f2f3cb5869d 100644 --- a/hotspot/src/share/vm/classfile/javaClasses.cpp +++ b/hotspot/src/share/vm/classfile/javaClasses.cpp @@ -143,13 +143,43 @@ Handle java_lang_String::create_from_platform_dependent_str(const char* str, TRA jstring js = NULL; { JavaThread* thread = (JavaThread*)THREAD; assert(thread->is_Java_thread(), "must be java thread"); - ThreadToNativeFromVM ttn(thread); HandleMark hm(thread); + ThreadToNativeFromVM ttn(thread); js = (_to_java_string_fn)(thread->jni_environment(), str); } return Handle(THREAD, JNIHandles::resolve(js)); } +// Converts a Java String to a native C string that can be used for +// native OS calls. +char* java_lang_String::as_platform_dependent_str(Handle java_string, TRAPS) { + + typedef char* (*to_platform_string_fn_t)(JNIEnv*, jstring, bool*); + static to_platform_string_fn_t _to_platform_string_fn = NULL; + + if (_to_platform_string_fn == NULL) { + void *lib_handle = os::native_java_library(); + _to_platform_string_fn = CAST_TO_FN_PTR(to_platform_string_fn_t, hpi::dll_lookup(lib_handle, "GetStringPlatformChars")); + if (_to_platform_string_fn == NULL) { + fatal("GetStringPlatformChars missing"); + } + } + + char *native_platform_string; + { JavaThread* thread = (JavaThread*)THREAD; + assert(thread->is_Java_thread(), "must be java thread"); + JNIEnv *env = thread->jni_environment(); + jstring js = (jstring) JNIHandles::make_local(env, java_string()); + bool is_copy; + HandleMark hm(thread); + ThreadToNativeFromVM ttn(thread); + native_platform_string = (_to_platform_string_fn)(env, js, &is_copy); + assert(is_copy == JNI_TRUE, "is_copy value changed"); + JNIHandles::destroy_local(js); + } + return native_platform_string; +} + Handle java_lang_String::char_converter(Handle java_string, jchar from_char, jchar to_char, TRAPS) { oop obj = java_string(); // Typical usage is to convert all '/' to '.' in string. diff --git a/hotspot/src/share/vm/classfile/javaClasses.hpp b/hotspot/src/share/vm/classfile/javaClasses.hpp index 45acae2bd98..8ac7cf883fd 100644 --- a/hotspot/src/share/vm/classfile/javaClasses.hpp +++ b/hotspot/src/share/vm/classfile/javaClasses.hpp @@ -96,6 +96,7 @@ class java_lang_String : AllStatic { // String converters static char* as_utf8_string(oop java_string); static char* as_utf8_string(oop java_string, int start, int len); + static char* as_platform_dependent_str(Handle java_string, TRAPS); static jchar* as_unicode_string(oop java_string, int& length); static bool equals(oop java_string, jchar* chars, int len); diff --git a/hotspot/src/share/vm/classfile/systemDictionary.cpp b/hotspot/src/share/vm/classfile/systemDictionary.cpp index d71f63a6c12..a714ef583a6 100644 --- a/hotspot/src/share/vm/classfile/systemDictionary.cpp +++ b/hotspot/src/share/vm/classfile/systemDictionary.cpp @@ -1242,7 +1242,9 @@ static instanceKlassHandle download_and_retry_class_load( oop obj = (oop) result.get_jobject(); if (obj == NULL) { return nk; } - char* new_class_name = java_lang_String::as_utf8_string(obj); + Handle h_obj(THREAD, obj); + char* new_class_name = java_lang_String::as_platform_dependent_str(h_obj, + CHECK_(nk)); // lock the loader // we use this lock because JVMTI does. From f54eceace37cfe71701b1276cc5836245c73751b Mon Sep 17 00:00:00 2001 From: Keith McGuigan Date: Thu, 31 Jan 2008 09:41:34 -0500 Subject: [PATCH 008/258] 6631248: Memory problem when doing invalid type cast Changed memory allocation method for exception method Reviewed-by: ysr, never --- hotspot/src/share/vm/runtime/sharedRuntime.cpp | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/hotspot/src/share/vm/runtime/sharedRuntime.cpp b/hotspot/src/share/vm/runtime/sharedRuntime.cpp index e9a5685889d..5d507d165fd 100644 --- a/hotspot/src/share/vm/runtime/sharedRuntime.cpp +++ b/hotspot/src/share/vm/runtime/sharedRuntime.cpp @@ -1481,11 +1481,9 @@ char* SharedRuntime::generate_class_cast_message( const char* desc = " cannot be cast to "; size_t msglen = strlen(objName) + strlen(desc) + strlen(targetKlassName) + 1; - char* message = NEW_C_HEAP_ARRAY(char, msglen); + char* message = NEW_RESOURCE_ARRAY(char, msglen); if (NULL == message) { - // out of memory - can't use a detailed message. Since caller is - // using a resource mark to free memory, returning this should be - // safe (caller won't explicitly delete it). + // Shouldn't happen, but don't cause even more problems if it does message = const_cast(objName); } else { jio_snprintf(message, msglen, "%s%s%s", objName, desc, targetKlassName); From f7eb4517190504f13f900048fb0c5dfc9cc93902 Mon Sep 17 00:00:00 2001 From: Steve Bohne Date: Thu, 31 Jan 2008 14:56:50 -0500 Subject: [PATCH 009/258] 6598190: JPRT tests fail when run with -XX:+CheckUnhandledOops Work around Sun Studio C++ compiler bug 6629277 in dependencies.cpp Reviewed-by: kamg, sgoldman, pbk --- hotspot/src/share/vm/code/dependencies.cpp | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/hotspot/src/share/vm/code/dependencies.cpp b/hotspot/src/share/vm/code/dependencies.cpp index 75d0546642e..8d9d70d4207 100644 --- a/hotspot/src/share/vm/code/dependencies.cpp +++ b/hotspot/src/share/vm/code/dependencies.cpp @@ -1491,9 +1491,12 @@ bool DepChange::ContextStream::next() { // fall through: _change_type = Change_new_sub; case Change_new_sub: - _klass = instanceKlass::cast(_klass)->super(); - if (_klass != NULL) { - return true; + // 6598190: brackets workaround Sun Studio C++ compiler bug 6629277 + { + _klass = instanceKlass::cast(_klass)->super(); + if (_klass != NULL) { + return true; + } } // else set up _ti_limit and fall through: _ti_limit = (_ti_base == NULL) ? 0 : _ti_base->length(); From f804a7e9f9ba6f5dac4fc2f10b464f98cd319874 Mon Sep 17 00:00:00 2001 From: Xiaobin Lu Date: Tue, 5 Feb 2008 23:21:57 -0800 Subject: [PATCH 010/258] 6610420: Debug VM crashes during monitor lock rank checking Make SerializePage lock as raw lock and add name for mutex locks Reviewed-by: never, dice, dholmes --- hotspot/src/share/vm/runtime/mutex.cpp | 13 ++++++++---- hotspot/src/share/vm/runtime/mutex.hpp | 8 ++++--- hotspot/src/share/vm/runtime/mutexLocker.cpp | 4 ---- hotspot/src/share/vm/runtime/mutexLocker.hpp | 1 - hotspot/src/share/vm/runtime/os.cpp | 22 +++++++++----------- 5 files changed, 24 insertions(+), 24 deletions(-) diff --git a/hotspot/src/share/vm/runtime/mutex.cpp b/hotspot/src/share/vm/runtime/mutex.cpp index a4d341b9637..c8751c2121c 100644 --- a/hotspot/src/share/vm/runtime/mutex.cpp +++ b/hotspot/src/share/vm/runtime/mutex.cpp @@ -1119,10 +1119,15 @@ Monitor::~Monitor() { assert ((UNS(_owner)|UNS(_LockWord.FullWord)|UNS(_EntryList)|UNS(_WaitSet)|UNS(_OnDeck)) == 0, "") ; } -void Monitor::ClearMonitor (Monitor * m) { +void Monitor::ClearMonitor (Monitor * m, const char *name) { m->_owner = NULL ; m->_snuck = false ; - m->_name = "UNKNOWN" ; + if (name == NULL) { + strcpy(m->_name, "UNKNOWN") ; + } else { + strncpy(m->_name, name, MONITOR_NAME_LEN - 1); + m->_name[MONITOR_NAME_LEN - 1] = '\0'; + } m->_LockWord.FullWord = 0 ; m->_EntryList = NULL ; m->_OnDeck = NULL ; @@ -1133,7 +1138,7 @@ void Monitor::ClearMonitor (Monitor * m) { Monitor::Monitor() { ClearMonitor(this); } Monitor::Monitor (int Rank, const char * name, bool allow_vm_block) { - ClearMonitor (this) ; + ClearMonitor (this, name) ; #ifdef ASSERT _allow_vm_block = allow_vm_block; _rank = Rank ; @@ -1145,7 +1150,7 @@ Mutex::~Mutex() { } Mutex::Mutex (int Rank, const char * name, bool allow_vm_block) { - ClearMonitor ((Monitor *) this) ; + ClearMonitor ((Monitor *) this, name) ; #ifdef ASSERT _allow_vm_block = allow_vm_block; _rank = Rank ; diff --git a/hotspot/src/share/vm/runtime/mutex.hpp b/hotspot/src/share/vm/runtime/mutex.hpp index 761cebb2ba4..56988e20e79 100644 --- a/hotspot/src/share/vm/runtime/mutex.hpp +++ b/hotspot/src/share/vm/runtime/mutex.hpp @@ -82,6 +82,9 @@ class ParkEvent ; // *in that order*. If their implementations change such that these // assumptions are violated, a whole lot of code will break. +// The default length of monitor name is choosen to be 64 to avoid false sharing. +static const int MONITOR_NAME_LEN = 64; + class Monitor : public CHeapObj { public: @@ -126,9 +129,8 @@ class Monitor : public CHeapObj { volatile intptr_t _WaitLock [1] ; // Protects _WaitSet ParkEvent * volatile _WaitSet ; // LL of ParkEvents volatile bool _snuck; // Used for sneaky locking (evil). - const char * _name; // Name of mutex int NotifyCount ; // diagnostic assist - double pad [8] ; // avoid false sharing + char _name[MONITOR_NAME_LEN]; // Name of mutex // Debugging fields for naming, deadlock detection, etc. (some only used in debug mode) #ifndef PRODUCT @@ -170,7 +172,7 @@ class Monitor : public CHeapObj { int ILocked () ; protected: - static void ClearMonitor (Monitor * m) ; + static void ClearMonitor (Monitor * m, const char* name = NULL) ; Monitor() ; public: diff --git a/hotspot/src/share/vm/runtime/mutexLocker.cpp b/hotspot/src/share/vm/runtime/mutexLocker.cpp index 317e24ee535..a639519d26d 100644 --- a/hotspot/src/share/vm/runtime/mutexLocker.cpp +++ b/hotspot/src/share/vm/runtime/mutexLocker.cpp @@ -188,10 +188,6 @@ void mutex_init() { def(Safepoint_lock , Monitor, safepoint, true ); // locks SnippetCache_lock/Threads_lock - if (!UseMembar) { - def(SerializePage_lock , Monitor, leaf, true ); - } - def(Threads_lock , Monitor, barrier, true ); def(VMOperationQueue_lock , Monitor, nonleaf, true ); // VM_thread allowed to block on these diff --git a/hotspot/src/share/vm/runtime/mutexLocker.hpp b/hotspot/src/share/vm/runtime/mutexLocker.hpp index 59f145fcfb6..e21367cb960 100644 --- a/hotspot/src/share/vm/runtime/mutexLocker.hpp +++ b/hotspot/src/share/vm/runtime/mutexLocker.hpp @@ -52,7 +52,6 @@ extern Mutex* DerivedPointerTableGC_lock; // a lock to protect the derive extern Monitor* VMOperationQueue_lock; // a lock on queue of vm_operations waiting to execute extern Monitor* VMOperationRequest_lock; // a lock on Threads waiting for a vm_operation to terminate extern Monitor* Safepoint_lock; // a lock used by the safepoint abstraction -extern Monitor* SerializePage_lock; // a lock used when VMThread changing serialize memory page permission during safepoint extern Monitor* Threads_lock; // a lock on the Threads table of active Java threads // (also used by Safepoints too to block threads creation/destruction) extern Monitor* CGC_lock; // used for coordination between diff --git a/hotspot/src/share/vm/runtime/os.cpp b/hotspot/src/share/vm/runtime/os.cpp index 72dfb2265ff..980c1179340 100644 --- a/hotspot/src/share/vm/runtime/os.cpp +++ b/hotspot/src/share/vm/runtime/os.cpp @@ -956,7 +956,6 @@ bool os::set_boot_path(char fileSep, char pathSep) { return true; } - void os::set_memory_serialize_page(address page) { int count = log2_intptr(sizeof(class JavaThread)) - log2_intptr(64); _mem_serialize_page = (volatile int32_t *)page; @@ -967,6 +966,8 @@ void os::set_memory_serialize_page(address page) { set_serialize_page_mask((uintptr_t)(vm_page_size() - sizeof(int32_t))); } +static volatile intptr_t SerializePageLock = 0; + // This method is called from signal handler when SIGSEGV occurs while the current // thread tries to store to the "read-only" memory serialize page during state // transition. @@ -974,15 +975,14 @@ void os::block_on_serialize_page_trap() { if (TraceSafepoint) { tty->print_cr("Block until the serialize page permission restored"); } - // When VMThread is holding the SerializePage_lock during modifying the + // When VMThread is holding the SerializePageLock during modifying the // access permission of the memory serialize page, the following call // will block until the permission of that page is restored to rw. // Generally, it is unsafe to manipulate locks in signal handlers, but in // this case, it's OK as the signal is synchronous and we know precisely when - // it can occur. SerializePage_lock is a transiently-held leaf lock, so - // lock_without_safepoint_check should be safe. - SerializePage_lock->lock_without_safepoint_check(); - SerializePage_lock->unlock(); + // it can occur. + Thread::muxAcquire(&SerializePageLock, "set_memory_serialize_page"); + Thread::muxRelease(&SerializePageLock); } // Serialize all thread state variables @@ -990,14 +990,12 @@ void os::serialize_thread_states() { // On some platforms such as Solaris & Linux, the time duration of the page // permission restoration is observed to be much longer than expected due to // scheduler starvation problem etc. To avoid the long synchronization - // time and expensive page trap spinning, 'SerializePage_lock' is used to block - // the mutator thread if such case is encountered. Since this method is always - // called by VMThread during safepoint, lock_without_safepoint_check is used - // instead. See bug 6546278. - SerializePage_lock->lock_without_safepoint_check(); + // time and expensive page trap spinning, 'SerializePageLock' is used to block + // the mutator thread if such case is encountered. See bug 6546278 for details. + Thread::muxAcquire(&SerializePageLock, "serialize_thread_states"); os::protect_memory( (char *)os::get_memory_serialize_page(), os::vm_page_size() ); os::unguard_memory( (char *)os::get_memory_serialize_page(), os::vm_page_size() ); - SerializePage_lock->unlock(); + Thread::muxRelease(&SerializePageLock); } // Returns true if the current stack pointer is above the stack shadow From 527390207c78c2ab03991f03fd3a585775ee497f Mon Sep 17 00:00:00 2001 From: Jon Masamitsu Date: Mon, 11 Feb 2008 15:40:07 -0800 Subject: [PATCH 011/258] 6624782: Bigapps crashes during CMS precleaning Lowered optimization level for files instanceKlass.cpp and objArrayKlass.cpp Reviewed-by: ysr --- hotspot/build/solaris/makefiles/amd64.make | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/hotspot/build/solaris/makefiles/amd64.make b/hotspot/build/solaris/makefiles/amd64.make index d4a09b7b778..9b229e83b79 100644 --- a/hotspot/build/solaris/makefiles/amd64.make +++ b/hotspot/build/solaris/makefiles/amd64.make @@ -19,7 +19,7 @@ # Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, # CA 95054 USA or visit www.sun.com if you need additional information or # have any questions. -# +# # # Must also specify if CPU is little endian @@ -45,6 +45,10 @@ OPT_CFLAGS/os_solaris_x86_64.o = -xO1 OPT_CFLAGS/generateOptoStub.o = -xO2 OPT_CFLAGS/thread.o = -xO2 +# Work around for 6624782 +OPT_CFLAGS/instanceKlass.o = -Qoption ube -no_a2lf +OPT_CFLAGS/objArrayKlass.o = -Qoption ube -no_a2lf + else ifeq ("${Platform_compiler}", "gcc") @@ -58,6 +62,6 @@ else # error _JUNK2_ := $(shell echo >&2 \ "*** ERROR: this compiler is not yet supported by this code base!") - @exit 1 + @exit 1 endif endif From 41895dc06d21a7bc20eb4bb838400e30046a92df Mon Sep 17 00:00:00 2001 From: "Y. Srinivas Ramakrishna" Date: Tue, 12 Feb 2008 16:07:46 -0800 Subject: [PATCH 012/258] 6659981: +ParallelRefProcEnabled crashes on single core platform Disable parallel reference processing when there are no worker threads Reviewed-by: apetrusenko, pbk, jmasa, tonyp --- hotspot/src/share/vm/memory/referenceProcessor.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/hotspot/src/share/vm/memory/referenceProcessor.cpp b/hotspot/src/share/vm/memory/referenceProcessor.cpp index 24793bb4152..6aeeecd3e15 100644 --- a/hotspot/src/share/vm/memory/referenceProcessor.cpp +++ b/hotspot/src/share/vm/memory/referenceProcessor.cpp @@ -85,7 +85,7 @@ ReferenceProcessor* ReferenceProcessor::create_ref_processor( ReferenceProcessor* rp = new ReferenceProcessor(span, atomic_discovery, mt_discovery, mt_degree, - mt_processing); + mt_processing && (parallel_gc_threads > 0)); if (rp == NULL) { vm_exit_during_initialization("Could not allocate ReferenceProcessor object"); } From 90815abd517a1e64cd0719d70222b384a37dfbdd Mon Sep 17 00:00:00 2001 From: Vladimir Kozlov Date: Tue, 12 Feb 2008 18:37:50 -0800 Subject: [PATCH 013/258] 6621098: "* HeapWordSize" for TrackedInitializationLimit is missing '* HeapWordSize' is missing in GraphKit::set_output_for_allocation() Reviewed-by: rasbold, jrose, never --- hotspot/src/share/vm/opto/graphKit.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/hotspot/src/share/vm/opto/graphKit.cpp b/hotspot/src/share/vm/opto/graphKit.cpp index 8df5f4272f4..642883ad64b 100644 --- a/hotspot/src/share/vm/opto/graphKit.cpp +++ b/hotspot/src/share/vm/opto/graphKit.cpp @@ -2808,7 +2808,7 @@ Node* GraphKit::set_output_for_allocation(AllocateNode* alloc, ciInstanceKlass* ik = oop_type->klass()->as_instance_klass(); for (int i = 0, len = ik->nof_nonstatic_fields(); i < len; i++) { ciField* field = ik->nonstatic_field_at(i); - if (field->offset() >= TrackedInitializationLimit) + if (field->offset() >= TrackedInitializationLimit * HeapWordSize) continue; // do not bother to track really large numbers of fields // Find (or create) the alias category for this field: int fieldidx = C->alias_type(field)->index(); From 38fdc8ab98ef3f47aa5f80ff05d049694ceb3dc7 Mon Sep 17 00:00:00 2001 From: Jon Masamitsu Date: Fri, 15 Feb 2008 07:01:10 -0800 Subject: [PATCH 014/258] 6624765: Guarantee failure "Unexpected dirty card found" In verification take into account partial coverage of a region by a card and expansion of the card table. Reviewed-by: ysr, apetrusenko --- .../parNew/parNewGeneration.cpp | 3 +++ .../src/share/vm/memory/cardTableModRefBS.cpp | 20 +++++++++---------- hotspot/src/share/vm/memory/cardTableRS.cpp | 8 +++++++- hotspot/src/share/vm/memory/cardTableRS.hpp | 2 +- hotspot/src/share/vm/memory/genRemSet.hpp | 11 ++++++++-- .../src/share/vm/memory/tenuredGeneration.cpp | 3 ++- 6 files changed, 32 insertions(+), 15 deletions(-) diff --git a/hotspot/src/share/vm/gc_implementation/parNew/parNewGeneration.cpp b/hotspot/src/share/vm/gc_implementation/parNew/parNewGeneration.cpp index 603d6493fef..2bcd31138ff 100644 --- a/hotspot/src/share/vm/gc_implementation/parNew/parNewGeneration.cpp +++ b/hotspot/src/share/vm/gc_implementation/parNew/parNewGeneration.cpp @@ -785,6 +785,9 @@ void ParNewGeneration::collect(bool full, swap_spaces(); // Make life simpler for CMS || rescan; see 6483690. from()->set_next_compaction_space(to()); gch->set_incremental_collection_will_fail(); + + // Reset the PromotionFailureALot counters. + NOT_PRODUCT(Universe::heap()->reset_promotion_should_fail();) } // set new iteration safe limit for the survivor spaces from()->set_concurrent_iteration_safe_limit(from()->top()); diff --git a/hotspot/src/share/vm/memory/cardTableModRefBS.cpp b/hotspot/src/share/vm/memory/cardTableModRefBS.cpp index db7ffffc74e..df330e6c0b9 100644 --- a/hotspot/src/share/vm/memory/cardTableModRefBS.cpp +++ b/hotspot/src/share/vm/memory/cardTableModRefBS.cpp @@ -196,8 +196,8 @@ void CardTableModRefBS::resize_covered_region(MemRegion new_region) { assert(_whole_heap.contains(new_region), "attempt to cover area not in reserved area"); debug_only(verify_guard();) - int ind = find_covering_region_by_base(new_region.start()); - MemRegion old_region = _covered[ind]; + int const ind = find_covering_region_by_base(new_region.start()); + MemRegion const old_region = _covered[ind]; assert(old_region.start() == new_region.start(), "just checking"); if (new_region.word_size() != old_region.word_size()) { // Commit new or uncommit old pages, if necessary. @@ -205,21 +205,21 @@ void CardTableModRefBS::resize_covered_region(MemRegion new_region) { // Extend the end of this _commited region // to cover the end of any lower _committed regions. // This forms overlapping regions, but never interior regions. - HeapWord* max_prev_end = largest_prev_committed_end(ind); + HeapWord* const max_prev_end = largest_prev_committed_end(ind); if (max_prev_end > cur_committed.end()) { cur_committed.set_end(max_prev_end); } // Align the end up to a page size (starts are already aligned). - jbyte* new_end = byte_after(new_region.last()); - HeapWord* new_end_aligned = - (HeapWord*)align_size_up((uintptr_t)new_end, _page_size); + jbyte* const new_end = byte_after(new_region.last()); + HeapWord* const new_end_aligned = + (HeapWord*) align_size_up((uintptr_t)new_end, _page_size); assert(new_end_aligned >= (HeapWord*) new_end, "align up, but less"); // The guard page is always committed and should not be committed over. - HeapWord* new_end_for_commit = MIN2(new_end_aligned, _guard_region.start()); + HeapWord* const new_end_for_commit = MIN2(new_end_aligned, _guard_region.start()); if (new_end_for_commit > cur_committed.end()) { // Must commit new pages. - MemRegion new_committed = + MemRegion const new_committed = MemRegion(cur_committed.end(), new_end_for_commit); assert(!new_committed.is_empty(), "Region should not be empty here"); @@ -233,7 +233,7 @@ void CardTableModRefBS::resize_covered_region(MemRegion new_region) { // the cur_committed region may include the guard region. } else if (new_end_aligned < cur_committed.end()) { // Must uncommit pages. - MemRegion uncommit_region = + MemRegion const uncommit_region = committed_unique_to_self(ind, MemRegion(new_end_aligned, cur_committed.end())); if (!uncommit_region.is_empty()) { @@ -257,7 +257,7 @@ void CardTableModRefBS::resize_covered_region(MemRegion new_region) { } assert(index_for(new_region.last()) < (int) _guard_index, "The guard card will be overwritten"); - jbyte* end = byte_after(new_region.last()); + jbyte* const end = (jbyte*) new_end_for_commit; // do nothing if we resized downward. if (entry < end) { memset(entry, clean_card, pointer_delta(end, entry, sizeof(jbyte))); diff --git a/hotspot/src/share/vm/memory/cardTableRS.cpp b/hotspot/src/share/vm/memory/cardTableRS.cpp index 6c762941be2..f389a70a40a 100644 --- a/hotspot/src/share/vm/memory/cardTableRS.cpp +++ b/hotspot/src/share/vm/memory/cardTableRS.cpp @@ -556,10 +556,16 @@ void CardTableRS::verify() { } -void CardTableRS::verify_empty(MemRegion mr) { +void CardTableRS::verify_aligned_region_empty(MemRegion mr) { if (!mr.is_empty()) { jbyte* cur_entry = byte_for(mr.start()); jbyte* limit = byte_after(mr.last()); + // The region mr may not start on a card boundary so + // the first card may reflect a write to the space + // just prior to mr. + if (!is_aligned(mr.start())) { + cur_entry++; + } for (;cur_entry < limit; cur_entry++) { guarantee(*cur_entry == CardTableModRefBS::clean_card, "Unexpected dirty card found"); diff --git a/hotspot/src/share/vm/memory/cardTableRS.hpp b/hotspot/src/share/vm/memory/cardTableRS.hpp index fa973aee45f..5d92067aa43 100644 --- a/hotspot/src/share/vm/memory/cardTableRS.hpp +++ b/hotspot/src/share/vm/memory/cardTableRS.hpp @@ -126,7 +126,7 @@ public: } void verify(); - void verify_empty(MemRegion mr); + void verify_aligned_region_empty(MemRegion mr); void clear(MemRegion mr) { _ct_bs.clear(mr); } void clear_into_younger(Generation* gen, bool clear_perm); diff --git a/hotspot/src/share/vm/memory/genRemSet.hpp b/hotspot/src/share/vm/memory/genRemSet.hpp index 5de388cda52..006eab3ebb6 100644 --- a/hotspot/src/share/vm/memory/genRemSet.hpp +++ b/hotspot/src/share/vm/memory/genRemSet.hpp @@ -91,8 +91,15 @@ public: virtual void verify() = 0; // Verify that the remembered set has no entries for - // the heap interval denoted by mr. - virtual void verify_empty(MemRegion mr) = 0; + // the heap interval denoted by mr. If there are any + // alignment constraints on the remembered set, only the + // part of the region that is aligned is checked. + // + // alignment boundaries + // +--------+-------+--------+-------+ + // [ region mr ) + // [ part checked ) + virtual void verify_aligned_region_empty(MemRegion mr) = 0; // If appropriate, print some information about the remset on "tty". virtual void print() {} diff --git a/hotspot/src/share/vm/memory/tenuredGeneration.cpp b/hotspot/src/share/vm/memory/tenuredGeneration.cpp index 8c46169b7fe..8e04fd38814 100644 --- a/hotspot/src/share/vm/memory/tenuredGeneration.cpp +++ b/hotspot/src/share/vm/memory/tenuredGeneration.cpp @@ -409,10 +409,11 @@ void TenuredGeneration::retire_alloc_buffers_before_full_gc() { void TenuredGeneration::verify_alloc_buffers_clean() { if (UseParNewGC) { for (uint i = 0; i < ParallelGCThreads; i++) { - _rs->verify_empty(_alloc_buffers[i]->range()); + _rs->verify_aligned_region_empty(_alloc_buffers[i]->range()); } } } + #else // SERIALGC void TenuredGeneration::retire_alloc_buffers_before_full_gc() {} void TenuredGeneration::verify_alloc_buffers_clean() {} From ae065e629037a6560e694d5332bc57286dddb75f Mon Sep 17 00:00:00 2001 From: "Y. Srinivas Ramakrishna" Date: Sat, 16 Feb 2008 22:41:20 -0800 Subject: [PATCH 015/258] 6621144: CMS: assertion failure "is_cms_thread == Thread::current()->is_ConcurrentGC_thread()" Take lock conditionally (in asynchronous mode only) when updating the dead-object map. Reviewed-by: jmasa --- .../concurrentMarkSweepGeneration.cpp | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/concurrentMarkSweepGeneration.cpp b/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/concurrentMarkSweepGeneration.cpp index f8355d945e6..3fbed8f3cbe 100644 --- a/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/concurrentMarkSweepGeneration.cpp +++ b/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/concurrentMarkSweepGeneration.cpp @@ -5732,13 +5732,19 @@ void CMSCollector::sweep(bool asynch) { // in the perm_gen_verify_bit_map. In order to do that we traverse // all blocks in perm gen and mark all dead objects. if (verifying() && !cms_should_unload_classes()) { - CMSTokenSyncWithLocks ts(true, _permGen->freelistLock(), - bitMapLock()); assert(perm_gen_verify_bit_map()->sizeInBits() != 0, "Should have already been allocated"); MarkDeadObjectsClosure mdo(this, _permGen->cmsSpace(), markBitMap(), perm_gen_verify_bit_map()); - _permGen->cmsSpace()->blk_iterate(&mdo); + if (asynch) { + CMSTokenSyncWithLocks ts(true, _permGen->freelistLock(), + bitMapLock()); + _permGen->cmsSpace()->blk_iterate(&mdo); + } else { + // In the case of synchronous sweep, we already have + // the requisite locks/tokens. + _permGen->cmsSpace()->blk_iterate(&mdo); + } } if (asynch) { From 9c36dab8c45513cb35868adef9df7b0ffc058a58 Mon Sep 17 00:00:00 2001 From: Jon Masamitsu Date: Wed, 20 Feb 2008 08:40:31 -0800 Subject: [PATCH 016/258] 6665445: Backout change to CardTableModRefBS::resize_covered_region() Backed out part of cahnge for 6624765 because of nightly testing regressions. Reviewers below were for 6624765. Reviewed-by: ysr, apetrusenko --- hotspot/src/share/vm/memory/cardTableModRefBS.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/hotspot/src/share/vm/memory/cardTableModRefBS.cpp b/hotspot/src/share/vm/memory/cardTableModRefBS.cpp index df330e6c0b9..6de1366952d 100644 --- a/hotspot/src/share/vm/memory/cardTableModRefBS.cpp +++ b/hotspot/src/share/vm/memory/cardTableModRefBS.cpp @@ -257,7 +257,7 @@ void CardTableModRefBS::resize_covered_region(MemRegion new_region) { } assert(index_for(new_region.last()) < (int) _guard_index, "The guard card will be overwritten"); - jbyte* const end = (jbyte*) new_end_for_commit; + jbyte* const end = byte_after(new_region.last()); // do nothing if we resized downward. if (entry < end) { memset(entry, clean_card, pointer_delta(end, entry, sizeof(jbyte))); From 5ade869e8cbf3ff04f55aa99824d8ae79f45915c Mon Sep 17 00:00:00 2001 From: Vladimir Kozlov Date: Wed, 20 Feb 2008 16:19:43 -0800 Subject: [PATCH 017/258] 6614330: Node::dump(n) does not print full graph for specified depth A node is not processed in dump_nodes() if it was visited during processing previous inputs. Reviewed-by: rasbold --- hotspot/src/share/vm/opto/node.cpp | 77 ++++++++++++++++-------------- 1 file changed, 41 insertions(+), 36 deletions(-) diff --git a/hotspot/src/share/vm/opto/node.cpp b/hotspot/src/share/vm/opto/node.cpp index d7563d611ea..14e112e2101 100644 --- a/hotspot/src/share/vm/opto/node.cpp +++ b/hotspot/src/share/vm/opto/node.cpp @@ -1486,70 +1486,75 @@ static void dump_nodes(const Node* start, int d, bool only_ctrl) { Node* s = (Node*)start; // remove const if (NotANode(s)) return; + uint depth = (uint)ABS(d); + int direction = d; Compile* C = Compile::current(); ResourceArea *area = Thread::current()->resource_area(); - Node_Stack stack(area, MIN2((uint)ABS(d), C->unique() >> 1)); - OldNewVectorSet visited(C->node_arena(), area); + Node_Stack stack(area, MIN2(depth, C->unique() >> 1)); + OldNewVectorSet dumped(C->node_arena(), area); OldNewVectorSet on_stack(C->node_arena(), area); - visited.set(s); on_stack.set(s); stack.push(s, 0); - if (d < 0) s->dump(); + if (direction < 0) { + dumped.set(s); + s->dump(); + } // Do a depth first walk over edges while (stack.is_nonempty()) { Node* tp = stack.node(); uint idx = stack.index(); - uint limit = d > 0 ? tp->len() : tp->outcnt(); + uint limit; + // Limit depth + if (stack.size() < depth) { + limit = direction > 0 ? tp->len() : tp->outcnt(); + } else { + limit = 0; // reached depth limit. + } if (idx >= limit) { // no more arcs to visit - if (d > 0) tp->dump(); + if (direction > 0 && !dumped.test_set(tp)) tp->dump(); on_stack.del(tp); stack.pop(); } else { // process the "idx"th arc stack.set_index(idx + 1); - Node* n = d > 0 ? tp->in(idx) : tp->raw_out(idx); + Node* n = direction > 0 ? tp->in(idx) : tp->raw_out(idx); if (NotANode(n)) continue; // do not recurse through top or the root (would reach unrelated stuff) if (n->is_Root() || n->is_top()) continue; if (only_ctrl && !n->is_CFG()) continue; - if (!visited.test_set(n)) { // forward arc - // Limit depth - if (stack.size() < (uint)ABS(d)) { - if (d < 0) n->dump(); - stack.push(n, 0); - on_stack.set(n); - } + if (!on_stack.test(n)) { // forward arc + if (direction < 0 && !dumped.test_set(n)) n->dump(); + stack.push(n, 0); + on_stack.set(n); } else { // back or cross arc - if (on_stack.test(n)) { // back arc - // print loop if there are no phis or regions in the mix - bool found_loop_breaker = false; - int k; - for (k = stack.size() - 1; k >= 0; k--) { - Node* m = stack.node_at(k); - if (m->is_Phi() || m->is_Region() || m->is_Root() || m->is_Start()) { - found_loop_breaker = true; - break; - } - if (m == n) // Found loop head - break; + // print loop if there are no phis or regions in the mix + bool found_loop_breaker = false; + int k; + for (k = stack.size() - 1; k >= 0; k--) { + Node* m = stack.node_at(k); + if (m->is_Phi() || m->is_Region() || m->is_Root() || m->is_Start()) { + found_loop_breaker = true; + break; } - assert(k >= 0, "n must be on stack"); + if (m == n) // Found loop head + break; + } + assert(k >= 0, "n must be on stack"); - if (!found_loop_breaker) { - tty->print("# %s LOOP FOUND:", only_ctrl ? "CONTROL" : "DATA"); - for (int i = stack.size() - 1; i >= k; i--) { - Node* m = stack.node_at(i); - bool mnew = C->node_arena()->contains(m); - tty->print(" %s%d:%s", (mnew? "": "o"), m->_idx, m->Name()); - if (i != 0) tty->print(d > 0? " <-": " ->"); - } - tty->cr(); + if (!found_loop_breaker) { + tty->print("# %s LOOP FOUND:", only_ctrl ? "CONTROL" : "DATA"); + for (int i = stack.size() - 1; i >= k; i--) { + Node* m = stack.node_at(i); + bool mnew = C->node_arena()->contains(m); + tty->print(" %s%d:%s", (mnew? "": "o"), m->_idx, m->Name()); + if (i != 0) tty->print(direction > 0? " <-": " ->"); } + tty->cr(); } } } From 26097e9848a3655dc2b4e7664639e4e56f1c135c Mon Sep 17 00:00:00 2001 From: Vladimir Kozlov Date: Wed, 20 Feb 2008 17:23:43 -0800 Subject: [PATCH 018/258] 6621094: PrintOptoAssembly is broken for oops information in DebugInfo OopMapValue and VMRegImpl classes miss the virtual method print_on(st). Reviewed-by: rasbold, jrose, never --- hotspot/src/share/vm/code/vmreg.cpp | 10 ++++----- hotspot/src/share/vm/code/vmreg.hpp | 9 ++++---- hotspot/src/share/vm/compiler/oopMap.cpp | 28 ++++++++++++------------ hotspot/src/share/vm/compiler/oopMap.hpp | 3 ++- 4 files changed, 26 insertions(+), 24 deletions(-) diff --git a/hotspot/src/share/vm/code/vmreg.cpp b/hotspot/src/share/vm/code/vmreg.cpp index 32e70f8cda4..22be4b2f390 100644 --- a/hotspot/src/share/vm/code/vmreg.cpp +++ b/hotspot/src/share/vm/code/vmreg.cpp @@ -36,16 +36,16 @@ const int VMRegImpl::register_count = ConcreteRegisterImpl::number_of_registers; // Register names const char *VMRegImpl::regName[ConcreteRegisterImpl::number_of_registers]; -void VMRegImpl::print() { #ifndef PRODUCT +void VMRegImpl::print_on(outputStream* st) const { if( is_reg() ) { assert( VMRegImpl::regName[value()], "" ); - tty->print("%s",VMRegImpl::regName[value()]); + st->print("%s",VMRegImpl::regName[value()]); } else if (is_stack()) { int stk = value() - stack0->value(); - tty->print("[%d]", stk*4); + st->print("[%d]", stk*4); } else { - tty->print("BAD!"); + st->print("BAD!"); } -#endif // PRODUCT } +#endif // PRODUCT diff --git a/hotspot/src/share/vm/code/vmreg.hpp b/hotspot/src/share/vm/code/vmreg.hpp index 66b3540789f..ab77b265fe3 100644 --- a/hotspot/src/share/vm/code/vmreg.hpp +++ b/hotspot/src/share/vm/code/vmreg.hpp @@ -66,9 +66,9 @@ public: } } static VMReg Bad() { return (VMReg) (intptr_t) BAD; } - bool is_valid() { return ((intptr_t) this) != BAD; } - bool is_stack() { return (intptr_t) this >= (intptr_t) stack0; } - bool is_reg() { return is_valid() && !is_stack(); } + bool is_valid() const { return ((intptr_t) this) != BAD; } + bool is_stack() const { return (intptr_t) this >= (intptr_t) stack0; } + bool is_reg() const { return is_valid() && !is_stack(); } // A concrete register is a value that returns true for is_reg() and is // also a register you could use in the assembler. On machines with @@ -96,7 +96,8 @@ public: intptr_t value() const {return (intptr_t) this; } - void print(); + void print_on(outputStream* st) const PRODUCT_RETURN; + void print() const { print_on(tty); } // bias a stack slot. // Typically used to adjust a virtual frame slots by amounts that are offset by diff --git a/hotspot/src/share/vm/compiler/oopMap.cpp b/hotspot/src/share/vm/compiler/oopMap.cpp index bd6dc80132e..b4a85f787f8 100644 --- a/hotspot/src/share/vm/compiler/oopMap.cpp +++ b/hotspot/src/share/vm/compiler/oopMap.cpp @@ -506,27 +506,27 @@ bool OopMap::has_derived_pointer() const { } -void print_register_type(OopMapValue::oop_types x, VMReg optional) { +static void print_register_type(OopMapValue::oop_types x, VMReg optional, outputStream* st) { switch( x ) { case OopMapValue::oop_value: - tty->print("Oop"); + st->print("Oop"); break; case OopMapValue::value_value: - tty->print("Value" ); + st->print("Value" ); break; case OopMapValue::dead_value: - tty->print("Dead" ); + st->print("Dead" ); break; case OopMapValue::callee_saved_value: - tty->print("Callers_" ); - optional->print(); + st->print("Callers_" ); + optional->print_on(st); break; case OopMapValue::derived_oop_value: - tty->print("Derived_oop_" ); - optional->print(); + st->print("Derived_oop_" ); + optional->print_on(st); break; case OopMapValue::stack_obj: - tty->print("Stack"); + st->print("Stack"); break; default: ShouldNotReachHere(); @@ -534,11 +534,11 @@ void print_register_type(OopMapValue::oop_types x, VMReg optional) { } -void OopMapValue::print() const { - reg()->print(); - tty->print("="); - print_register_type(type(),content_reg()); - tty->print(" "); +void OopMapValue::print_on(outputStream* st) const { + reg()->print_on(st); + st->print("="); + print_register_type(type(),content_reg(),st); + st->print(" "); } diff --git a/hotspot/src/share/vm/compiler/oopMap.hpp b/hotspot/src/share/vm/compiler/oopMap.hpp index dec8afe5789..8b678368247 100644 --- a/hotspot/src/share/vm/compiler/oopMap.hpp +++ b/hotspot/src/share/vm/compiler/oopMap.hpp @@ -129,7 +129,8 @@ public: return reg()->reg2stack(); } - void print( ) const PRODUCT_RETURN; + void print_on(outputStream* st) const PRODUCT_RETURN; + void print() const { print_on(tty); } }; From 74f243990ce624512f791cddc8b32abf3f021944 Mon Sep 17 00:00:00 2001 From: "Y. Srinivas Ramakrishna" Date: Thu, 21 Feb 2008 11:03:54 -0800 Subject: [PATCH 019/258] 6642634: Test nsk/regression/b6186200 crashed with SIGSEGV Use correct allocation path in expand_and_allocate() so object's mark and p-bits are set as appropriate. Reviewed-by: jmasa, pbk --- .../concurrentMarkSweep/concurrentMarkSweepGeneration.cpp | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/concurrentMarkSweepGeneration.cpp b/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/concurrentMarkSweepGeneration.cpp index 3fbed8f3cbe..eff7a042e95 100644 --- a/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/concurrentMarkSweepGeneration.cpp +++ b/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/concurrentMarkSweepGeneration.cpp @@ -3121,12 +3121,7 @@ ConcurrentMarkSweepGeneration::expand_and_allocate(size_t word_size, if (GCExpandToAllocateDelayMillis > 0) { os::sleep(Thread::current(), GCExpandToAllocateDelayMillis, false); } - size_t adj_word_sz = CompactibleFreeListSpace::adjustObjectSize(word_size); - if (parallel) { - return cmsSpace()->par_allocate(adj_word_sz); - } else { - return cmsSpace()->allocate(adj_word_sz); - } + return have_lock_and_allocate(word_size, tlab); } // YSR: All of this generation expansion/shrinking stuff is an exact copy of From b8789d9c9af593b423495c9be35b857aca38984b Mon Sep 17 00:00:00 2001 From: Vladimir Kozlov Date: Thu, 21 Feb 2008 14:03:41 -0800 Subject: [PATCH 020/258] 6621084: ciMethodBlocks::split_block_at() is broken for methods with exception handler After an exception handler block is split the exception information is not moved to the new block which starts in exception handler BCI. Reviewed-by: jrose --- hotspot/src/share/vm/ci/ciMethodBlocks.cpp | 39 ++++++++++++++++++++-- hotspot/src/share/vm/ci/ciMethodBlocks.hpp | 3 +- 2 files changed, 38 insertions(+), 4 deletions(-) diff --git a/hotspot/src/share/vm/ci/ciMethodBlocks.cpp b/hotspot/src/share/vm/ci/ciMethodBlocks.cpp index d2b93186d9d..4c596bbc4fb 100644 --- a/hotspot/src/share/vm/ci/ciMethodBlocks.cpp +++ b/hotspot/src/share/vm/ci/ciMethodBlocks.cpp @@ -67,6 +67,14 @@ ciBlock *ciMethodBlocks::split_block_at(int bci) { break; } } + // Move an exception handler information if needed. + if (former_block->is_handler()) { + int ex_start = former_block->ex_start_bci(); + int ex_end = former_block->ex_limit_bci(); + new_block->set_exception_range(ex_start, ex_end); + // Clear information in former_block. + former_block->clear_exception_handler(); + } return former_block; } @@ -102,7 +110,7 @@ void ciMethodBlocks::do_analysis() { // one and end the old one. assert(cur_block != NULL, "must always have a current block"); ciBlock *new_block = block_containing(bci); - if (new_block == NULL) { + if (new_block == NULL || new_block == cur_block) { // We have not marked this bci as the start of a new block. // Keep interpreting the current_range. _bci_to_block[bci] = cur_block; @@ -254,9 +262,33 @@ ciMethodBlocks::ciMethodBlocks(Arena *arena, ciMethod *meth): _method(meth), for(ciExceptionHandlerStream str(meth); !str.is_done(); str.next()) { ciExceptionHandler* handler = str.handler(); ciBlock *eb = make_block_at(handler->handler_bci()); - eb->set_handler(); + // + // Several exception handlers can have the same handler_bci: + // + // try { + // if (a.foo(b) < 0) { + // return a.error(); + // } + // return CoderResult.UNDERFLOW; + // } finally { + // a.position(b); + // } + // + // The try block above is divided into 2 exception blocks + // separated by 'areturn' bci. + // int ex_start = handler->start(); int ex_end = handler->limit(); + if (eb->is_handler()) { + // Extend old handler exception range to cover additional range. + int old_ex_start = eb->ex_start_bci(); + int old_ex_end = eb->ex_limit_bci(); + if (ex_start > old_ex_start) + ex_start = old_ex_start; + if (ex_end < old_ex_end) + ex_end = old_ex_end; + eb->clear_exception_handler(); // Reset exception information + } eb->set_exception_range(ex_start, ex_end); // ensure a block at the start of exception range and start of following code (void) make_block_at(ex_start); @@ -312,9 +344,10 @@ ciBlock::ciBlock(ciMethod *method, int index, ciMethodBlocks *mb, int start_bci) void ciBlock::set_exception_range(int start_bci, int limit_bci) { assert(limit_bci >= start_bci, "valid range"); - assert(is_handler(), "must be handler"); + assert(!is_handler() && _ex_start_bci == -1 && _ex_limit_bci == -1, "must not be handler"); _ex_start_bci = start_bci; _ex_limit_bci = limit_bci; + set_handler(); } #ifndef PRODUCT diff --git a/hotspot/src/share/vm/ci/ciMethodBlocks.hpp b/hotspot/src/share/vm/ci/ciMethodBlocks.hpp index a0db4bb6dcd..b4398f39f4a 100644 --- a/hotspot/src/share/vm/ci/ciMethodBlocks.hpp +++ b/hotspot/src/share/vm/ci/ciMethodBlocks.hpp @@ -110,9 +110,10 @@ public: void set_does_jsr() { _flags |= DoesJsr; } void clear_does_jsr() { _flags &= ~DoesJsr; } void set_does_ret() { _flags |= DoesRet; } - void clear_does_ret() { _flags |= DoesRet; } + void clear_does_ret() { _flags &= ~DoesRet; } void set_is_ret_target() { _flags |= RetTarget; } void set_has_handler() { _flags |= HasHandler; } + void clear_exception_handler() { _flags &= ~Handler; _ex_start_bci = -1; _ex_limit_bci = -1; } #ifndef PRODUCT ciMethod *method() const { return _method; } void dump(); From e06dedd2f1d176b64b44ec363ee00b5d9dbc821a Mon Sep 17 00:00:00 2001 From: Vladimir Kozlov Date: Thu, 21 Feb 2008 19:03:44 -0800 Subject: [PATCH 021/258] 6498878: client compiler crashes on windows when dealing with breakpoint instructions _is_compilable check prevents breakpoint bytecodes reversion when loading bytecodes for ciMethod. Reviewed-by: never --- hotspot/src/share/vm/ci/ciMethod.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/hotspot/src/share/vm/ci/ciMethod.cpp b/hotspot/src/share/vm/ci/ciMethod.cpp index f527b1fd6e6..2c6c5aa272d 100644 --- a/hotspot/src/share/vm/ci/ciMethod.cpp +++ b/hotspot/src/share/vm/ci/ciMethod.cpp @@ -146,7 +146,7 @@ void ciMethod::load_code() { memcpy(_code, me->code_base(), code_size()); // Revert any breakpoint bytecodes in ci's copy - if (_is_compilable && me->number_of_breakpoints() > 0) { + if (me->number_of_breakpoints() > 0) { BreakpointInfo* bp = instanceKlass::cast(me->method_holder())->breakpoints(); for (; bp != NULL; bp = bp->next()) { if (bp->match(me)) { From 63f1de52fc66114c4fbda6a2b4632b94b336be55 Mon Sep 17 00:00:00 2001 From: Jon Masamitsu Date: Fri, 22 Feb 2008 17:17:14 -0800 Subject: [PATCH 022/258] 6362677: Change parallel GC collector default number of parallel GC threads Use the same default number of GC threads as used by ParNewGC and ConcMarkSweepGC (i.e., the 5/8th rule). Reviewed-by: ysr, tonyp --- hotspot/src/cpu/sparc/vm/vm_version_sparc.cpp | 16 ++ hotspot/src/cpu/sparc/vm/vm_version_sparc.hpp | 8 + .../parallelScavenge/generationSizer.hpp | 8 +- hotspot/src/share/vm/runtime/arguments.cpp | 159 +++++++++--------- hotspot/src/share/vm/runtime/arguments.hpp | 4 +- hotspot/src/share/vm/runtime/globals.hpp | 3 + hotspot/src/share/vm/runtime/vm_version.cpp | 42 +++++ hotspot/src/share/vm/runtime/vm_version.hpp | 15 ++ 8 files changed, 174 insertions(+), 81 deletions(-) diff --git a/hotspot/src/cpu/sparc/vm/vm_version_sparc.cpp b/hotspot/src/cpu/sparc/vm/vm_version_sparc.cpp index 3d43a1b51a2..755df962f5d 100644 --- a/hotspot/src/cpu/sparc/vm/vm_version_sparc.cpp +++ b/hotspot/src/cpu/sparc/vm/vm_version_sparc.cpp @@ -28,6 +28,12 @@ int VM_Version::_features = VM_Version::unknown_m; const char* VM_Version::_features_str = ""; +bool VM_Version::is_niagara1_plus() { + // This is a placeholder until the real test is determined. + return is_niagara1() && + (os::processor_count() > maximum_niagara1_processor_count()); +} + void VM_Version::initialize() { _features = determine_features(); PrefetchCopyIntervalInBytes = prefetch_copy_interval_in_bytes(); @@ -160,3 +166,13 @@ void VM_Version::allow_all() { void VM_Version::revert() { _features = saved_features; } + +unsigned int VM_Version::calc_parallel_worker_threads() { + unsigned int result; + if (is_niagara1_plus()) { + result = nof_parallel_worker_threads(5, 16, 8); + } else { + result = nof_parallel_worker_threads(5, 8, 8); + } + return result; +} diff --git a/hotspot/src/cpu/sparc/vm/vm_version_sparc.hpp b/hotspot/src/cpu/sparc/vm/vm_version_sparc.hpp index 8eda5c3108d..d10845d0659 100644 --- a/hotspot/src/cpu/sparc/vm/vm_version_sparc.hpp +++ b/hotspot/src/cpu/sparc/vm/vm_version_sparc.hpp @@ -64,6 +64,11 @@ protected: static bool is_niagara1(int features) { return (features & niagara1_m) == niagara1_m; } + static int maximum_niagara1_processor_count() { return 32; } + // Returns true if the platform is in the niagara line and + // newer than the niagara1. + static bool is_niagara1_plus(); + public: // Initialization static void initialize(); @@ -129,4 +134,7 @@ public: // Override the Abstract_VM_Version implementation. static uint page_size_count() { return is_sun4v() ? 4 : 2; } + + // Calculates the number of parallel threads + static unsigned int calc_parallel_worker_threads(); }; diff --git a/hotspot/src/share/vm/gc_implementation/parallelScavenge/generationSizer.hpp b/hotspot/src/share/vm/gc_implementation/parallelScavenge/generationSizer.hpp index 9ca614c4823..4f284a5d572 100644 --- a/hotspot/src/share/vm/gc_implementation/parallelScavenge/generationSizer.hpp +++ b/hotspot/src/share/vm/gc_implementation/parallelScavenge/generationSizer.hpp @@ -39,10 +39,10 @@ class GenerationSizer : public TwoGenerationCollectorPolicy { // If the user hasn't explicitly set the number of worker // threads, set the count. - if (ParallelGCThreads == 0) { - assert(UseParallelGC, "Setting ParallelGCThreads without UseParallelGC"); - ParallelGCThreads = os::active_processor_count(); - } + assert(UseSerialGC || + !FLAG_IS_DEFAULT(ParallelGCThreads) || + (ParallelGCThreads > 0), + "ParallelGCThreads should be set before flag initialization"); // The survivor ratio's are calculated "raw", unlike the // default gc, which adds 2 to the ratio value. We need to diff --git a/hotspot/src/share/vm/runtime/arguments.cpp b/hotspot/src/share/vm/runtime/arguments.cpp index 5d0329ad046..0e631006212 100644 --- a/hotspot/src/share/vm/runtime/arguments.cpp +++ b/hotspot/src/share/vm/runtime/arguments.cpp @@ -924,10 +924,18 @@ static void no_shared_spaces() { void Arguments::set_parnew_gc_flags() { assert(!UseSerialGC && !UseParallelGC, "control point invariant"); + // Turn off AdaptiveSizePolicy by default for parnew until it is + // complete. + if (UseParNewGC && + FLAG_IS_DEFAULT(UseAdaptiveSizePolicy)) { + FLAG_SET_DEFAULT(UseAdaptiveSizePolicy, false); + } + if (FLAG_IS_DEFAULT(UseParNewGC) && ParallelGCThreads > 1) { FLAG_SET_DEFAULT(UseParNewGC, true); } else if (UseParNewGC && ParallelGCThreads == 0) { - FLAG_SET_DEFAULT(ParallelGCThreads, nof_parallel_gc_threads()); + FLAG_SET_DEFAULT(ParallelGCThreads, + Abstract_VM_Version::parallel_worker_threads()); if (FLAG_IS_DEFAULT(ParallelGCThreads) && ParallelGCThreads == 1) { FLAG_SET_DEFAULT(UseParNewGC, false); } @@ -956,25 +964,6 @@ void Arguments::set_parnew_gc_flags() { } } -// CAUTION: this code is currently shared by UseParallelGC, UseParNewGC and -// UseconcMarkSweepGC. Further tuning of individual collectors might -// dictate refinement on a per-collector basis. -int Arguments::nof_parallel_gc_threads() { - if (FLAG_IS_DEFAULT(ParallelGCThreads)) { - // For very large machines, there are diminishing returns - // for large numbers of worker threads. Instead of - // hogging the whole system, use 5/8ths of a worker for every - // processor after the first 8. For example, on a 72 cpu - // machine use 8 + (72 - 8) * (5/8) == 48 worker threads. - // This is just a start and needs further tuning and study in - // Tiger. - int ncpus = os::active_processor_count(); - return (ncpus <= 8) ? ncpus : 3 + ((ncpus * 5) / 8); - } else { - return ParallelGCThreads; - } -} - // Adjust some sizes to suit CMS and/or ParNew needs; these work well on // sparc/solaris for certain applications, but would gain from // further optimization and tuning efforts, and would almost @@ -984,26 +973,24 @@ void Arguments::set_cms_and_parnew_gc_flags() { return; } + assert(UseConcMarkSweepGC, "CMS is expected to be on here"); + // If we are using CMS, we prefer to UseParNewGC, // unless explicitly forbidden. - if (UseConcMarkSweepGC && !UseParNewGC && FLAG_IS_DEFAULT(UseParNewGC)) { - FLAG_SET_DEFAULT(UseParNewGC, true); + if (!UseParNewGC && FLAG_IS_DEFAULT(UseParNewGC)) { + FLAG_SET_ERGO(bool, UseParNewGC, true); } // Turn off AdaptiveSizePolicy by default for cms until it is - // complete. Also turn it off in general if the - // parnew collector has been selected. - if ((UseConcMarkSweepGC || UseParNewGC) && - FLAG_IS_DEFAULT(UseAdaptiveSizePolicy)) { + // complete. + if (FLAG_IS_DEFAULT(UseAdaptiveSizePolicy)) { FLAG_SET_DEFAULT(UseAdaptiveSizePolicy, false); } // In either case, adjust ParallelGCThreads and/or UseParNewGC // as needed. - set_parnew_gc_flags(); - - if (!UseConcMarkSweepGC) { - return; + if (UseParNewGC) { + set_parnew_gc_flags(); } // Now make adjustments for CMS @@ -1147,17 +1134,11 @@ void Arguments::set_ergonomics_flags() { FLAG_IS_DEFAULT(UseParallelGC)) { if (should_auto_select_low_pause_collector()) { FLAG_SET_ERGO(bool, UseConcMarkSweepGC, true); - set_cms_and_parnew_gc_flags(); } else { FLAG_SET_ERGO(bool, UseParallelGC, true); } no_shared_spaces(); } - - // This is here because the parallel collector could - // have been selected so this initialization should - // still be done. - set_parallel_gc_flags(); } } @@ -1170,6 +1151,9 @@ void Arguments::set_parallel_gc_flags() { // If no heap maximum was requested explicitly, use some reasonable fraction // of the physical memory, up to a maximum of 1GB. if (UseParallelGC) { + FLAG_SET_ERGO(uintx, ParallelGCThreads, + Abstract_VM_Version::parallel_worker_threads()); + if (FLAG_IS_DEFAULT(MaxHeapSize)) { const uint64_t reasonable_fraction = os::physical_memory() / DefaultMaxRAMFraction; @@ -1312,6 +1296,31 @@ static bool verify_serial_gc_flags() { UseParallelOldGC)); } +// Check consistency of GC selection +bool Arguments::check_gc_consistency() { + bool status = true; + // Ensure that the user has not selected conflicting sets + // of collectors. [Note: this check is merely a user convenience; + // collectors over-ride each other so that only a non-conflicting + // set is selected; however what the user gets is not what they + // may have expected from the combination they asked for. It's + // better to reduce user confusion by not allowing them to + // select conflicting combinations. + uint i = 0; + if (UseSerialGC) i++; + if (UseConcMarkSweepGC || UseParNewGC) i++; + if (UseParallelGC || UseParallelOldGC) i++; + if (i > 1) { + jio_fprintf(defaultStream::error_stream(), + "Conflicting collector combinations in option list; " + "please refer to the release notes for the combinations " + "allowed\n"); + status = false; + } + + return status; +} + // Check the consistency of vm_init_args bool Arguments::check_vm_args_consistency() { // Method for adding checks for flag consistency. @@ -1354,14 +1363,14 @@ bool Arguments::check_vm_args_consistency() { status = false; } - status &= verify_percentage(MaxLiveObjectEvacuationRatio, + status = status && verify_percentage(MaxLiveObjectEvacuationRatio, "MaxLiveObjectEvacuationRatio"); - status &= verify_percentage(AdaptiveSizePolicyWeight, + status = status && verify_percentage(AdaptiveSizePolicyWeight, "AdaptiveSizePolicyWeight"); - status &= verify_percentage(AdaptivePermSizeWeight, "AdaptivePermSizeWeight"); - status &= verify_percentage(ThresholdTolerance, "ThresholdTolerance"); - status &= verify_percentage(MinHeapFreeRatio, "MinHeapFreeRatio"); - status &= verify_percentage(MaxHeapFreeRatio, "MaxHeapFreeRatio"); + status = status && verify_percentage(AdaptivePermSizeWeight, "AdaptivePermSizeWeight"); + status = status && verify_percentage(ThresholdTolerance, "ThresholdTolerance"); + status = status && verify_percentage(MinHeapFreeRatio, "MinHeapFreeRatio"); + status = status && verify_percentage(MaxHeapFreeRatio, "MaxHeapFreeRatio"); if (MinHeapFreeRatio > MaxHeapFreeRatio) { jio_fprintf(defaultStream::error_stream(), @@ -1377,14 +1386,14 @@ bool Arguments::check_vm_args_consistency() { MarkSweepAlwaysCompactCount = 1; // Move objects every gc. } - status &= verify_percentage(GCHeapFreeLimit, "GCHeapFreeLimit"); - status &= verify_percentage(GCTimeLimit, "GCTimeLimit"); + status = status && verify_percentage(GCHeapFreeLimit, "GCHeapFreeLimit"); + status = status && verify_percentage(GCTimeLimit, "GCTimeLimit"); if (GCTimeLimit == 100) { // Turn off gc-overhead-limit-exceeded checks FLAG_SET_DEFAULT(UseGCOverheadLimit, false); } - status &= verify_percentage(GCHeapFreeLimit, "GCHeapFreeLimit"); + status = status && verify_percentage(GCHeapFreeLimit, "GCHeapFreeLimit"); // Check user specified sharing option conflict with Parallel GC bool cannot_share = (UseConcMarkSweepGC || UseParallelGC || @@ -1402,24 +1411,7 @@ bool Arguments::check_vm_args_consistency() { } } - // Ensure that the user has not selected conflicting sets - // of collectors. [Note: this check is merely a user convenience; - // collectors over-ride each other so that only a non-conflicting - // set is selected; however what the user gets is not what they - // may have expected from the combination they asked for. It's - // better to reduce user confusion by not allowing them to - // select conflicting combinations. - uint i = 0; - if (UseSerialGC) i++; - if (UseConcMarkSweepGC || UseParNewGC) i++; - if (UseParallelGC || UseParallelOldGC) i++; - if (i > 1) { - jio_fprintf(defaultStream::error_stream(), - "Conflicting collector combinations in option list; " - "please refer to the release notes for the combinations " - "allowed\n"); - status = false; - } + status = status && check_gc_consistency(); if (_has_alloc_profile) { if (UseParallelGC || UseParallelOldGC) { @@ -1451,15 +1443,15 @@ bool Arguments::check_vm_args_consistency() { "allocation buffers\n(-XX:+UseTLAB).\n"); status = false; } else { - status &= verify_percentage(CMSIncrementalDutyCycle, + status = status && verify_percentage(CMSIncrementalDutyCycle, "CMSIncrementalDutyCycle"); - status &= verify_percentage(CMSIncrementalDutyCycleMin, + status = status && verify_percentage(CMSIncrementalDutyCycleMin, "CMSIncrementalDutyCycleMin"); - status &= verify_percentage(CMSIncrementalSafetyFactor, + status = status && verify_percentage(CMSIncrementalSafetyFactor, "CMSIncrementalSafetyFactor"); - status &= verify_percentage(CMSIncrementalOffset, + status = status && verify_percentage(CMSIncrementalOffset, "CMSIncrementalOffset"); - status &= verify_percentage(CMSExpAvgFactor, + status = status && verify_percentage(CMSExpAvgFactor, "CMSExpAvgFactor"); // If it was not set on the command line, set // CMSInitiatingOccupancyFraction to 1 so icms can initiate cycles early. @@ -2064,7 +2056,8 @@ jint Arguments::parse_each_vm_init_arg(const JavaVMInitArgs* args, // Enable parallel GC and adaptive generation sizing FLAG_SET_CMDLINE(bool, UseParallelGC, true); - FLAG_SET_DEFAULT(ParallelGCThreads, nof_parallel_gc_threads()); + FLAG_SET_DEFAULT(ParallelGCThreads, + Abstract_VM_Version::parallel_worker_threads()); // Encourage steady state memory management FLAG_SET_CMDLINE(uintx, ThresholdTolerance, 100); @@ -2451,15 +2444,25 @@ jint Arguments::parse(const JavaVMInitArgs* args) { no_shared_spaces(); #endif // KERNEL - // Set some flags for ParallelGC if needed. - set_parallel_gc_flags(); - - // Set some flags for CMS and/or ParNew collectors, as needed. - set_cms_and_parnew_gc_flags(); - // Set flags based on ergonomics. set_ergonomics_flags(); + // Check the GC selections again. + if (!check_gc_consistency()) { + return JNI_EINVAL; + } + + if (UseParallelGC) { + // Set some flags for ParallelGC if needed. + set_parallel_gc_flags(); + } else if (UseConcMarkSweepGC) { + // Set some flags for CMS + set_cms_and_parnew_gc_flags(); + } else if (UseParNewGC) { + // Set some flags for ParNew + set_parnew_gc_flags(); + } + #ifdef SERIALGC assert(verify_serial_gc_flags(), "SerialGC unset"); #endif // SERIALGC @@ -2479,6 +2482,12 @@ jint Arguments::parse(const JavaVMInitArgs* args) { CommandLineFlags::printSetFlags(); } +#ifdef ASSERT + if (PrintFlagsFinal) { + CommandLineFlags::printFlags(); + } +#endif + return JNI_OK; } diff --git a/hotspot/src/share/vm/runtime/arguments.hpp b/hotspot/src/share/vm/runtime/arguments.hpp index fc373c41dd0..b806f4800f8 100644 --- a/hotspot/src/share/vm/runtime/arguments.hpp +++ b/hotspot/src/share/vm/runtime/arguments.hpp @@ -291,8 +291,6 @@ class Arguments : AllStatic { static bool _CIDynamicCompilePriority; static intx _Tier2CompileThreshold; - // GC processing - static int nof_parallel_gc_threads(); // CMS/ParNew garbage collectors static void set_parnew_gc_flags(); static void set_cms_and_parnew_gc_flags(); @@ -385,6 +383,8 @@ class Arguments : AllStatic { public: // Parses the arguments static jint parse(const JavaVMInitArgs* args); + // Check for consistency in the selection of the garbage collector. + static bool check_gc_consistency(); // Check consistecy or otherwise of VM argument settings static bool check_vm_args_consistency(); // Used by os_solaris diff --git a/hotspot/src/share/vm/runtime/globals.hpp b/hotspot/src/share/vm/runtime/globals.hpp index c1e8fefeba9..80f9541bc39 100644 --- a/hotspot/src/share/vm/runtime/globals.hpp +++ b/hotspot/src/share/vm/runtime/globals.hpp @@ -1794,6 +1794,9 @@ class CommandLineFlags { "number of times a GC thread (minus the coordinator) " \ "will sleep while yielding before giving up and resuming GC") \ \ + notproduct(bool, PrintFlagsFinal, false, \ + "Print all command line flags after argument processing") \ + \ /* gc tracing */ \ manageable(bool, PrintGC, false, \ "Print message at garbage collect") \ diff --git a/hotspot/src/share/vm/runtime/vm_version.cpp b/hotspot/src/share/vm/runtime/vm_version.cpp index f5ee15ade86..9c335eb44b3 100644 --- a/hotspot/src/share/vm/runtime/vm_version.cpp +++ b/hotspot/src/share/vm/runtime/vm_version.cpp @@ -52,6 +52,8 @@ int Abstract_VM_Version::_vm_major_version = 0; int Abstract_VM_Version::_vm_minor_version = 0; int Abstract_VM_Version::_vm_build_number = 0; bool Abstract_VM_Version::_initialized = false; +int Abstract_VM_Version::_parallel_worker_threads = 0; +bool Abstract_VM_Version::_parallel_worker_threads_initialized = false; void Abstract_VM_Version::initialize() { if (_initialized) { @@ -210,3 +212,43 @@ void VM_Version_init() { } #endif } + +unsigned int Abstract_VM_Version::nof_parallel_worker_threads( + unsigned int num, + unsigned int den, + unsigned int switch_pt) { + if (FLAG_IS_DEFAULT(ParallelGCThreads)) { + assert(ParallelGCThreads == 0, "Default ParallelGCThreads is not 0"); + // For very large machines, there are diminishing returns + // for large numbers of worker threads. Instead of + // hogging the whole system, use a fraction of the workers for every + // processor after the first 8. For example, on a 72 cpu machine + // and a chosen fraction of 5/8 + // use 8 + (72 - 8) * (5/8) == 48 worker threads. + unsigned int ncpus = (unsigned int) os::active_processor_count(); + return (ncpus <= switch_pt) ? + ncpus : + (switch_pt + ((ncpus - switch_pt) * num) / den); + } else { + return ParallelGCThreads; + } +} + +unsigned int Abstract_VM_Version::calc_parallel_worker_threads() { + return nof_parallel_worker_threads(5, 8, 8); +} + + +// Does not set the _initialized flag since it is +// a global flag. +unsigned int Abstract_VM_Version::parallel_worker_threads() { + if (!_parallel_worker_threads_initialized) { + if (FLAG_IS_DEFAULT(ParallelGCThreads)) { + _parallel_worker_threads = VM_Version::calc_parallel_worker_threads(); + } else { + _parallel_worker_threads = ParallelGCThreads; + } + _parallel_worker_threads_initialized = true; + } + return _parallel_worker_threads; +} diff --git a/hotspot/src/share/vm/runtime/vm_version.hpp b/hotspot/src/share/vm/runtime/vm_version.hpp index 2f708e39db8..5a46f04fb1d 100644 --- a/hotspot/src/share/vm/runtime/vm_version.hpp +++ b/hotspot/src/share/vm/runtime/vm_version.hpp @@ -36,6 +36,12 @@ class Abstract_VM_Version: AllStatic { static int _vm_minor_version; static int _vm_build_number; static bool _initialized; + static int _parallel_worker_threads; + static bool _parallel_worker_threads_initialized; + + static unsigned int nof_parallel_worker_threads(unsigned int num, + unsigned int dem, + unsigned int switch_pt); public: static void initialize(); @@ -69,4 +75,13 @@ class Abstract_VM_Version: AllStatic { // subclasses should define new versions to hide this one as needed. Note // that the O/S may support more sizes, but at most this many are used. static uint page_size_count() { return 2; } + + // Returns the number of parallel threads to be used for VM + // work. If that number has not been calculated, do so and + // save it. Returns ParallelGCThreads if it is set on the + // command line. + static unsigned int parallel_worker_threads(); + // Calculates and returns the number of parallel threads. May + // be VM version specific. + static unsigned int calc_parallel_worker_threads(); }; From 0dd8f3e8c01bfe0c6550ebaa97b44b6e01aeac6c Mon Sep 17 00:00:00 2001 From: Vladimir Kozlov Date: Fri, 22 Feb 2008 17:55:13 -0800 Subject: [PATCH 023/258] 6650373: Assert in methodOopDesc::make_adapters() AdapterHandlerLibrary::get_create_adapter_index() returns incorrect value (-2) when CodeCache is full. Reviewed-by: sgoldman --- hotspot/src/share/vm/opto/output.cpp | 5 +---- .../src/share/vm/runtime/sharedRuntime.cpp | 20 ++++++++++++++++++- 2 files changed, 20 insertions(+), 5 deletions(-) diff --git a/hotspot/src/share/vm/opto/output.cpp b/hotspot/src/share/vm/opto/output.cpp index 7868ec2378f..690459e5f0b 100644 --- a/hotspot/src/share/vm/opto/output.cpp +++ b/hotspot/src/share/vm/opto/output.cpp @@ -921,11 +921,8 @@ static void turn_off_compiler(Compile* C) { // blown the code cache size. C->record_failure("excessive request to CodeCache"); } else { - UseInterpreter = true; - UseCompiler = false; - AlwaysCompileLoopMethods = false; + // Let CompilerBroker disable further compilations. C->record_failure("CodeCache is full"); - warning("CodeCache is full. Compiling has been disabled"); } } diff --git a/hotspot/src/share/vm/runtime/sharedRuntime.cpp b/hotspot/src/share/vm/runtime/sharedRuntime.cpp index cda256b74a3..4ae00d9556a 100644 --- a/hotspot/src/share/vm/runtime/sharedRuntime.cpp +++ b/hotspot/src/share/vm/runtime/sharedRuntime.cpp @@ -1839,7 +1839,25 @@ int AdapterHandlerLibrary::get_create_adapter_index(methodHandle method) { regs); B = BufferBlob::create(AdapterHandlerEntry::name, &buffer); - if (B == NULL) return -2; // Out of CodeCache space + if (B == NULL) { + // CodeCache is full, disable compilation + // Ought to log this but compile log is only per compile thread + // and we're some non descript Java thread. + UseInterpreter = true; + if (UseCompiler || AlwaysCompileLoopMethods ) { +#ifndef PRODUCT + warning("CodeCache is full. Compiler has been disabled"); + if (CompileTheWorld || ExitOnFullCodeCache) { + before_exit(JavaThread::current()); + exit_globals(); // will delete tty + vm_direct_exit(CompileTheWorld ? 0 : 1); + } +#endif + UseCompiler = false; + AlwaysCompileLoopMethods = false; + } + return 0; // Out of CodeCache space (_handlers[0] == NULL) + } entry->relocate(B->instructions_begin()); #ifndef PRODUCT // debugging suppport From 9f1a8ede80bc83d81c160cf9f598e2637ca56449 Mon Sep 17 00:00:00 2001 From: Vladimir Kozlov Date: Mon, 25 Feb 2008 15:05:44 -0800 Subject: [PATCH 024/258] 6633953: type2aelembytes{T_ADDRESS} should be 8 bytes in 64 bit VM T_ADDRESS size is defined as 'int' size (4 bytes) but C2 use it for raw pointers and as memory type for StoreP and LoadP nodes. Reviewed-by: jrose --- hotspot/src/cpu/sparc/vm/c1_LIRAssembler_sparc.cpp | 4 ++-- hotspot/src/cpu/sparc/vm/c1_LIRGenerator_sparc.cpp | 2 +- hotspot/src/cpu/x86/vm/c1_LIRAssembler_x86.cpp | 8 ++++---- hotspot/src/cpu/x86/vm/c1_LIRGenerator_x86.cpp | 2 +- hotspot/src/share/vm/c1/c1_LIR.cpp | 2 +- hotspot/src/share/vm/ci/ciField.hpp | 2 +- hotspot/src/share/vm/oops/arrayOop.hpp | 4 ++-- hotspot/src/share/vm/oops/klass.cpp | 2 +- hotspot/src/share/vm/opto/graphKit.cpp | 2 +- hotspot/src/share/vm/opto/library_call.cpp | 10 +++++----- hotspot/src/share/vm/opto/memnode.cpp | 2 +- hotspot/src/share/vm/opto/memnode.hpp | 8 +++++++- hotspot/src/share/vm/opto/superword.cpp | 5 +++-- hotspot/src/share/vm/opto/vectornode.cpp | 2 +- hotspot/src/share/vm/opto/vectornode.hpp | 6 +++--- hotspot/src/share/vm/services/heapDumper.cpp | 2 +- hotspot/src/share/vm/utilities/globalDefinitions.cpp | 10 ++++++++-- hotspot/src/share/vm/utilities/globalDefinitions.hpp | 11 ++++++++++- 18 files changed, 53 insertions(+), 31 deletions(-) diff --git a/hotspot/src/cpu/sparc/vm/c1_LIRAssembler_sparc.cpp b/hotspot/src/cpu/sparc/vm/c1_LIRAssembler_sparc.cpp index e594085505b..8436fb8561b 100644 --- a/hotspot/src/cpu/sparc/vm/c1_LIRAssembler_sparc.cpp +++ b/hotspot/src/cpu/sparc/vm/c1_LIRAssembler_sparc.cpp @@ -2037,7 +2037,7 @@ void LIR_Assembler::logic_op(LIR_Code code, LIR_Opr left, LIR_Opr right, LIR_Opr int LIR_Assembler::shift_amount(BasicType t) { - int elem_size = type2aelembytes[t]; + int elem_size = type2aelembytes(t); switch (elem_size) { case 1 : return 0; case 2 : return 1; @@ -2360,7 +2360,7 @@ void LIR_Assembler::emit_alloc_array(LIR_OpAllocArray* op) { op->tmp2()->as_register(), op->tmp3()->as_register(), arrayOopDesc::header_size(op->type()), - type2aelembytes[op->type()], + type2aelembytes(op->type()), op->klass()->as_register(), *op->stub()->entry()); } diff --git a/hotspot/src/cpu/sparc/vm/c1_LIRGenerator_sparc.cpp b/hotspot/src/cpu/sparc/vm/c1_LIRGenerator_sparc.cpp index 443551871fe..74bc5ecf3b4 100644 --- a/hotspot/src/cpu/sparc/vm/c1_LIRGenerator_sparc.cpp +++ b/hotspot/src/cpu/sparc/vm/c1_LIRGenerator_sparc.cpp @@ -179,7 +179,7 @@ LIR_Address* LIRGenerator::generate_address(LIR_Opr base, LIR_Opr index, LIR_Address* LIRGenerator::emit_array_address(LIR_Opr array_opr, LIR_Opr index_opr, BasicType type, bool needs_card_mark) { - int elem_size = type2aelembytes[type]; + int elem_size = type2aelembytes(type); int shift = exact_log2(elem_size); LIR_Opr base_opr; diff --git a/hotspot/src/cpu/x86/vm/c1_LIRAssembler_x86.cpp b/hotspot/src/cpu/x86/vm/c1_LIRAssembler_x86.cpp index e87d55ce228..7c632cbabcd 100644 --- a/hotspot/src/cpu/x86/vm/c1_LIRAssembler_x86.cpp +++ b/hotspot/src/cpu/x86/vm/c1_LIRAssembler_x86.cpp @@ -546,8 +546,8 @@ void LIR_Assembler::emit_string_compare(LIR_Opr arg0, LIR_Opr arg1, LIR_Opr dst, // set rsi.edi to the end of the arrays (arrays have same length) // negate the index - __ leal(rsi, Address(rsi, rax, Address::times_2, type2aelembytes[T_CHAR])); - __ leal(rdi, Address(rdi, rax, Address::times_2, type2aelembytes[T_CHAR])); + __ leal(rsi, Address(rsi, rax, Address::times_2, type2aelembytes(T_CHAR))); + __ leal(rdi, Address(rdi, rax, Address::times_2, type2aelembytes(T_CHAR))); __ negl(rax); // compare the strings in a loop @@ -1232,7 +1232,7 @@ void LIR_Assembler::prefetchw(LIR_Opr src) { NEEDS_CLEANUP; // This could be static? Address::ScaleFactor LIR_Assembler::array_element_size(BasicType type) const { - int elem_size = type2aelembytes[type]; + int elem_size = type2aelembytes(type); switch (elem_size) { case 1: return Address::times_1; case 2: return Address::times_2; @@ -2739,7 +2739,7 @@ void LIR_Assembler::emit_arraycopy(LIR_OpArrayCopy* op) { assert(default_type != NULL && default_type->is_array_klass() && default_type->is_loaded(), "must be true at this point"); - int elem_size = type2aelembytes[basic_type]; + int elem_size = type2aelembytes(basic_type); int shift_amount; Address::ScaleFactor scale; diff --git a/hotspot/src/cpu/x86/vm/c1_LIRGenerator_x86.cpp b/hotspot/src/cpu/x86/vm/c1_LIRGenerator_x86.cpp index a98d1b95416..7c4861d614e 100644 --- a/hotspot/src/cpu/x86/vm/c1_LIRGenerator_x86.cpp +++ b/hotspot/src/cpu/x86/vm/c1_LIRGenerator_x86.cpp @@ -151,7 +151,7 @@ LIR_Address* LIRGenerator::emit_array_address(LIR_Opr array_opr, LIR_Opr index_o LIR_Address* addr; if (index_opr->is_constant()) { - int elem_size = type2aelembytes[type]; + int elem_size = type2aelembytes(type); addr = new LIR_Address(array_opr, offset_in_bytes + index_opr->as_jint() * elem_size, type); } else { diff --git a/hotspot/src/share/vm/c1/c1_LIR.cpp b/hotspot/src/share/vm/c1/c1_LIR.cpp index 60e25387a71..46e725b5a14 100644 --- a/hotspot/src/share/vm/c1/c1_LIR.cpp +++ b/hotspot/src/share/vm/c1/c1_LIR.cpp @@ -105,7 +105,7 @@ LIR_Opr LIR_OprFact::dummy_value_type(ValueType* type) { LIR_Address::Scale LIR_Address::scale(BasicType type) { - int elem_size = type2aelembytes[type]; + int elem_size = type2aelembytes(type); switch (elem_size) { case 1: return LIR_Address::times_1; case 2: return LIR_Address::times_2; diff --git a/hotspot/src/share/vm/ci/ciField.hpp b/hotspot/src/share/vm/ci/ciField.hpp index 2498007f506..72a64c03a63 100644 --- a/hotspot/src/share/vm/ci/ciField.hpp +++ b/hotspot/src/share/vm/ci/ciField.hpp @@ -102,7 +102,7 @@ public: BasicType layout_type() { return type2field[(_type == NULL) ? T_OBJECT : _type->basic_type()]; } // How big is this field in memory? - int size_in_bytes() { return type2aelembytes[layout_type()]; } + int size_in_bytes() { return type2aelembytes(layout_type()); } // What is the offset of this field? int offset() { diff --git a/hotspot/src/share/vm/oops/arrayOop.hpp b/hotspot/src/share/vm/oops/arrayOop.hpp index e9bde1d6c8e..49fc566a90e 100644 --- a/hotspot/src/share/vm/oops/arrayOop.hpp +++ b/hotspot/src/share/vm/oops/arrayOop.hpp @@ -58,11 +58,11 @@ class arrayOopDesc : public oopDesc { // alignments. It gets the scale from the type2aelembytes array. static int32_t max_array_length(BasicType type) { assert(type >= 0 && type < T_CONFLICT, "wrong type"); - assert(type2aelembytes[type] != 0, "wrong type"); + assert(type2aelembytes(type) != 0, "wrong type"); // We use max_jint, since object_size is internally represented by an 'int' // This gives us an upper bound of max_jint words for the size of the oop. int32_t max_words = (max_jint - header_size(type) - 2); - int elembytes = (type == T_OBJECT) ? T_OBJECT_aelem_bytes : type2aelembytes[type]; + int elembytes = (type == T_OBJECT) ? T_OBJECT_aelem_bytes : type2aelembytes(type); jlong len = ((jlong)max_words * HeapWordSize) / elembytes; return (len > max_jint) ? max_jint : (int32_t)len; } diff --git a/hotspot/src/share/vm/oops/klass.cpp b/hotspot/src/share/vm/oops/klass.cpp index c21393ce5a0..33e800a3cd5 100644 --- a/hotspot/src/share/vm/oops/klass.cpp +++ b/hotspot/src/share/vm/oops/klass.cpp @@ -182,7 +182,7 @@ jint Klass::array_layout_helper(BasicType etype) { assert(etype >= T_BOOLEAN && etype <= T_OBJECT, "valid etype"); // Note that T_ARRAY is not allowed here. int hsize = arrayOopDesc::base_offset_in_bytes(etype); - int esize = type2aelembytes[etype]; + int esize = type2aelembytes(etype); bool isobj = (etype == T_OBJECT); int tag = isobj ? _lh_array_tag_obj_value : _lh_array_tag_type_value; int lh = array_layout_helper(tag, hsize, etype, exact_log2(esize)); diff --git a/hotspot/src/share/vm/opto/graphKit.cpp b/hotspot/src/share/vm/opto/graphKit.cpp index 642883ad64b..45471f29fde 100644 --- a/hotspot/src/share/vm/opto/graphKit.cpp +++ b/hotspot/src/share/vm/opto/graphKit.cpp @@ -1447,7 +1447,7 @@ Node* GraphKit::store_oop_to_unknown(Node* ctl, //-------------------------array_element_address------------------------- Node* GraphKit::array_element_address(Node* ary, Node* idx, BasicType elembt, const TypeInt* sizetype) { - uint shift = exact_log2(type2aelembytes[elembt]); + uint shift = exact_log2(type2aelembytes(elembt)); uint header = arrayOopDesc::base_offset_in_bytes(elembt); // short-circuit a common case (saves lots of confusing waste motion) diff --git a/hotspot/src/share/vm/opto/library_call.cpp b/hotspot/src/share/vm/opto/library_call.cpp index d78f62d4038..e69e2d9e68b 100644 --- a/hotspot/src/share/vm/opto/library_call.cpp +++ b/hotspot/src/share/vm/opto/library_call.cpp @@ -2097,7 +2097,7 @@ bool LibraryCallKit::inline_unsafe_CAS(BasicType type) { int type_words = type2size[type]; // Cannot inline wide CAS on machines that don't support it natively - if (type2aelembytes[type] > BytesPerInt && !VM_Version::supports_cx8()) + if (type2aelembytes(type) > BytesPerInt && !VM_Version::supports_cx8()) return false; C->set_has_unsafe_access(true); // Mark eventual nmethod as "unsafe". @@ -3975,7 +3975,7 @@ address LibraryCallKit::basictype2arraycopy(BasicType t, // both indices are constants int s_offs = src_offset_inttype->get_con(); int d_offs = dest_offset_inttype->get_con(); - int element_size = type2aelembytes[t]; + int element_size = type2aelembytes(t); aligned = ((arrayOopDesc::base_offset_in_bytes(t) + s_offs * element_size) % HeapWordSize == 0) && ((arrayOopDesc::base_offset_in_bytes(t) + d_offs * element_size) % HeapWordSize == 0); if (s_offs >= d_offs) disjoint = true; @@ -4389,7 +4389,7 @@ LibraryCallKit::generate_arraycopy(const TypePtr* adr_type, if (alloc != NULL && use_ReduceInitialCardMarks()) { // If we do not need card marks, copy using the jint or jlong stub. copy_type = LP64_ONLY(T_LONG) NOT_LP64(T_INT); - assert(type2aelembytes[basic_elem_type] == type2aelembytes[copy_type], + assert(type2aelembytes(basic_elem_type) == type2aelembytes(copy_type), "sizes agree"); } } @@ -4659,7 +4659,7 @@ LibraryCallKit::generate_clear_array(const TypePtr* adr_type, Node* mem = memory(adr_type); // memory slice to operate on // scaling and rounding of indexes: - int scale = exact_log2(type2aelembytes[basic_elem_type]); + int scale = exact_log2(type2aelembytes(basic_elem_type)); int abase = arrayOopDesc::base_offset_in_bytes(basic_elem_type); int clear_low = (-1 << scale) & (BytesPerInt - 1); int bump_bit = (-1 << scale) & BytesPerInt; @@ -4753,7 +4753,7 @@ LibraryCallKit::generate_block_arraycopy(const TypePtr* adr_type, Node* dest, Node* dest_offset, Node* dest_size) { // See if there is an advantage from block transfer. - int scale = exact_log2(type2aelembytes[basic_elem_type]); + int scale = exact_log2(type2aelembytes(basic_elem_type)); if (scale >= LogBytesPerLong) return false; // it is already a block transfer diff --git a/hotspot/src/share/vm/opto/memnode.cpp b/hotspot/src/share/vm/opto/memnode.cpp index b65a03bbf3b..28f37d9a8a5 100644 --- a/hotspot/src/share/vm/opto/memnode.cpp +++ b/hotspot/src/share/vm/opto/memnode.cpp @@ -889,7 +889,7 @@ Node* LoadNode::eliminate_autobox(PhaseGVN* phase) { int shift = -1; Node* cache = NULL; if (is_autobox_cache(atp)) { - shift = exact_log2(type2aelembytes[T_OBJECT]); + shift = exact_log2(type2aelembytes(T_OBJECT)); cache = AddPNode::Ideal_base_and_offset(load_base->in(Address), phase, cache_offset); } if (cache != NULL && base->in(Address)->is_AddP()) { diff --git a/hotspot/src/share/vm/opto/memnode.hpp b/hotspot/src/share/vm/opto/memnode.hpp index 34f36a27118..505cbdf979f 100644 --- a/hotspot/src/share/vm/opto/memnode.hpp +++ b/hotspot/src/share/vm/opto/memnode.hpp @@ -97,7 +97,13 @@ public: // What is the type of the value in memory? (T_VOID mean "unspecified".) virtual BasicType memory_type() const = 0; - virtual int memory_size() const { return type2aelembytes[memory_type()]; } + virtual int memory_size() const { +#ifdef ASSERT + return type2aelembytes(memory_type(), true); +#else + return type2aelembytes(memory_type()); +#endif + } // Search through memory states which precede this node (load or store). // Look for an exact match for the address, with no intervening diff --git a/hotspot/src/share/vm/opto/superword.cpp b/hotspot/src/share/vm/opto/superword.cpp index b1467fc9e05..9b9ffdd0241 100644 --- a/hotspot/src/share/vm/opto/superword.cpp +++ b/hotspot/src/share/vm/opto/superword.cpp @@ -159,7 +159,8 @@ void SuperWord::find_adjacent_refs() { Node_List memops; for (int i = 0; i < _block.length(); i++) { Node* n = _block.at(i); - if (n->is_Mem() && in_bb(n)) { + if (n->is_Mem() && in_bb(n) && + is_java_primitive(n->as_Mem()->memory_type())) { int align = memory_alignment(n->as_Mem(), 0); if (align != bottom_align) { memops.push(n); @@ -570,7 +571,7 @@ void SuperWord::set_alignment(Node* s1, Node* s2, int align) { int SuperWord::data_size(Node* s) { const Type* t = velt_type(s); BasicType bt = t->array_element_basic_type(); - int bsize = type2aelembytes[bt]; + int bsize = type2aelembytes(bt); assert(bsize != 0, "valid size"); return bsize; } diff --git a/hotspot/src/share/vm/opto/vectornode.cpp b/hotspot/src/share/vm/opto/vectornode.cpp index f137516052d..7a581282d9c 100644 --- a/hotspot/src/share/vm/opto/vectornode.cpp +++ b/hotspot/src/share/vm/opto/vectornode.cpp @@ -135,7 +135,7 @@ Node* PackNode::binaryTreePack(Compile* C, int lo, int hi) { int mid = lo + ct/2; Node* n1 = ct == 2 ? in(lo) : binaryTreePack(C, lo, mid); Node* n2 = ct == 2 ? in(lo+1) : binaryTreePack(C, mid, hi ); - int rslt_bsize = ct * type2aelembytes[elt_basic_type()]; + int rslt_bsize = ct * type2aelembytes(elt_basic_type()); if (bottom_type()->is_floatingpoint()) { switch (rslt_bsize) { case 8: return new (C, 3) PackFNode(n1, n2); diff --git a/hotspot/src/share/vm/opto/vectornode.hpp b/hotspot/src/share/vm/opto/vectornode.hpp index c0638677780..ed442b973ba 100644 --- a/hotspot/src/share/vm/opto/vectornode.hpp +++ b/hotspot/src/share/vm/opto/vectornode.hpp @@ -48,7 +48,7 @@ class VectorNode : public Node { uint length() const { return _length; } // Vector length static uint max_vlen(BasicType bt) { // max vector length - return (uint)(Matcher::vector_width_in_bytes() / type2aelembytes[bt]); + return (uint)(Matcher::vector_width_in_bytes() / type2aelembytes(bt)); } // Element and vector type @@ -392,7 +392,7 @@ class VectorLoadNode : public LoadNode { virtual uint ideal_reg() const { return Matcher::vector_ideal_reg(); } virtual BasicType memory_type() const { return T_VOID; } - virtual int memory_size() const { return length()*type2aelembytes[elt_basic_type()]; } + virtual int memory_size() const { return length()*type2aelembytes(elt_basic_type()); } // Vector opcode from scalar opcode static int opcode(int sopc, uint vlen); @@ -620,7 +620,7 @@ class VectorStoreNode : public StoreNode { virtual uint ideal_reg() const { return Matcher::vector_ideal_reg(); } virtual BasicType memory_type() const { return T_VOID; } - virtual int memory_size() const { return length()*type2aelembytes[elt_basic_type()]; } + virtual int memory_size() const { return length()*type2aelembytes(elt_basic_type()); } // Vector opcode from scalar opcode static int opcode(int sopc, uint vlen); diff --git a/hotspot/src/share/vm/services/heapDumper.cpp b/hotspot/src/share/vm/services/heapDumper.cpp index cdd79a61817..afb7d9cbb14 100644 --- a/hotspot/src/share/vm/services/heapDumper.cpp +++ b/hotspot/src/share/vm/services/heapDumper.cpp @@ -997,7 +997,7 @@ void DumperSupport::dump_prim_array(DumpWriter* writer, typeArrayOop array) { } // If the byte ordering is big endian then we can copy most types directly - int length_in_bytes = array->length() * type2aelembytes[type]; + int length_in_bytes = array->length() * type2aelembytes(type); assert(length_in_bytes > 0, "nothing to copy"); switch (type) { diff --git a/hotspot/src/share/vm/utilities/globalDefinitions.cpp b/hotspot/src/share/vm/utilities/globalDefinitions.cpp index 12edbeff792..89373ef2894 100644 --- a/hotspot/src/share/vm/utilities/globalDefinitions.cpp +++ b/hotspot/src/share/vm/utilities/globalDefinitions.cpp @@ -214,7 +214,7 @@ BasicType type2wfield[T_CONFLICT+1] = { }; -int type2aelembytes[T_CONFLICT+1] = { +int _type2aelembytes[T_CONFLICT+1] = { 0, // 0 0, // 1 0, // 2 @@ -230,10 +230,16 @@ int type2aelembytes[T_CONFLICT+1] = { T_OBJECT_aelem_bytes, // T_OBJECT = 12, T_ARRAY_aelem_bytes, // T_ARRAY = 13, 0, // T_VOID = 14, - T_INT_aelem_bytes, // T_ADDRESS = 15, + T_OBJECT_aelem_bytes, // T_ADDRESS = 15, 0 // T_CONFLICT = 16, }; +#ifdef ASSERT +int type2aelembytes(BasicType t, bool allow_address) { + assert(allow_address || t != T_ADDRESS, " "); + return _type2aelembytes[t]; +} +#endif // Support for 64-bit integer arithmetic diff --git a/hotspot/src/share/vm/utilities/globalDefinitions.hpp b/hotspot/src/share/vm/utilities/globalDefinitions.hpp index 460cd1f345e..0feceb5deee 100644 --- a/hotspot/src/share/vm/utilities/globalDefinitions.hpp +++ b/hotspot/src/share/vm/utilities/globalDefinitions.hpp @@ -392,6 +392,10 @@ enum BasicType { T_ILLEGAL = 99 }; +inline bool is_java_primitive(BasicType t) { + return T_BOOLEAN <= t && t <= T_LONG; +} + // Convert a char from a classfile signature to a BasicType inline BasicType char2type(char c) { switch( c ) { @@ -464,7 +468,12 @@ enum ArrayElementSize { T_VOID_aelem_bytes = 0 }; -extern int type2aelembytes[T_CONFLICT+1]; // maps a BasicType to nof bytes used by its array element +extern int _type2aelembytes[T_CONFLICT+1]; // maps a BasicType to nof bytes used by its array element +#ifdef ASSERT +extern int type2aelembytes(BasicType t, bool allow_address = false); // asserts +#else +inline int type2aelembytes(BasicType t) { return _type2aelembytes[t]; } +#endif // JavaValue serves as a container for arbitrary Java values. From 51bf19209d6a425cd0a0ef2046df7282636e57d3 Mon Sep 17 00:00:00 2001 From: "Y. Srinivas Ramakrishna" Date: Tue, 26 Feb 2008 15:57:49 -0800 Subject: [PATCH 025/258] 6621728: Heap inspection should not crash in the face of C-heap exhaustion Deal more gracefully with situations where C-heap scratch space cannot be had Reviewed-by: jmasa --- .../src/share/vm/memory/heapInspection.cpp | 99 +++++++++++++------ .../src/share/vm/memory/heapInspection.hpp | 3 +- 2 files changed, 70 insertions(+), 32 deletions(-) diff --git a/hotspot/src/share/vm/memory/heapInspection.cpp b/hotspot/src/share/vm/memory/heapInspection.cpp index ac8aa641fc2..9fc47755608 100644 --- a/hotspot/src/share/vm/memory/heapInspection.cpp +++ b/hotspot/src/share/vm/memory/heapInspection.cpp @@ -65,7 +65,7 @@ void KlassInfoEntry::print_on(outputStream* st) const { name = ""; } // simplify the formatting (ILP32 vs LP64) - always cast the numbers to 64-bit - st->print_cr("%13" FORMAT64_MODIFIER "d %13" FORMAT64_MODIFIER "u %s", + st->print_cr(INT64_FORMAT_W(13) " " UINT64_FORMAT_W(13) " %s", (jlong) _instance_count, (julong) _instance_words * HeapWordSize, name); @@ -80,7 +80,10 @@ KlassInfoEntry* KlassInfoBucket::lookup(const klassOop k) { elt = elt->next(); } elt = new KlassInfoEntry(k, list()); - set_list(elt); + // We may be out of space to allocate the new entry. + if (elt != NULL) { + set_list(elt); + } return elt; } @@ -103,21 +106,25 @@ void KlassInfoBucket::empty() { } KlassInfoTable::KlassInfoTable(int size, HeapWord* ref) { - _size = size; + _size = 0; _ref = ref; - _buckets = NEW_C_HEAP_ARRAY(KlassInfoBucket, _size); - - for (int index = 0; index < _size; index++) { - _buckets[index].initialize(); + _buckets = NEW_C_HEAP_ARRAY(KlassInfoBucket, size); + if (_buckets != NULL) { + _size = size; + for (int index = 0; index < _size; index++) { + _buckets[index].initialize(); + } } } KlassInfoTable::~KlassInfoTable() { - for (int index = 0; index < _size; index++) { - _buckets[index].empty(); + if (_buckets != NULL) { + for (int index = 0; index < _size; index++) { + _buckets[index].empty(); + } + FREE_C_HEAP_ARRAY(KlassInfoBucket, _buckets); + _size = 0; } - FREE_C_HEAP_ARRAY(KlassInfoBucket, _buckets); - _size = 0; } uint KlassInfoTable::hash(klassOop p) { @@ -127,19 +134,32 @@ uint KlassInfoTable::hash(klassOop p) { KlassInfoEntry* KlassInfoTable::lookup(const klassOop k) { uint idx = hash(k) % _size; + assert(_buckets != NULL, "Allocation failure should have been caught"); KlassInfoEntry* e = _buckets[idx].lookup(k); - assert(k == e->klass(), "must be equal"); + // Lookup may fail if this is a new klass for which we + // could not allocate space for an new entry. + assert(e == NULL || k == e->klass(), "must be equal"); return e; } -void KlassInfoTable::record_instance(const oop obj) { +// Return false if the entry could not be recorded on account +// of running out of space required to create a new entry. +bool KlassInfoTable::record_instance(const oop obj) { klassOop k = obj->klass(); KlassInfoEntry* elt = lookup(k); - elt->set_count(elt->count() + 1); - elt->set_words(elt->words() + obj->size()); + // elt may be NULL if it's a new klass for which we + // could not allocate space for a new entry in the hashtable. + if (elt != NULL) { + elt->set_count(elt->count() + 1); + elt->set_words(elt->words() + obj->size()); + return true; + } else { + return false; + } } void KlassInfoTable::iterate(KlassInfoClosure* cic) { + assert(_size == 0 || _buckets != NULL, "Allocation failure should have been caught"); for (int index = 0; index < _size; index++) { _buckets[index].iterate(cic); } @@ -176,7 +196,7 @@ void KlassInfoHisto::print_elements(outputStream* st) const { total += elements()->at(i)->count(); totalw += elements()->at(i)->words(); } - st->print_cr("Total %13" FORMAT64_MODIFIER "d %13" FORMAT64_MODIFIER "u", + st->print_cr("Total " INT64_FORMAT_W(13) " " UINT64_FORMAT_W(13), total, totalw * HeapWordSize); } @@ -199,12 +219,18 @@ class HistoClosure : public KlassInfoClosure { class RecordInstanceClosure : public ObjectClosure { private: KlassInfoTable* _cit; + size_t _missed_count; public: - RecordInstanceClosure(KlassInfoTable* cit) : _cit(cit) {} + RecordInstanceClosure(KlassInfoTable* cit) : + _cit(cit), _missed_count(0) {} void do_object(oop obj) { - _cit->record_instance(obj); + if (!_cit->record_instance(obj)) { + _missed_count++; + } } + + size_t missed_count() { return _missed_count; } }; void HeapInspection::heap_inspection(outputStream* st) { @@ -230,21 +256,32 @@ void HeapInspection::heap_inspection(outputStream* st) { ShouldNotReachHere(); // Unexpected heap kind for this op } // Collect klass instance info - - // Iterate over objects in the heap KlassInfoTable cit(KlassInfoTable::cit_size, ref); - RecordInstanceClosure ric(&cit); - Universe::heap()->object_iterate(&ric); + if (!cit.allocation_failed()) { + // Iterate over objects in the heap + RecordInstanceClosure ric(&cit); + Universe::heap()->object_iterate(&ric); - // Sort and print klass instance info - KlassInfoHisto histo("\n" - " num #instances #bytes class name\n" - "----------------------------------------------", - KlassInfoHisto::histo_initial_size); - HistoClosure hc(&histo); - cit.iterate(&hc); - histo.sort(); - histo.print_on(st); + // Report if certain classes are not counted because of + // running out of C-heap for the histogram. + size_t missed_count = ric.missed_count(); + if (missed_count != 0) { + st->print_cr("WARNING: Ran out of C-heap; undercounted " SIZE_FORMAT + " total instances in data below", + missed_count); + } + // Sort and print klass instance info + KlassInfoHisto histo("\n" + " num #instances #bytes class name\n" + "----------------------------------------------", + KlassInfoHisto::histo_initial_size); + HistoClosure hc(&histo); + cit.iterate(&hc); + histo.sort(); + histo.print_on(st); + } else { + st->print_cr("WARNING: Ran out of C-heap; histogram not generated"); + } st->flush(); if (Universe::heap()->kind() == CollectedHeap::GenCollectedHeap) { diff --git a/hotspot/src/share/vm/memory/heapInspection.hpp b/hotspot/src/share/vm/memory/heapInspection.hpp index d56f8518c5f..f235d510b06 100644 --- a/hotspot/src/share/vm/memory/heapInspection.hpp +++ b/hotspot/src/share/vm/memory/heapInspection.hpp @@ -98,8 +98,9 @@ class KlassInfoTable: public StackObj { }; KlassInfoTable(int size, HeapWord* ref); ~KlassInfoTable(); - void record_instance(const oop obj); + bool record_instance(const oop obj); void iterate(KlassInfoClosure* cic); + bool allocation_failed() { return _buckets == NULL; } }; class KlassInfoHisto : public StackObj { From 73fa03eafcf9f01c6497091425c92a9975c20860 Mon Sep 17 00:00:00 2001 From: John R Rose Date: Wed, 27 Feb 2008 00:23:37 -0800 Subject: [PATCH 026/258] 6610906: inexplicable IncompatibleClassChangeError Dependency check must treat polymorphic interfaces consistently Reviewed-by: kvn, never, sgoldman --- hotspot/src/share/vm/code/dependencies.cpp | 8 ++++++++ hotspot/src/share/vm/code/nmethod.cpp | 2 +- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/hotspot/src/share/vm/code/dependencies.cpp b/hotspot/src/share/vm/code/dependencies.cpp index 75d0546642e..3ca91958270 100644 --- a/hotspot/src/share/vm/code/dependencies.cpp +++ b/hotspot/src/share/vm/code/dependencies.cpp @@ -882,6 +882,14 @@ klassOop ClassHierarchyWalker::find_witness_in(DepChange& changes, // Must not move the class hierarchy during this check: assert_locked_or_safepoint(Compile_lock); + int nof_impls = instanceKlass::cast(context_type)->nof_implementors(); + if (nof_impls > 1) { + // Avoid this case: *I.m > { A.m, C }; B.m > C + // %%% Until this is fixed more systematically, bail out. + // See corresponding comment in find_witness_anywhere. + return context_type; + } + assert(!is_participant(new_type), "only old classes are participants"); if (participants_hide_witnesses) { // If the new type is a subtype of a participant, we are done. diff --git a/hotspot/src/share/vm/code/nmethod.cpp b/hotspot/src/share/vm/code/nmethod.cpp index 89a3f0d1612..518c0ce717d 100644 --- a/hotspot/src/share/vm/code/nmethod.cpp +++ b/hotspot/src/share/vm/code/nmethod.cpp @@ -1971,7 +1971,7 @@ void nmethod::print_dependencies() { if (ctxk != NULL) { Klass* k = Klass::cast(ctxk); if (k->oop_is_instance() && ((instanceKlass*)k)->is_dependent_nmethod(this)) { - tty->print(" [nmethod<=klass]%s", k->external_name()); + tty->print_cr(" [nmethod<=klass]%s", k->external_name()); } } deps.log_dependency(); // put it into the xml log also From f235d989d0bd983448c1ecdda9196a0711b70e43 Mon Sep 17 00:00:00 2001 From: Coleen Phillimore Date: Wed, 27 Feb 2008 13:55:58 -0500 Subject: [PATCH 027/258] 6549844: Wording problems in "An unexpected error ..." Changed wording to "A fatal error.." also don't claim it's not VM bug if in hotspot compilers (Java thread in native). Reviewed-by: jjh, sbohne, jrose, never --- hotspot/src/share/vm/utilities/vmError.cpp | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/hotspot/src/share/vm/utilities/vmError.cpp b/hotspot/src/share/vm/utilities/vmError.cpp index 17dfb6b0c65..81b95462553 100644 --- a/hotspot/src/share/vm/utilities/vmError.cpp +++ b/hotspot/src/share/vm/utilities/vmError.cpp @@ -170,7 +170,8 @@ static void print_bug_submit_message(outputStream *out, Thread *thread) { out->print_raw_cr(Arguments::java_vendor_url_bug()); // If the crash is in native code, encourage user to submit a bug to the // provider of that code. - if (thread && thread->is_Java_thread()) { + if (thread && thread->is_Java_thread() && + !thread->is_hidden_from_external_view()) { JavaThread* jt = (JavaThread*)thread; if (jt->thread_state() == _thread_in_native) { out->print_cr("# The crash happened outside the Java Virtual Machine in native code.\n# See problematic frame for where to report the bug."); @@ -249,10 +250,10 @@ void VMError::report(outputStream* st) { BEGIN - STEP(10, "(printing unexpected error message)") + STEP(10, "(printing fatal error message)") st->print_cr("#"); - st->print_cr("# An unexpected error has been detected by Java Runtime Environment:"); + st->print_cr("# A fatal error has been detected by the Java Runtime Environment:"); STEP(15, "(printing type of error)") From 7be6246821e3297a1d0b59b3144e81429e15a896 Mon Sep 17 00:00:00 2001 From: Vladimir Kozlov Date: Thu, 28 Feb 2008 10:45:15 -0800 Subject: [PATCH 028/258] 6590177: jck60019 test assert(!repeated,"do not walk merges twice") A mergemem node could be not in worklist_store but in should_not_repeat vectorset since it was processed and removed from worklist_store before. Reviewed-by: jrose, never --- hotspot/src/share/vm/opto/gcm.cpp | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/hotspot/src/share/vm/opto/gcm.cpp b/hotspot/src/share/vm/opto/gcm.cpp index 88af191a1a3..c02989e04d0 100644 --- a/hotspot/src/share/vm/opto/gcm.cpp +++ b/hotspot/src/share/vm/opto/gcm.cpp @@ -448,9 +448,9 @@ Block* PhaseCFG::insert_anti_dependences(Block* LCA, Node* load, bool verify) { ResourceArea *area = Thread::current()->resource_area(); Node_List worklist_mem(area); // prior memory state to store Node_List worklist_store(area); // possible-def to explore + Node_List worklist_visited(area); // visited mergemem nodes Node_List non_early_stores(area); // all relevant stores outside of early bool must_raise_LCA = false; - DEBUG_ONLY(VectorSet should_not_repeat(area)); #ifdef TRACK_PHI_INPUTS // %%% This extra checking fails because MergeMem nodes are not GVNed. @@ -479,8 +479,8 @@ Block* PhaseCFG::insert_anti_dependences(Block* LCA, Node* load, bool verify) { Node* initial_mem = load->in(MemNode::Memory); worklist_store.push(initial_mem); + worklist_visited.push(initial_mem); worklist_mem.push(NULL); - DEBUG_ONLY(should_not_repeat.test_set(initial_mem->_idx)); while (worklist_store.size() > 0) { // Examine a nearby store to see if it might interfere with our load. Node* mem = worklist_mem.pop(); @@ -494,18 +494,20 @@ Block* PhaseCFG::insert_anti_dependences(Block* LCA, Node* load, bool verify) { || op == Op_MergeMem // internal node of tree we are searching ) { mem = store; // It's not a possibly interfering store. + if (store == initial_mem) + initial_mem = NULL; // only process initial memory once + for (DUIterator_Fast imax, i = mem->fast_outs(imax); i < imax; i++) { store = mem->fast_out(i); if (store->is_MergeMem()) { // Be sure we don't get into combinatorial problems. // (Allow phis to be repeated; they can merge two relevant states.) - uint i = worklist_store.size(); - for (; i > 0; i--) { - if (worklist_store.at(i-1) == store) break; + uint j = worklist_visited.size(); + for (; j > 0; j--) { + if (worklist_visited.at(j-1) == store) break; } - if (i > 0) continue; // already on work list; do not repeat - DEBUG_ONLY(int repeated = should_not_repeat.test_set(store->_idx)); - assert(!repeated, "do not walk merges twice"); + if (j > 0) continue; // already on work list; do not repeat + worklist_visited.push(store); } worklist_mem.push(mem); worklist_store.push(store); From 9a4ccf8a064b4273de35e7c5bf2e4681599a85ed Mon Sep 17 00:00:00 2001 From: Vladimir Kozlov Date: Thu, 28 Feb 2008 15:40:09 -0800 Subject: [PATCH 029/258] 6667573: Use set_req_X() in AddPNode::Ideal() for Iterative GVN Set_req_X() puts dependent nodes on IGVN worklist which allows to improve graph and gives more opportunities for EA scalar replacement. Reviewed-by: jrose, never --- hotspot/src/share/vm/opto/addnode.cpp | 22 ++++++++++++++++------ 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/hotspot/src/share/vm/opto/addnode.cpp b/hotspot/src/share/vm/opto/addnode.cpp index 7b29f422911..2369792a1bf 100644 --- a/hotspot/src/share/vm/opto/addnode.cpp +++ b/hotspot/src/share/vm/opto/addnode.cpp @@ -505,15 +505,25 @@ Node *AddPNode::Ideal(PhaseGVN *phase, bool can_reshape) { const Type *temp_t2 = phase->type( in(Offset) ); if( temp_t2 == Type::TOP ) return NULL; const TypeX *t2 = temp_t2->is_intptr_t(); + Node* address; + Node* offset; if( t2->is_con() ) { // The Add of the flattened expression - set_req(Address, addp->in(Address)); - set_req(Offset , phase->MakeConX(t2->get_con() + t12->get_con())); - return this; // Made progress + address = addp->in(Address); + offset = phase->MakeConX(t2->get_con() + t12->get_con()); + } else { + // Else move the constant to the right. ((A+con)+B) into ((A+B)+con) + address = phase->transform(new (phase->C, 4) AddPNode(in(Base),addp->in(Address),in(Offset))); + offset = addp->in(Offset); + } + PhaseIterGVN *igvn = phase->is_IterGVN(); + if( igvn ) { + set_req_X(Address,address,igvn); + set_req_X(Offset,offset,igvn); + } else { + set_req(Address,address); + set_req(Offset,offset); } - // Else move the constant to the right. ((A+con)+B) into ((A+B)+con) - set_req(Address, phase->transform(new (phase->C, 4) AddPNode(in(Base),addp->in(Address),in(Offset)))); - set_req(Offset , addp->in(Offset)); return this; } } From c223fed0840265d0d638faa6465418f3f0594fc0 Mon Sep 17 00:00:00 2001 From: Vladimir Kozlov Date: Fri, 29 Feb 2008 09:57:18 -0800 Subject: [PATCH 030/258] 6667580: Optimize CmpP for allocations CmpP could be optimized out if it compares new allocated objects. Reviewed-by: jrose, never, rasbold --- hotspot/src/share/vm/includeDB_compiler2 | 7 ++++--- hotspot/src/share/vm/opto/callnode.hpp | 6 ++++-- hotspot/src/share/vm/opto/memnode.hpp | 2 +- hotspot/src/share/vm/opto/node.hpp | 3 +++ hotspot/src/share/vm/opto/subnode.cpp | 7 +++++++ 5 files changed, 19 insertions(+), 6 deletions(-) diff --git a/hotspot/src/share/vm/includeDB_compiler2 b/hotspot/src/share/vm/includeDB_compiler2 index 0138cc664f6..01a6b9c94ce 100644 --- a/hotspot/src/share/vm/includeDB_compiler2 +++ b/hotspot/src/share/vm/includeDB_compiler2 @@ -19,7 +19,7 @@ // Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, // CA 95054 USA or visit www.sun.com if you need additional information or // have any questions. -// +// // ad_.cpp adGlobals_.hpp @@ -990,6 +990,7 @@ stubRoutines.cpp runtime.hpp subnode.cpp addnode.hpp subnode.cpp allocation.inline.hpp +subnode.cpp callnode.hpp subnode.cpp cfgnode.hpp subnode.cpp compileLog.hpp subnode.cpp connode.hpp @@ -1086,7 +1087,7 @@ idealGraphPrinter.hpp growableArray.hpp idealGraphPrinter.hpp ostream.hpp idealGraphPrinter.cpp idealGraphPrinter.hpp -idealGraphPrinter.cpp chaitin.hpp +idealGraphPrinter.cpp chaitin.hpp idealGraphPrinter.cpp machnode.hpp idealGraphPrinter.cpp parse.hpp idealGraphPrinter.cpp threadCritical.hpp @@ -1098,4 +1099,4 @@ parse2.cpp idealGraphPrinter.hpp parse1.cpp idealGraphPrinter.hpp matcher.cpp idealGraphPrinter.hpp loopnode.cpp idealGraphPrinter.hpp -chaitin.cpp idealGraphPrinter.hpp +chaitin.cpp idealGraphPrinter.hpp diff --git a/hotspot/src/share/vm/opto/callnode.hpp b/hotspot/src/share/vm/opto/callnode.hpp index e1e6116b689..c8315f94c96 100644 --- a/hotspot/src/share/vm/opto/callnode.hpp +++ b/hotspot/src/share/vm/opto/callnode.hpp @@ -38,7 +38,7 @@ class CallRuntimeNode; class CallLeafNode; class CallLeafNoFPNode; class AllocateNode; -class AllocateArrayNode; +class AllocateArrayNode; class LockNode; class UnlockNode; class JVMState; @@ -91,7 +91,9 @@ public: class ParmNode : public ProjNode { static const char * const names[TypeFunc::Parms+1]; public: - ParmNode( StartNode *src, uint con ) : ProjNode(src,con) {} + ParmNode( StartNode *src, uint con ) : ProjNode(src,con) { + init_class_id(Class_Parm); + } virtual int Opcode() const; virtual bool is_CFG() const { return (_con == TypeFunc::Control); } virtual uint ideal_reg() const; diff --git a/hotspot/src/share/vm/opto/memnode.hpp b/hotspot/src/share/vm/opto/memnode.hpp index 505cbdf979f..8c8676b4d36 100644 --- a/hotspot/src/share/vm/opto/memnode.hpp +++ b/hotspot/src/share/vm/opto/memnode.hpp @@ -60,13 +60,13 @@ protected: debug_only(_adr_type=at; adr_type();) } +public: // Helpers for the optimizer. Documented in memnode.cpp. static bool detect_ptr_independence(Node* p1, AllocateNode* a1, Node* p2, AllocateNode* a2, PhaseTransform* phase); static bool adr_phi_is_loop_invariant(Node* adr_phi, Node* cast); -public: // This one should probably be a phase-specific function: static bool detect_dominating_control(Node* dom, Node* sub); diff --git a/hotspot/src/share/vm/opto/node.hpp b/hotspot/src/share/vm/opto/node.hpp index f93562c09e7..8066da703ba 100644 --- a/hotspot/src/share/vm/opto/node.hpp +++ b/hotspot/src/share/vm/opto/node.hpp @@ -91,6 +91,7 @@ class Node_List; class Node_Stack; class NullCheckNode; class OopMap; +class ParmNode; class PCTableNode; class PhaseCCP; class PhaseGVN; @@ -557,6 +558,7 @@ public: DEFINE_CLASS_ID(JumpProj, Proj, 1) DEFINE_CLASS_ID(IfTrue, Proj, 2) DEFINE_CLASS_ID(IfFalse, Proj, 3) + DEFINE_CLASS_ID(Parm, Proj, 4) DEFINE_CLASS_ID(Region, Node, 3) DEFINE_CLASS_ID(Loop, Region, 0) @@ -712,6 +714,7 @@ public: DEFINE_CLASS_QUERY(Mul) DEFINE_CLASS_QUERY(Multi) DEFINE_CLASS_QUERY(MultiBranch) + DEFINE_CLASS_QUERY(Parm) DEFINE_CLASS_QUERY(PCTable) DEFINE_CLASS_QUERY(Phi) DEFINE_CLASS_QUERY(Proj) diff --git a/hotspot/src/share/vm/opto/subnode.cpp b/hotspot/src/share/vm/opto/subnode.cpp index 1344197ca22..2fc00289233 100644 --- a/hotspot/src/share/vm/opto/subnode.cpp +++ b/hotspot/src/share/vm/opto/subnode.cpp @@ -614,6 +614,13 @@ const Type *CmpPNode::sub( const Type *t1, const Type *t2 ) const { const TypeOopPtr* p0 = r0->isa_oopptr(); const TypeOopPtr* p1 = r1->isa_oopptr(); if (p0 && p1) { + Node* in1 = in(1)->uncast(); + Node* in2 = in(2)->uncast(); + AllocateNode* alloc1 = AllocateNode::Ideal_allocation(in1, NULL); + AllocateNode* alloc2 = AllocateNode::Ideal_allocation(in2, NULL); + if (MemNode::detect_ptr_independence(in1, alloc1, in2, alloc2, NULL)) { + return TypeInt::CC_GT; // different pointers + } ciKlass* klass0 = p0->klass(); bool xklass0 = p0->klass_is_exact(); ciKlass* klass1 = p1->klass(); From 7ec44373b51141fa3fff9336636923f42a4140b8 Mon Sep 17 00:00:00 2001 From: Vladimir Kozlov Date: Fri, 29 Feb 2008 11:22:27 -0800 Subject: [PATCH 031/258] 6667581: Don't generate initialization (by 0) code for arrays with size 0 Generate_arraycopy() does not check the size of allocated array. Reviewed-by: jrose, never --- hotspot/src/share/vm/opto/library_call.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/hotspot/src/share/vm/opto/library_call.cpp b/hotspot/src/share/vm/opto/library_call.cpp index e69e2d9e68b..b0587edfc3b 100644 --- a/hotspot/src/share/vm/opto/library_call.cpp +++ b/hotspot/src/share/vm/opto/library_call.cpp @@ -4170,6 +4170,7 @@ LibraryCallKit::generate_arraycopy(const TypePtr* adr_type, && !_gvn.eqv_uncast(src, dest) && ((alloc = tightly_coupled_allocation(dest, slow_region)) != NULL) + && _gvn.find_int_con(alloc->in(AllocateNode::ALength), 1) > 0 && alloc->maybe_set_complete(&_gvn)) { // "You break it, you buy it." InitializeNode* init = alloc->initialization(); From a6d8fca8768972ae0f1ce72e06677e5dc3260e09 Mon Sep 17 00:00:00 2001 From: "Y. Srinivas Ramakrishna" Date: Fri, 29 Feb 2008 14:42:56 -0800 Subject: [PATCH 032/258] 6668743: CMS: Consolidate block statistics reporting code Reduce the amount of related code replication and improve pretty printing. Reviewed-by: jmasa --- .../binaryTreeDictionary.cpp | 91 +++++++------------ .../compactibleFreeListSpace.cpp | 85 +++++++---------- .../compactibleFreeListSpace.hpp | 12 ++- .../concurrentMarkSweep/freeList.cpp | 26 ++++++ .../concurrentMarkSweep/freeList.hpp | 14 ++- .../vm/gc_implementation/includeDB_gc_shared | 17 +++- .../shared}/allocationStats.cpp | 0 .../shared}/allocationStats.hpp | 2 + hotspot/src/share/vm/includeDB_core | 16 +--- 9 files changed, 130 insertions(+), 133 deletions(-) rename hotspot/src/share/vm/{memory => gc_implementation/shared}/allocationStats.cpp (100%) rename hotspot/src/share/vm/{memory => gc_implementation/shared}/allocationStats.hpp (99%) diff --git a/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/binaryTreeDictionary.cpp b/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/binaryTreeDictionary.cpp index 09e0b282b06..91d381d5501 100644 --- a/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/binaryTreeDictionary.cpp +++ b/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/binaryTreeDictionary.cpp @@ -1071,85 +1071,56 @@ void BinaryTreeDictionary::reportStatistics() const { // for each list in the tree. Also print some summary // information. class printTreeCensusClosure : public AscendTreeCensusClosure { + int _print_line; size_t _totalFree; - AllocationStats _totals; - size_t _count; + FreeList _total; public: printTreeCensusClosure() { + _print_line = 0; _totalFree = 0; - _count = 0; - _totals.initialize(); } - AllocationStats* totals() { return &_totals; } - size_t count() { return _count; } - void increment_count_by(size_t v) { _count += v; } + FreeList* total() { return &_total; } size_t totalFree() { return _totalFree; } - void increment_totalFree_by(size_t v) { _totalFree += v; } void do_list(FreeList* fl) { - bool nl = false; // "maybe this is not needed" isNearLargestChunk(fl->head()); - - gclog_or_tty->print("%c %4d\t\t" "%7d\t" "%7d\t" - "%7d\t" "%7d\t" "%7d\t" "%7d\t" - "%7d\t" "%7d\t" "%7d\t" - "%7d\t" "\n", - " n"[nl], fl->size(), fl->bfrSurp(), fl->surplus(), - fl->desired(), fl->prevSweep(), fl->beforeSweep(), fl->count(), - fl->coalBirths(), fl->coalDeaths(), fl->splitBirths(), - fl->splitDeaths()); - - increment_totalFree_by(fl->count() * fl->size()); - increment_count_by(fl->count()); - totals()->set_bfrSurp(totals()->bfrSurp() + fl->bfrSurp()); - totals()->set_surplus(totals()->splitDeaths() + fl->surplus()); - totals()->set_prevSweep(totals()->prevSweep() + fl->prevSweep()); - totals()->set_beforeSweep(totals()->beforeSweep() + fl->beforeSweep()); - totals()->set_coalBirths(totals()->coalBirths() + fl->coalBirths()); - totals()->set_coalDeaths(totals()->coalDeaths() + fl->coalDeaths()); - totals()->set_splitBirths(totals()->splitBirths() + fl->splitBirths()); - totals()->set_splitDeaths(totals()->splitDeaths() + fl->splitDeaths()); + if (++_print_line >= 40) { + FreeList::print_labels_on(gclog_or_tty, "size"); + _print_line = 0; + } + fl->print_on(gclog_or_tty); + _totalFree += fl->count() * fl->size() ; + total()->set_count( total()->count() + fl->count() ); + total()->set_bfrSurp( total()->bfrSurp() + fl->bfrSurp() ); + total()->set_surplus( total()->splitDeaths() + fl->surplus() ); + total()->set_desired( total()->desired() + fl->desired() ); + total()->set_prevSweep( total()->prevSweep() + fl->prevSweep() ); + total()->set_beforeSweep(total()->beforeSweep() + fl->beforeSweep()); + total()->set_coalBirths( total()->coalBirths() + fl->coalBirths() ); + total()->set_coalDeaths( total()->coalDeaths() + fl->coalDeaths() ); + total()->set_splitBirths(total()->splitBirths() + fl->splitBirths()); + total()->set_splitDeaths(total()->splitDeaths() + fl->splitDeaths()); } }; void BinaryTreeDictionary::printDictCensus(void) const { gclog_or_tty->print("\nBinaryTree\n"); - gclog_or_tty->print( - "%4s\t\t" "%7s\t" "%7s\t" "%7s\t" "%7s\t" "%7s\t" - "%7s\t" "%7s\t" "%7s\t" "%7s\t" "%7s\t" "\n", - "size", "bfrsurp", "surplus", "desired", "prvSwep", "bfrSwep", - "count", "cBirths", "cDeaths", "sBirths", "sDeaths"); - + FreeList::print_labels_on(gclog_or_tty, "size"); printTreeCensusClosure ptc; ptc.do_tree(root()); + FreeList* total = ptc.total(); + FreeList::print_labels_on(gclog_or_tty, " "); + total->print_on(gclog_or_tty, "TOTAL\t"); gclog_or_tty->print( - "\t\t" "%7s\t" "%7s\t" "%7s\t" "%7s\t" - "%7s\t" "%7s\t" "%7s\t" "%7s\t" "%7s\t" "\n", - "bfrsurp", "surplus", "prvSwep", "bfrSwep", - "count", "cBirths", "cDeaths", "sBirths", "sDeaths"); - gclog_or_tty->print( - "%s\t\t" "%7d\t" "%7d\t" "%7d\t" "%7d\t" - "%7d\t" "%7d\t" "%7d\t" "%7d\t" "%7d\t" "\n", - "totl", - ptc.totals()->bfrSurp(), - ptc.totals()->surplus(), - ptc.totals()->prevSweep(), - ptc.totals()->beforeSweep(), - ptc.count(), - ptc.totals()->coalBirths(), - ptc.totals()->coalDeaths(), - ptc.totals()->splitBirths(), - ptc.totals()->splitDeaths()); - gclog_or_tty->print("totalFree(words): %7d growth: %8.5f deficit: %8.5f\n", + "totalFree(words): " SIZE_FORMAT_W(16) + " growth: %8.5f deficit: %8.5f\n", ptc.totalFree(), - (double)(ptc.totals()->splitBirths()+ptc.totals()->coalBirths() - -ptc.totals()->splitDeaths()-ptc.totals()->coalDeaths()) - /(ptc.totals()->prevSweep() != 0 ? - (double)ptc.totals()->prevSweep() : 1.0), - (double)(ptc.totals()->desired() - ptc.count()) - /(ptc.totals()->desired() != 0 ? - (double)ptc.totals()->desired() : 1.0)); + (double)(total->splitBirths() + total->coalBirths() + - total->splitDeaths() - total->coalDeaths()) + /(total->prevSweep() != 0 ? (double)total->prevSweep() : 1.0), + (double)(total->desired() - total->count()) + /(total->desired() != 0 ? (double)total->desired() : 1.0)); } // Verify the following tree invariants: diff --git a/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/compactibleFreeListSpace.cpp b/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/compactibleFreeListSpace.cpp index 27b5c08100c..de5611ddb7b 100644 --- a/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/compactibleFreeListSpace.cpp +++ b/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/compactibleFreeListSpace.cpp @@ -1835,7 +1835,7 @@ void CompactibleFreeListSpace::object_iterate_since_last_GC(ObjectClosure* cl) { guarantee(false, "NYI"); } -bool CompactibleFreeListSpace::linearAllocationWouldFail() { +bool CompactibleFreeListSpace::linearAllocationWouldFail() const { return _smallLinearAllocBlock._word_size == 0; } @@ -1906,6 +1906,13 @@ CompactibleFreeListSpace::refillLinearAllocBlock(LinearAllocBlock* blk) { } } +// Support for concurrent collection policy decisions. +bool CompactibleFreeListSpace::should_concurrent_collect() const { + // In the future we might want to add in frgamentation stats -- + // including erosion of the "mountain" into this decision as well. + return !adaptive_freelists() && linearAllocationWouldFail(); +} + // Support for compaction void CompactibleFreeListSpace::prepare_for_compaction(CompactPoint* cp) { @@ -2013,11 +2020,11 @@ void CompactibleFreeListSpace::clearFLCensus() { } } -void CompactibleFreeListSpace::endSweepFLCensus(int sweepCt) { +void CompactibleFreeListSpace::endSweepFLCensus(size_t sweep_count) { setFLSurplus(); setFLHints(); if (PrintGC && PrintFLSCensus > 0) { - printFLCensus(sweepCt); + printFLCensus(sweep_count); } clearFLCensus(); assert_locked(); @@ -2293,59 +2300,37 @@ void CompactibleFreeListSpace::checkFreeListConsistency() const { } #endif -void CompactibleFreeListSpace::printFLCensus(int sweepCt) const { +void CompactibleFreeListSpace::printFLCensus(size_t sweep_count) const { assert_lock_strong(&_freelistLock); - ssize_t bfrSurp = 0; - ssize_t surplus = 0; - ssize_t desired = 0; - ssize_t prevSweep = 0; - ssize_t beforeSweep = 0; - ssize_t count = 0; - ssize_t coalBirths = 0; - ssize_t coalDeaths = 0; - ssize_t splitBirths = 0; - ssize_t splitDeaths = 0; - gclog_or_tty->print("end sweep# %d\n", sweepCt); - gclog_or_tty->print("%4s\t" "%7s\t" "%7s\t" "%7s\t" "%7s\t" - "%7s\t" "%7s\t" "%7s\t" "%7s\t" "%7s\t" - "%7s\t" "\n", - "size", "bfrsurp", "surplus", "desired", "prvSwep", - "bfrSwep", "count", "cBirths", "cDeaths", "sBirths", - "sDeaths"); - + FreeList total; + gclog_or_tty->print("end sweep# " SIZE_FORMAT "\n", sweep_count); + FreeList::print_labels_on(gclog_or_tty, "size"); size_t totalFree = 0; for (size_t i = IndexSetStart; i < IndexSetSize; i += IndexSetStride) { const FreeList *fl = &_indexedFreeList[i]; - totalFree += fl->count() * fl->size(); - - gclog_or_tty->print("%4d\t" "%7d\t" "%7d\t" "%7d\t" - "%7d\t" "%7d\t" "%7d\t" "%7d\t" - "%7d\t" "%7d\t" "%7d\t" "\n", - fl->size(), fl->bfrSurp(), fl->surplus(), fl->desired(), - fl->prevSweep(), fl->beforeSweep(), fl->count(), fl->coalBirths(), - fl->coalDeaths(), fl->splitBirths(), fl->splitDeaths()); - bfrSurp += fl->bfrSurp(); - surplus += fl->surplus(); - desired += fl->desired(); - prevSweep += fl->prevSweep(); - beforeSweep += fl->beforeSweep(); - count += fl->count(); - coalBirths += fl->coalBirths(); - coalDeaths += fl->coalDeaths(); - splitBirths += fl->splitBirths(); - splitDeaths += fl->splitDeaths(); + totalFree += fl->count() * fl->size(); + if (i % (40*IndexSetStride) == 0) { + FreeList::print_labels_on(gclog_or_tty, "size"); + } + fl->print_on(gclog_or_tty); + total.set_bfrSurp( total.bfrSurp() + fl->bfrSurp() ); + total.set_surplus( total.surplus() + fl->surplus() ); + total.set_desired( total.desired() + fl->desired() ); + total.set_prevSweep( total.prevSweep() + fl->prevSweep() ); + total.set_beforeSweep(total.beforeSweep() + fl->beforeSweep()); + total.set_count( total.count() + fl->count() ); + total.set_coalBirths( total.coalBirths() + fl->coalBirths() ); + total.set_coalDeaths( total.coalDeaths() + fl->coalDeaths() ); + total.set_splitBirths(total.splitBirths() + fl->splitBirths()); + total.set_splitDeaths(total.splitDeaths() + fl->splitDeaths()); } - gclog_or_tty->print("%4s\t" - "%7d\t" "%7d\t" "%7d\t" "%7d\t" "%7d\t" - "%7d\t" "%7d\t" "%7d\t" "%7d\t" "%7d\t" "\n", - "totl", - bfrSurp, surplus, desired, prevSweep, beforeSweep, - count, coalBirths, coalDeaths, splitBirths, splitDeaths); - gclog_or_tty->print_cr("Total free in indexed lists %d words", totalFree); + total.print_on(gclog_or_tty, "TOTAL"); + gclog_or_tty->print_cr("Total free in indexed lists " + SIZE_FORMAT " words", totalFree); gclog_or_tty->print("growth: %8.5f deficit: %8.5f\n", - (double)(splitBirths+coalBirths-splitDeaths-coalDeaths)/ - (prevSweep != 0 ? (double)prevSweep : 1.0), - (double)(desired - count)/(desired != 0 ? (double)desired : 1.0)); + (double)(total.splitBirths()+total.coalBirths()-total.splitDeaths()-total.coalDeaths())/ + (total.prevSweep() != 0 ? (double)total.prevSweep() : 1.0), + (double)(total.desired() - total.count())/(total.desired() != 0 ? (double)total.desired() : 1.0)); _dictionary->printDictCensus(); } diff --git a/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/compactibleFreeListSpace.hpp b/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/compactibleFreeListSpace.hpp index ef5d12a6cac..5eb0f41b6a1 100644 --- a/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/compactibleFreeListSpace.hpp +++ b/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/compactibleFreeListSpace.hpp @@ -418,7 +418,7 @@ class CompactibleFreeListSpace: public CompactibleSpace { // chunk exists, return NULL. FreeChunk* find_chunk_at_end(); - bool adaptive_freelists() { return _adaptive_freelists; } + bool adaptive_freelists() const { return _adaptive_freelists; } void set_collector(CMSCollector* collector) { _collector = collector; } @@ -566,7 +566,7 @@ class CompactibleFreeListSpace: public CompactibleSpace { FreeChunk* allocateScratch(size_t size); // returns true if either the small or large linear allocation buffer is empty. - bool linearAllocationWouldFail(); + bool linearAllocationWouldFail() const; // Adjust the chunk for the minimum size. This version is called in // most cases in CompactibleFreeListSpace methods. @@ -585,6 +585,9 @@ class CompactibleFreeListSpace: public CompactibleSpace { void addChunkAndRepairOffsetTable(HeapWord* chunk, size_t size, bool coalesced); + // Support for decisions regarding concurrent collection policy + bool should_concurrent_collect() const; + // Support for compaction void prepare_for_compaction(CompactPoint* cp); void adjust_pointers(); @@ -622,7 +625,7 @@ class CompactibleFreeListSpace: public CompactibleSpace { // coalescing of chunks during the sweep of garbage. // Print the statistics for the free lists. - void printFLCensus(int sweepCt) const; + void printFLCensus(size_t sweep_count) const; // Statistics functions // Initialize census for lists before the sweep. @@ -635,12 +638,11 @@ class CompactibleFreeListSpace: public CompactibleSpace { // Clear the census for each of the free lists. void clearFLCensus(); // Perform functions for the census after the end of the sweep. - void endSweepFLCensus(int sweepCt); + void endSweepFLCensus(size_t sweep_count); // Return true if the count of free chunks is greater // than the desired number of free chunks. bool coalOverPopulated(size_t size); - // Record (for each size): // // split-births = #chunks added due to splits in (prev-sweep-end, diff --git a/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/freeList.cpp b/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/freeList.cpp index 1d1024e5057..e7b1b3aae8d 100644 --- a/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/freeList.cpp +++ b/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/freeList.cpp @@ -302,3 +302,29 @@ void FreeList::assert_proper_lock_protection_work() const { #endif } #endif + +// Print the "label line" for free list stats. +void FreeList::print_labels_on(outputStream* st, const char* c) { + st->print("%16s\t", c); + st->print("%14s\t" "%14s\t" "%14s\t" "%14s\t" "%14s\t" + "%14s\t" "%14s\t" "%14s\t" "%14s\t" "%14s\t" "\n", + "bfrsurp", "surplus", "desired", "prvSwep", "bfrSwep", + "count", "cBirths", "cDeaths", "sBirths", "sDeaths"); +} + +// Print the AllocationStats for the given free list. If the second argument +// to the call is a non-null string, it is printed in the first column; +// otherwise, if the argument is null (the default), then the size of the +// (free list) block is printed in the first column. +void FreeList::print_on(outputStream* st, const char* c) const { + if (c != NULL) { + st->print("%16s", c); + } else { + st->print(SIZE_FORMAT_W(16), size()); + } + st->print("\t" + SSIZE_FORMAT_W(14) "\t" SSIZE_FORMAT_W(14) "\t" SSIZE_FORMAT_W(14) "\t" SSIZE_FORMAT_W(14) "\t" SSIZE_FORMAT_W(14) "\t" + SSIZE_FORMAT_W(14) "\t" SSIZE_FORMAT_W(14) "\t" SSIZE_FORMAT_W(14) "\t" SSIZE_FORMAT_W(14) "\t" SSIZE_FORMAT_W(14) "\n", + bfrSurp(), surplus(), desired(), prevSweep(), beforeSweep(), + count(), coalBirths(), coalDeaths(), splitBirths(), splitDeaths()); +} diff --git a/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/freeList.hpp b/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/freeList.hpp index 4d4c1362a20..b553dd3fe47 100644 --- a/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/freeList.hpp +++ b/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/freeList.hpp @@ -38,6 +38,7 @@ class Mutex; class FreeList VALUE_OBJ_CLASS_SPEC { friend class CompactibleFreeListSpace; + friend class printTreeCensusClosure; FreeChunk* _head; // List of free chunks FreeChunk* _tail; // Tail of list of free chunks size_t _size; // Size in Heap words of each chunks @@ -63,10 +64,11 @@ class FreeList VALUE_OBJ_CLASS_SPEC { protected: void init_statistics(); void set_count(ssize_t v) { _count = v;} - void increment_count() { _count++; } + void increment_count() { _count++; } void decrement_count() { _count--; - assert(_count >= 0, "Count should not be negative"); } + assert(_count >= 0, "Count should not be negative"); + } public: // Constructor @@ -159,6 +161,10 @@ class FreeList VALUE_OBJ_CLASS_SPEC { ssize_t desired() const { return _allocation_stats.desired(); } + void set_desired(ssize_t v) { + assert_proper_lock_protection(); + _allocation_stats.set_desired(v); + } void compute_desired(float inter_sweep_current, float inter_sweep_estimate) { assert_proper_lock_protection(); @@ -298,4 +304,8 @@ class FreeList VALUE_OBJ_CLASS_SPEC { // Verify that the chunk is in the list. // found. Return NULL if "fc" is not found. bool verifyChunkInFreeLists(FreeChunk* fc) const; + + // Printing support + static void print_labels_on(outputStream* st, const char* c); + void print_on(outputStream* st, const char* c = NULL) const; }; diff --git a/hotspot/src/share/vm/gc_implementation/includeDB_gc_shared b/hotspot/src/share/vm/gc_implementation/includeDB_gc_shared index c0b6332e89f..ca8a47fa2fa 100644 --- a/hotspot/src/share/vm/gc_implementation/includeDB_gc_shared +++ b/hotspot/src/share/vm/gc_implementation/includeDB_gc_shared @@ -19,15 +19,22 @@ // Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, // CA 95054 USA or visit www.sun.com if you need additional information or // have any questions. -// +// // // NOTE: DO NOT CHANGE THIS COPYRIGHT TO NEW STYLE - IT WILL BREAK makeDeps! -gcAdaptivePolicyCounters.hpp adaptiveSizePolicy.hpp -gcAdaptivePolicyCounters.hpp gcPolicyCounters.hpp +allocationStats.cpp allocationStats.hpp +allocationStats.cpp ostream.hpp -gcAdaptivePolicyCounters.cpp resourceArea.hpp +allocationStats.hpp allocation.hpp +allocationStats.hpp gcUtil.hpp +allocationStats.hpp globalDefinitions.hpp + +gcAdaptivePolicyCounters.hpp adaptiveSizePolicy.hpp +gcAdaptivePolicyCounters.hpp gcPolicyCounters.hpp + +gcAdaptivePolicyCounters.cpp resourceArea.hpp gcAdaptivePolicyCounters.cpp gcAdaptivePolicyCounters.hpp gSpaceCounters.cpp generation.hpp @@ -44,7 +51,7 @@ immutableSpace.cpp universe.hpp isGCActiveMark.hpp parallelScavengeHeap.hpp -markSweep.inline.hpp psParallelCompact.hpp +markSweep.inline.hpp psParallelCompact.hpp mutableNUMASpace.cpp mutableNUMASpace.hpp mutableNUMASpace.cpp sharedHeap.hpp diff --git a/hotspot/src/share/vm/memory/allocationStats.cpp b/hotspot/src/share/vm/gc_implementation/shared/allocationStats.cpp similarity index 100% rename from hotspot/src/share/vm/memory/allocationStats.cpp rename to hotspot/src/share/vm/gc_implementation/shared/allocationStats.cpp diff --git a/hotspot/src/share/vm/memory/allocationStats.hpp b/hotspot/src/share/vm/gc_implementation/shared/allocationStats.hpp similarity index 99% rename from hotspot/src/share/vm/memory/allocationStats.hpp rename to hotspot/src/share/vm/gc_implementation/shared/allocationStats.hpp index 829a39cb5a0..a60fc2bc164 100644 --- a/hotspot/src/share/vm/memory/allocationStats.hpp +++ b/hotspot/src/share/vm/gc_implementation/shared/allocationStats.hpp @@ -98,6 +98,8 @@ class AllocationStats VALUE_OBJ_CLASS_SPEC { } ssize_t desired() const { return _desired; } + void set_desired(ssize_t v) { _desired = v; } + ssize_t coalDesired() const { return _coalDesired; } void set_coalDesired(ssize_t v) { _coalDesired = v; } diff --git a/hotspot/src/share/vm/includeDB_core b/hotspot/src/share/vm/includeDB_core index cbf8e561a73..a4c4a356f82 100644 --- a/hotspot/src/share/vm/includeDB_core +++ b/hotspot/src/share/vm/includeDB_core @@ -19,7 +19,7 @@ // Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, // CA 95054 USA or visit www.sun.com if you need additional information or // have any questions. -// +// // // NOTE: DO NOT CHANGE THIS COPYRIGHT TO NEW STYLE - IT WILL BREAK makeDeps! @@ -46,13 +46,13 @@ // as dependencies. Header files named H.inline.hpp generally contain // bodies for inline functions declared in H.hpp. // -// NOTE: Files that use the token "generate_platform_dependent_include" +// NOTE: Files that use the token "generate_platform_dependent_include" // are expected to contain macro references like , , ... and // makedeps has a dependency on these platform files looking like: -// foo_.trailing_string +// foo_.trailing_string // (where "trailing_string" can be any legal filename strings but typically // is "hpp" or "inline.hpp"). -// +// // The dependency in makedeps (and enforced) is that an underscore // will precedure the macro invocation. Note that this restriction // is only enforced on filenames that have the dependency token @@ -148,12 +148,6 @@ allocation.hpp globals.hpp allocation.inline.hpp os.hpp -allocationStats.cpp allocationStats.hpp - -allocationStats.hpp allocation.hpp -allocationStats.hpp gcUtil.hpp -allocationStats.hpp globalDefinitions.hpp - aprofiler.cpp aprofiler.hpp aprofiler.cpp collectedHeap.inline.hpp aprofiler.cpp oop.inline.hpp @@ -1935,7 +1929,7 @@ icache_.hpp generate_platform_dependent_include init.cpp bytecodes.hpp init.cpp collectedHeap.hpp -init.cpp handles.inline.hpp +init.cpp handles.inline.hpp init.cpp icBuffer.hpp init.cpp icache.hpp init.cpp init.hpp From 09d7f4bbcfe5123354aae0379beadc49bcda94ca Mon Sep 17 00:00:00 2001 From: Vladimir Kozlov Date: Fri, 29 Feb 2008 19:07:15 -0800 Subject: [PATCH 033/258] 6667588: Don't generate duplicated CMP for float/double values Float CMove generation add duplicated CMPF if there are more then one Move depending on the condition. Reviewed-by: jrose, never, rasbold --- hotspot/src/share/vm/opto/loopopts.cpp | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/hotspot/src/share/vm/opto/loopopts.cpp b/hotspot/src/share/vm/opto/loopopts.cpp index 0da6b1eeebb..d7b9ec89337 100644 --- a/hotspot/src/share/vm/opto/loopopts.cpp +++ b/hotspot/src/share/vm/opto/loopopts.cpp @@ -435,9 +435,11 @@ Node *PhaseIdealLoop::conditional_move( Node *region ) { // Check profitability int cost = 0; + int phis = 0; for (DUIterator_Fast imax, i = region->fast_outs(imax); i < imax; i++) { Node *out = region->fast_out(i); if( !out->is_Phi() ) continue; // Ignore other control edges, etc + phis++; PhiNode* phi = out->as_Phi(); switch (phi->type()->basic_type()) { case T_LONG: @@ -489,6 +491,12 @@ Node *PhaseIdealLoop::conditional_move( Node *region ) { } } if( cost >= ConditionalMoveLimit ) return NULL; // Too much goo + Node* bol = iff->in(1); + assert( bol->Opcode() == Op_Bool, "" ); + int cmp_op = bol->in(1)->Opcode(); + // It is expensive to generate flags from a float compare. + // Avoid duplicated float compare. + if( phis > 1 && (cmp_op == Op_CmpF || cmp_op == Op_CmpD)) return NULL; // -------------- // Now replace all Phis with CMOV's From dc6ad19d705a56b1945988da7bb874c099e0c73c Mon Sep 17 00:00:00 2001 From: Vladimir Kozlov Date: Fri, 29 Feb 2008 19:57:41 -0800 Subject: [PATCH 034/258] 6667618: disable LoadL->ConvL2I ==> LoadI optimization This optimization causes problems (sizes of Load and Store nodes do not match) for objects initialization code and Escape Analysis Reviewed-by: jrose, never --- hotspot/src/share/vm/opto/connode.cpp | 31 +++------------------------ hotspot/src/share/vm/opto/memnode.cpp | 20 ++++++----------- 2 files changed, 10 insertions(+), 41 deletions(-) diff --git a/hotspot/src/share/vm/opto/connode.cpp b/hotspot/src/share/vm/opto/connode.cpp index 6896f34710d..de3eed6f0e2 100644 --- a/hotspot/src/share/vm/opto/connode.cpp +++ b/hotspot/src/share/vm/opto/connode.cpp @@ -982,34 +982,9 @@ Node *ConvL2INode::Ideal(PhaseGVN *phase, bool can_reshape) { return new (phase->C, 3) AddINode(add1,add2); } - // Fold up with a prior LoadL: LoadL->ConvL2I ==> LoadI - // Requires we understand the 'endianess' of Longs. - if( andl_op == Op_LoadL ) { - Node *adr = andl->in(MemNode::Address); - // VM_LITTLE_ENDIAN is #defined appropriately in the Makefiles -#ifndef VM_LITTLE_ENDIAN - // The transformation can cause problems on BIG_ENDIAN architectures - // where the jint is not the same address as the jlong. Specifically, we - // will fail to insert an anti-dependence in GCM between the LoadI and a - // subsequent StoreL because different memory offsets provoke - // flatten_alias_type() into indicating two different types. See bug - // 4755222. - - // Node *base = adr->is_AddP() ? adr->in(AddPNode::Base) : adr; - // adr = phase->transform( new (phase->C, 4) AddPNode(base,adr,phase->MakeConX(sizeof(jint)))); - return NULL; -#else - if (phase->C->alias_type(andl->adr_type())->is_volatile()) { - // Picking up the low half by itself bypasses the atomic load and we could - // end up with more than one non-atomic load. See bugs 4432655 and 4526490. - // We could go to the trouble of iterating over andl's output edges and - // punting only if there's more than one real use, but we don't bother. - return NULL; - } - return new (phase->C, 3) LoadINode(andl->in(MemNode::Control),andl->in(MemNode::Memory),adr,((LoadLNode*)andl)->raw_adr_type()); -#endif - } - + // Disable optimization: LoadL->ConvL2I ==> LoadI. + // It causes problems (sizes of Load and Store nodes do not match) + // in objects initialization code and Escape Analysis. return NULL; } diff --git a/hotspot/src/share/vm/opto/memnode.cpp b/hotspot/src/share/vm/opto/memnode.cpp index 28f37d9a8a5..03f43d88595 100644 --- a/hotspot/src/share/vm/opto/memnode.cpp +++ b/hotspot/src/share/vm/opto/memnode.cpp @@ -108,19 +108,13 @@ Node *MemNode::Ideal_common(PhaseGVN *phase, bool can_reshape) { // Avoid independent memory operations Node* old_mem = mem; - if (mem->is_Proj() && mem->in(0)->is_Initialize()) { - InitializeNode* init = mem->in(0)->as_Initialize(); - if (init->is_complete()) { // i.e., after macro expansion - const TypePtr* tp = t_adr->is_ptr(); - uint alias_idx = phase->C->get_alias_index(tp); - // Free this slice from the init. It was hooked, temporarily, - // by GraphKit::set_output_for_allocation. - if (alias_idx > Compile::AliasIdxRaw) { - mem = init->memory(alias_idx); - // ...but not with the raw-pointer slice. - } - } - } + // The code which unhooks non-raw memories from complete (macro-expanded) + // initializations was removed. After macro-expansion all stores catched + // by Initialize node became raw stores and there is no information + // which memory slices they modify. So it is unsafe to move any memory + // operation above these stores. Also in most cases hooked non-raw memories + // were already unhooked by using information from detect_ptr_independence() + // and find_previous_store(). if (mem->is_MergeMem()) { MergeMemNode* mmem = mem->as_MergeMem(); From 6c0c606249d9751836d74b481d9a1e52bf0247d1 Mon Sep 17 00:00:00 2001 From: Jon Masamitsu Date: Sun, 2 Mar 2008 16:10:12 -0800 Subject: [PATCH 035/258] 6557851: CMS: ergonomics defaults are not set with FLAG_SET_ERGO Default values set by cms ergonomics are set with FLAG_SET_DEFAULT so down stream the values look like the default values and affect how later parameters are set. Set these values with FLAG_SET_ERGO instead and adjust how later parameters are interpreted. Reviewed-by: iveresov, apetrusenko, pbk, ysr --- .../parNew/asParNewGeneration.cpp | 4 +- .../parallelScavenge/asPSYoungGen.cpp | 6 +- .../parallelScavenge/parallelScavengeHeap.cpp | 2 +- .../parallelScavenge/parallelScavengeHeap.hpp | 14 +- .../parallelScavenge/psYoungGen.cpp | 10 +- .../src/share/vm/memory/collectorPolicy.cpp | 338 ++++++++++++++---- .../src/share/vm/memory/collectorPolicy.hpp | 31 ++ hotspot/src/share/vm/runtime/arguments.cpp | 52 ++- hotspot/src/share/vm/runtime/globals.cpp | 12 + .../share/vm/runtime/globals_extension.hpp | 4 + 10 files changed, 376 insertions(+), 97 deletions(-) diff --git a/hotspot/src/share/vm/gc_implementation/parNew/asParNewGeneration.cpp b/hotspot/src/share/vm/gc_implementation/parNew/asParNewGeneration.cpp index 506619547d2..fa4a554b976 100644 --- a/hotspot/src/share/vm/gc_implementation/parNew/asParNewGeneration.cpp +++ b/hotspot/src/share/vm/gc_implementation/parNew/asParNewGeneration.cpp @@ -74,8 +74,8 @@ size_t ASParNewGeneration::available_to_live() const { #ifdef SHRINKS_AT_END_OF_EDEN size_t delta_in_survivor = 0; ParallelScavengeHeap* heap = (ParallelScavengeHeap*)Universe::heap(); - const size_t space_alignment = heap->intra_generation_alignment(); - const size_t gen_alignment = heap->generation_alignment(); + const size_t space_alignment = heap->intra_heap_alignment(); + const size_t gen_alignment = heap->object_heap_alignment(); MutableSpace* space_shrinking = NULL; if (from_space()->end() > to_space()->end()) { diff --git a/hotspot/src/share/vm/gc_implementation/parallelScavenge/asPSYoungGen.cpp b/hotspot/src/share/vm/gc_implementation/parallelScavenge/asPSYoungGen.cpp index 3d16cf68109..7ef34bb89bd 100644 --- a/hotspot/src/share/vm/gc_implementation/parallelScavenge/asPSYoungGen.cpp +++ b/hotspot/src/share/vm/gc_implementation/parallelScavenge/asPSYoungGen.cpp @@ -86,7 +86,7 @@ size_t ASPSYoungGen::available_for_contraction() { if (eden_space()->is_empty()) { // Respect the minimum size for eden and for the young gen as a whole. ParallelScavengeHeap* heap = (ParallelScavengeHeap*)Universe::heap(); - const size_t eden_alignment = heap->intra_generation_alignment(); + const size_t eden_alignment = heap->intra_heap_alignment(); const size_t gen_alignment = heap->young_gen_alignment(); assert(eden_space()->capacity_in_bytes() >= eden_alignment, @@ -124,7 +124,7 @@ size_t ASPSYoungGen::available_for_contraction() { // to_space can be. size_t ASPSYoungGen::available_to_live() { ParallelScavengeHeap* heap = (ParallelScavengeHeap*)Universe::heap(); - const size_t alignment = heap->intra_generation_alignment(); + const size_t alignment = heap->intra_heap_alignment(); // Include any space that is committed but is not in eden. size_t available = pointer_delta(eden_space()->bottom(), @@ -275,7 +275,7 @@ void ASPSYoungGen::resize_spaces(size_t requested_eden_size, assert(eden_start < from_start, "Cannot push into from_space"); ParallelScavengeHeap* heap = (ParallelScavengeHeap*)Universe::heap(); - const size_t alignment = heap->intra_generation_alignment(); + const size_t alignment = heap->intra_heap_alignment(); // Check whether from space is below to space if (from_start < to_start) { diff --git a/hotspot/src/share/vm/gc_implementation/parallelScavenge/parallelScavengeHeap.cpp b/hotspot/src/share/vm/gc_implementation/parallelScavenge/parallelScavengeHeap.cpp index 7fde520423c..8088f0c5d0d 100644 --- a/hotspot/src/share/vm/gc_implementation/parallelScavenge/parallelScavengeHeap.cpp +++ b/hotspot/src/share/vm/gc_implementation/parallelScavenge/parallelScavengeHeap.cpp @@ -173,7 +173,7 @@ jint ParallelScavengeHeap::initialize() { new PSAdaptiveSizePolicy(eden_capacity, initial_promo_size, young_gen()->to_space()->capacity_in_bytes(), - intra_generation_alignment(), + intra_heap_alignment(), max_gc_pause_sec, max_gc_minor_pause_sec, GCTimeRatio diff --git a/hotspot/src/share/vm/gc_implementation/parallelScavenge/parallelScavengeHeap.hpp b/hotspot/src/share/vm/gc_implementation/parallelScavenge/parallelScavengeHeap.hpp index 5c1a765c215..6ea9b35f984 100644 --- a/hotspot/src/share/vm/gc_implementation/parallelScavenge/parallelScavengeHeap.hpp +++ b/hotspot/src/share/vm/gc_implementation/parallelScavenge/parallelScavengeHeap.hpp @@ -58,9 +58,9 @@ class ParallelScavengeHeap : public CollectedHeap { public: ParallelScavengeHeap() : CollectedHeap() { - set_alignment(_perm_gen_alignment, intra_generation_alignment()); - set_alignment(_young_gen_alignment, intra_generation_alignment()); - set_alignment(_old_gen_alignment, intra_generation_alignment()); + set_alignment(_perm_gen_alignment, intra_heap_alignment()); + set_alignment(_young_gen_alignment, intra_heap_alignment()); + set_alignment(_old_gen_alignment, intra_heap_alignment()); } // For use by VM operations @@ -92,14 +92,14 @@ class ParallelScavengeHeap : public CollectedHeap { void post_initialize(); void update_counters(); - // The alignment used for the various generations. size_t perm_gen_alignment() const { return _perm_gen_alignment; } size_t young_gen_alignment() const { return _young_gen_alignment; } size_t old_gen_alignment() const { return _old_gen_alignment; } - // The alignment used for eden and survivors within the young gen. - size_t intra_generation_alignment() const { return 64 * K; } + // The alignment used for eden and survivors within the young gen + // and for boundary between young gen and old gen. + size_t intra_heap_alignment() const { return 64 * K; } size_t capacity() const; size_t used() const; @@ -217,6 +217,6 @@ class ParallelScavengeHeap : public CollectedHeap { inline size_t ParallelScavengeHeap::set_alignment(size_t& var, size_t val) { assert(is_power_of_2((intptr_t)val), "must be a power of 2"); - var = round_to(val, intra_generation_alignment()); + var = round_to(val, intra_heap_alignment()); return var; } diff --git a/hotspot/src/share/vm/gc_implementation/parallelScavenge/psYoungGen.cpp b/hotspot/src/share/vm/gc_implementation/parallelScavenge/psYoungGen.cpp index ac7f64eaa06..b7088556bdc 100644 --- a/hotspot/src/share/vm/gc_implementation/parallelScavenge/psYoungGen.cpp +++ b/hotspot/src/share/vm/gc_implementation/parallelScavenge/psYoungGen.cpp @@ -88,7 +88,7 @@ void PSYoungGen::initialize_work() { // Compute maximum space sizes for performance counters ParallelScavengeHeap* heap = (ParallelScavengeHeap*)Universe::heap(); - size_t alignment = heap->intra_generation_alignment(); + size_t alignment = heap->intra_heap_alignment(); size_t size = _virtual_space->reserved_size(); size_t max_survivor_size; @@ -141,7 +141,7 @@ void PSYoungGen::compute_initial_space_boundaries() { assert(heap->kind() == CollectedHeap::ParallelScavengeHeap, "Sanity"); // Compute sizes - size_t alignment = heap->intra_generation_alignment(); + size_t alignment = heap->intra_heap_alignment(); size_t size = _virtual_space->committed_size(); size_t survivor_size = size / InitialSurvivorRatio; @@ -192,7 +192,7 @@ void PSYoungGen::set_space_boundaries(size_t eden_size, size_t survivor_size) { #ifndef PRODUCT void PSYoungGen::space_invariants() { ParallelScavengeHeap* heap = (ParallelScavengeHeap*)Universe::heap(); - const size_t alignment = heap->intra_generation_alignment(); + const size_t alignment = heap->intra_heap_alignment(); // Currently, our eden size cannot shrink to zero guarantee(eden_space()->capacity_in_bytes() >= alignment, "eden too small"); @@ -392,7 +392,7 @@ void PSYoungGen::resize_spaces(size_t requested_eden_size, char* to_end = (char*)to_space()->end(); ParallelScavengeHeap* heap = (ParallelScavengeHeap*)Universe::heap(); - const size_t alignment = heap->intra_generation_alignment(); + const size_t alignment = heap->intra_heap_alignment(); const bool maintain_minimum = (requested_eden_size + 2 * requested_survivor_size) <= min_gen_size(); @@ -708,7 +708,7 @@ size_t PSYoungGen::available_to_min_gen() { size_t PSYoungGen::available_to_live() { size_t delta_in_survivor = 0; ParallelScavengeHeap* heap = (ParallelScavengeHeap*)Universe::heap(); - const size_t space_alignment = heap->intra_generation_alignment(); + const size_t space_alignment = heap->intra_heap_alignment(); const size_t gen_alignment = heap->young_gen_alignment(); MutableSpace* space_shrinking = NULL; diff --git a/hotspot/src/share/vm/memory/collectorPolicy.cpp b/hotspot/src/share/vm/memory/collectorPolicy.cpp index de43e6aadf8..b26158e247b 100644 --- a/hotspot/src/share/vm/memory/collectorPolicy.cpp +++ b/hotspot/src/share/vm/memory/collectorPolicy.cpp @@ -57,45 +57,51 @@ void CollectorPolicy::initialize_size_info() { // User inputs from -mx and ms are aligned _initial_heap_byte_size = align_size_up(Arguments::initial_heap_size(), min_alignment()); - _min_heap_byte_size = align_size_up(Arguments::min_heap_size(), - min_alignment()); - _max_heap_byte_size = align_size_up(MaxHeapSize, max_alignment()); + set_min_heap_byte_size(align_size_up(Arguments::min_heap_size(), + min_alignment())); + set_max_heap_byte_size(align_size_up(MaxHeapSize, max_alignment())); // Check validity of heap parameters from launcher - if (_initial_heap_byte_size == 0) { - _initial_heap_byte_size = NewSize + OldSize; + if (initial_heap_byte_size() == 0) { + set_initial_heap_byte_size(NewSize + OldSize); } else { - Universe::check_alignment(_initial_heap_byte_size, min_alignment(), + Universe::check_alignment(initial_heap_byte_size(), min_alignment(), "initial heap"); } - if (_min_heap_byte_size == 0) { - _min_heap_byte_size = NewSize + OldSize; + if (min_heap_byte_size() == 0) { + set_min_heap_byte_size(NewSize + OldSize); } else { - Universe::check_alignment(_min_heap_byte_size, min_alignment(), + Universe::check_alignment(min_heap_byte_size(), min_alignment(), "initial heap"); } // Check heap parameter properties - if (_initial_heap_byte_size < M) { + if (initial_heap_byte_size() < M) { vm_exit_during_initialization("Too small initial heap"); } // Check heap parameter properties - if (_min_heap_byte_size < M) { + if (min_heap_byte_size() < M) { vm_exit_during_initialization("Too small minimum heap"); } - if (_initial_heap_byte_size <= NewSize) { + if (initial_heap_byte_size() <= NewSize) { // make sure there is at least some room in old space vm_exit_during_initialization("Too small initial heap for new size specified"); } - if (_max_heap_byte_size < _min_heap_byte_size) { + if (max_heap_byte_size() < min_heap_byte_size()) { vm_exit_during_initialization("Incompatible minimum and maximum heap sizes specified"); } - if (_initial_heap_byte_size < _min_heap_byte_size) { + if (initial_heap_byte_size() < min_heap_byte_size()) { vm_exit_during_initialization("Incompatible minimum and initial heap sizes specified"); } - if (_max_heap_byte_size < _initial_heap_byte_size) { + if (max_heap_byte_size() < initial_heap_byte_size()) { vm_exit_during_initialization("Incompatible initial and maximum heap sizes specified"); } + + if (PrintGCDetails && Verbose) { + gclog_or_tty->print_cr("Minimum heap " SIZE_FORMAT " Initial heap " + SIZE_FORMAT " Maximum heap " SIZE_FORMAT, + min_heap_byte_size(), initial_heap_byte_size(), max_heap_byte_size()); + } } void CollectorPolicy::initialize_perm_generation(PermGen::Name pgnm) { @@ -128,10 +134,26 @@ GenRemSet* CollectorPolicy::create_rem_set(MemRegion whole_heap, // GenCollectorPolicy methods. +size_t GenCollectorPolicy::scale_by_NewRatio_aligned(size_t base_size) { + size_t x = base_size / (NewRatio+1); + size_t new_gen_size = x > min_alignment() ? + align_size_down(x, min_alignment()) : + min_alignment(); + return new_gen_size; +} + +size_t GenCollectorPolicy::bound_minus_alignment(size_t desired_size, + size_t maximum_size) { + size_t alignment = min_alignment(); + size_t max_minus = maximum_size - alignment; + return desired_size < max_minus ? desired_size : max_minus; +} + + void GenCollectorPolicy::initialize_size_policy(size_t init_eden_size, size_t init_promo_size, size_t init_survivor_size) { - double max_gc_minor_pause_sec = ((double) MaxGCMinorPauseMillis)/1000.0; + const double max_gc_minor_pause_sec = ((double) MaxGCMinorPauseMillis)/1000.0; _size_policy = new AdaptiveSizePolicy(init_eden_size, init_promo_size, init_survivor_size, @@ -210,74 +232,260 @@ void TwoGenerationCollectorPolicy::initialize_flags() { assert(MaxHeapSize % max_alignment() == 0, "maximum heap alignment"); } +// Values set on the command line win over any ergonomically +// set command line parameters. +// Ergonomic choice of parameters are done before this +// method is called. Values for command line parameters such as NewSize +// and MaxNewSize feed those ergonomic choices into this method. +// This method makes the final generation sizings consistent with +// themselves and with overall heap sizings. +// In the absence of explicitly set command line flags, policies +// such as the use of NewRatio are used to size the generation. void GenCollectorPolicy::initialize_size_info() { CollectorPolicy::initialize_size_info(); - // Minimum sizes of the generations may be different than - // the initial sizes. - if (!FLAG_IS_DEFAULT(NewSize)) { - _min_gen0_size = NewSize; - } else { - _min_gen0_size = align_size_down(_min_heap_byte_size / (NewRatio+1), + // min_alignment() is used for alignment within a generation. + // There is additional alignment done down stream for some + // collectors that sometimes causes unwanted rounding up of + // generations sizes. + + // Determine maximum size of gen0 + + size_t max_new_size = 0; + if (FLAG_IS_CMDLINE(MaxNewSize)) { + if (MaxNewSize < min_alignment()) { + max_new_size = min_alignment(); + } else if (MaxNewSize >= max_heap_byte_size()) { + max_new_size = align_size_down(max_heap_byte_size() - min_alignment(), min_alignment()); - // We bound the minimum size by NewSize below (since it historically + warning("MaxNewSize (" SIZE_FORMAT "k) is equal to or " + "greater than the entire heap (" SIZE_FORMAT "k). A " + "new generation size of " SIZE_FORMAT "k will be used.", + MaxNewSize/K, max_heap_byte_size()/K, max_new_size/K); + } else { + max_new_size = align_size_down(MaxNewSize, min_alignment()); + } + + // The case for FLAG_IS_ERGO(MaxNewSize) could be treated + // specially at this point to just use an ergonomically set + // MaxNewSize to set max_new_size. For cases with small + // heaps such a policy often did not work because the MaxNewSize + // was larger than the entire heap. The interpretation given + // to ergonomically set flags is that the flags are set + // by different collectors for their own special needs but + // are not allowed to badly shape the heap. This allows the + // different collectors to decide what's best for themselves + // without having to factor in the overall heap shape. It + // can be the case in the future that the collectors would + // only make "wise" ergonomics choices and this policy could + // just accept those choices. The choices currently made are + // not always "wise". + } else { + max_new_size = scale_by_NewRatio_aligned(max_heap_byte_size()); + // Bound the maximum size by NewSize below (since it historically // would have been NewSize and because the NewRatio calculation could // yield a size that is too small) and bound it by MaxNewSize above. - // This is not always best. The NewSize calculated by CMS (which has - // a fixed minimum of 16m) can sometimes be "too" large. Consider - // the case where -Xmx32m. The CMS calculated NewSize would be about - // half the entire heap which seems too large. But the counter - // example is seen when the client defaults for NewRatio are used. - // An initial young generation size of 640k was observed - // with -Xmx128m -XX:MaxNewSize=32m when NewSize was not used - // as a lower bound as with - // _min_gen0_size = MIN2(_min_gen0_size, MaxNewSize); - // and 640k seemed too small a young generation. - _min_gen0_size = MIN2(MAX2(_min_gen0_size, NewSize), MaxNewSize); + // Ergonomics plays here by previously calculating the desired + // NewSize and MaxNewSize. + max_new_size = MIN2(MAX2(max_new_size, NewSize), MaxNewSize); + } + assert(max_new_size > 0, "All paths should set max_new_size"); + + // Given the maximum gen0 size, determine the initial and + // minimum sizes. + + if (max_heap_byte_size() == min_heap_byte_size()) { + // The maximum and minimum heap sizes are the same so + // the generations minimum and initial must be the + // same as its maximum. + set_min_gen0_size(max_new_size); + set_initial_gen0_size(max_new_size); + set_max_gen0_size(max_new_size); + } else { + size_t desired_new_size = 0; + if (!FLAG_IS_DEFAULT(NewSize)) { + // If NewSize is set ergonomically (for example by cms), it + // would make sense to use it. If it is used, also use it + // to set the initial size. Although there is no reason + // the minimum size and the initial size have to be the same, + // the current implementation gets into trouble during the calculation + // of the tenured generation sizes if they are different. + // Note that this makes the initial size and the minimum size + // generally small compared to the NewRatio calculation. + _min_gen0_size = NewSize; + desired_new_size = NewSize; + max_new_size = MAX2(max_new_size, NewSize); + } else { + // For the case where NewSize is the default, use NewRatio + // to size the minimum and initial generation sizes. + // Use the default NewSize as the floor for these values. If + // NewRatio is overly large, the resulting sizes can be too + // small. + _min_gen0_size = MAX2(scale_by_NewRatio_aligned(min_heap_byte_size()), + NewSize); + desired_new_size = + MAX2(scale_by_NewRatio_aligned(initial_heap_byte_size()), + NewSize); + } + + assert(_min_gen0_size > 0, "Sanity check"); + set_initial_gen0_size(desired_new_size); + set_max_gen0_size(max_new_size); + + // At this point the desirable initial and minimum sizes have been + // determined without regard to the maximum sizes. + + // Bound the sizes by the corresponding overall heap sizes. + set_min_gen0_size( + bound_minus_alignment(_min_gen0_size, min_heap_byte_size())); + set_initial_gen0_size( + bound_minus_alignment(_initial_gen0_size, initial_heap_byte_size())); + set_max_gen0_size( + bound_minus_alignment(_max_gen0_size, max_heap_byte_size())); + + // At this point all three sizes have been checked against the + // maximum sizes but have not been checked for consistency + // amoung the three. + + // Final check min <= initial <= max + set_min_gen0_size(MIN2(_min_gen0_size, _max_gen0_size)); + set_initial_gen0_size( + MAX2(MIN2(_initial_gen0_size, _max_gen0_size), _min_gen0_size)); + set_min_gen0_size(MIN2(_min_gen0_size, _initial_gen0_size)); } - // Parameters are valid, compute area sizes. - size_t max_new_size = align_size_down(_max_heap_byte_size / (NewRatio+1), - min_alignment()); - max_new_size = MIN2(MAX2(max_new_size, _min_gen0_size), MaxNewSize); - - // desired_new_size is used to set the initial size. The - // initial size must be greater than the minimum size. - size_t desired_new_size = - align_size_down(_initial_heap_byte_size / (NewRatio+1), - min_alignment()); - - size_t new_size = MIN2(MAX2(desired_new_size, _min_gen0_size), max_new_size); - - _initial_gen0_size = new_size; - _max_gen0_size = max_new_size; + if (PrintGCDetails && Verbose) { + gclog_or_tty->print_cr("Minimum gen0 " SIZE_FORMAT " Initial gen0 " + SIZE_FORMAT " Maximum gen0 " SIZE_FORMAT, + min_gen0_size(), initial_gen0_size(), max_gen0_size()); + } } +// Call this method during the sizing of the gen1 to make +// adjustments to gen0 because of gen1 sizing policy. gen0 initially has +// the most freedom in sizing because it is done before the +// policy for gen1 is applied. Once gen1 policies have been applied, +// there may be conflicts in the shape of the heap and this method +// is used to make the needed adjustments. The application of the +// policies could be more sophisticated (iterative for example) but +// keeping it simple also seems a worthwhile goal. +bool TwoGenerationCollectorPolicy::adjust_gen0_sizes(size_t* gen0_size_ptr, + size_t* gen1_size_ptr, + size_t heap_size, + size_t min_gen0_size) { + bool result = false; + if ((*gen1_size_ptr + *gen0_size_ptr) > heap_size) { + if (((*gen0_size_ptr + OldSize) > heap_size) && + (heap_size - min_gen0_size) >= min_alignment()) { + // Adjust gen0 down to accomodate OldSize + *gen0_size_ptr = heap_size - min_gen0_size; + *gen0_size_ptr = + MAX2((uintx)align_size_down(*gen0_size_ptr, min_alignment()), + min_alignment()); + assert(*gen0_size_ptr > 0, "Min gen0 is too large"); + result = true; + } else { + *gen1_size_ptr = heap_size - *gen0_size_ptr; + *gen1_size_ptr = + MAX2((uintx)align_size_down(*gen1_size_ptr, min_alignment()), + min_alignment()); + } + } + return result; +} + +// Minimum sizes of the generations may be different than +// the initial sizes. An inconsistently is permitted here +// in the total size that can be specified explicitly by +// command line specification of OldSize and NewSize and +// also a command line specification of -Xms. Issue a warning +// but allow the values to pass. + void TwoGenerationCollectorPolicy::initialize_size_info() { GenCollectorPolicy::initialize_size_info(); - // Minimum sizes of the generations may be different than - // the initial sizes. An inconsistently is permitted here - // in the total size that can be specified explicitly by - // command line specification of OldSize and NewSize and - // also a command line specification of -Xms. Issue a warning - // but allow the values to pass. - if (!FLAG_IS_DEFAULT(OldSize)) { - _min_gen1_size = OldSize; + // At this point the minimum, initial and maximum sizes + // of the overall heap and of gen0 have been determined. + // The maximum gen1 size can be determined from the maximum gen0 + // and maximum heap size since not explicit flags exits + // for setting the gen1 maximum. + _max_gen1_size = max_heap_byte_size() - _max_gen0_size; + _max_gen1_size = + MAX2((uintx)align_size_down(_max_gen1_size, min_alignment()), + min_alignment()); + // If no explicit command line flag has been set for the + // gen1 size, use what is left for gen1. + if (FLAG_IS_DEFAULT(OldSize) || FLAG_IS_ERGO(OldSize)) { + // The user has not specified any value or ergonomics + // has chosen a value (which may or may not be consistent + // with the overall heap size). In either case make + // the minimum, maximum and initial sizes consistent + // with the gen0 sizes and the overall heap sizes. + assert(min_heap_byte_size() > _min_gen0_size, + "gen0 has an unexpected minimum size"); + set_min_gen1_size(min_heap_byte_size() - min_gen0_size()); + set_min_gen1_size( + MAX2((uintx)align_size_down(_min_gen1_size, min_alignment()), + min_alignment())); + set_initial_gen1_size(initial_heap_byte_size() - initial_gen0_size()); + set_initial_gen1_size( + MAX2((uintx)align_size_down(_initial_gen1_size, min_alignment()), + min_alignment())); + + } else { + // It's been explicitly set on the command line. Use the + // OldSize and then determine the consequences. + set_min_gen1_size(OldSize); + set_initial_gen1_size(OldSize); + + // If the user has explicitly set an OldSize that is inconsistent + // with other command line flags, issue a warning. // The generation minimums and the overall heap mimimum should // be within one heap alignment. - if ((_min_gen1_size + _min_gen0_size + max_alignment()) < - _min_heap_byte_size) { + if ((_min_gen1_size + _min_gen0_size + min_alignment()) < + min_heap_byte_size()) { warning("Inconsistency between minimum heap size and minimum " - "generation sizes: using min heap = " SIZE_FORMAT, - _min_heap_byte_size); + "generation sizes: using minimum heap = " SIZE_FORMAT, + min_heap_byte_size()); } - } else { - _min_gen1_size = _min_heap_byte_size - _min_gen0_size; + if ((OldSize > _max_gen1_size)) { + warning("Inconsistency between maximum heap size and maximum " + "generation sizes: using maximum heap = " SIZE_FORMAT + " -XX:OldSize flag is being ignored", + max_heap_byte_size()); } + // If there is an inconsistency between the OldSize and the minimum and/or + // initial size of gen0, since OldSize was explicitly set, OldSize wins. + if (adjust_gen0_sizes(&_min_gen0_size, &_min_gen1_size, + min_heap_byte_size(), OldSize)) { + if (PrintGCDetails && Verbose) { + gclog_or_tty->print_cr("Minimum gen0 " SIZE_FORMAT " Initial gen0 " + SIZE_FORMAT " Maximum gen0 " SIZE_FORMAT, + min_gen0_size(), initial_gen0_size(), max_gen0_size()); + } + } + // Initial size + if (adjust_gen0_sizes(&_initial_gen0_size, &_initial_gen1_size, + initial_heap_byte_size(), OldSize)) { + if (PrintGCDetails && Verbose) { + gclog_or_tty->print_cr("Minimum gen0 " SIZE_FORMAT " Initial gen0 " + SIZE_FORMAT " Maximum gen0 " SIZE_FORMAT, + min_gen0_size(), initial_gen0_size(), max_gen0_size()); + } + } + } + // Enforce the maximum gen1 size. + set_min_gen1_size(MIN2(_min_gen1_size, _max_gen1_size)); - _initial_gen1_size = _initial_heap_byte_size - _initial_gen0_size; - _max_gen1_size = _max_heap_byte_size - _max_gen0_size; + // Check that min gen1 <= initial gen1 <= max gen1 + set_initial_gen1_size(MAX2(_initial_gen1_size, _min_gen1_size)); + set_initial_gen1_size(MIN2(_initial_gen1_size, _max_gen1_size)); + + if (PrintGCDetails && Verbose) { + gclog_or_tty->print_cr("Minimum gen1 " SIZE_FORMAT " Initial gen1 " + SIZE_FORMAT " Maximum gen1 " SIZE_FORMAT, + min_gen1_size(), initial_gen1_size(), max_gen1_size()); + } } HeapWord* GenCollectorPolicy::mem_allocate_work(size_t size, diff --git a/hotspot/src/share/vm/memory/collectorPolicy.hpp b/hotspot/src/share/vm/memory/collectorPolicy.hpp index fd00a800d32..da98dfd0106 100644 --- a/hotspot/src/share/vm/memory/collectorPolicy.hpp +++ b/hotspot/src/share/vm/memory/collectorPolicy.hpp @@ -82,8 +82,11 @@ class CollectorPolicy : public CHeapObj { size_t max_alignment() { return _max_alignment; } size_t initial_heap_byte_size() { return _initial_heap_byte_size; } + void set_initial_heap_byte_size(size_t v) { _initial_heap_byte_size = v; } size_t max_heap_byte_size() { return _max_heap_byte_size; } + void set_max_heap_byte_size(size_t v) { _max_heap_byte_size = v; } size_t min_heap_byte_size() { return _min_heap_byte_size; } + void set_min_heap_byte_size(size_t v) { _min_heap_byte_size = v; } enum Name { CollectorPolicyKind, @@ -182,8 +185,24 @@ class GenCollectorPolicy : public CollectorPolicy { // compute max heap alignment size_t compute_max_alignment(); + // Scale the base_size by NewRation according to + // result = base_size / (NewRatio + 1) + // and align by min_alignment() + size_t scale_by_NewRatio_aligned(size_t base_size); + + // Bound the value by the given maximum minus the + // min_alignment. + size_t bound_minus_alignment(size_t desired_size, size_t maximum_size); public: + // Accessors + size_t min_gen0_size() { return _min_gen0_size; } + void set_min_gen0_size(size_t v) { _min_gen0_size = v; } + size_t initial_gen0_size() { return _initial_gen0_size; } + void set_initial_gen0_size(size_t v) { _initial_gen0_size = v; } + size_t max_gen0_size() { return _max_gen0_size; } + void set_max_gen0_size(size_t v) { _max_gen0_size = v; } + virtual int number_of_generations() = 0; virtual GenerationSpec **generations() { @@ -236,6 +255,14 @@ class TwoGenerationCollectorPolicy : public GenCollectorPolicy { void initialize_generations() { ShouldNotReachHere(); } public: + // Accessors + size_t min_gen1_size() { return _min_gen1_size; } + void set_min_gen1_size(size_t v) { _min_gen1_size = v; } + size_t initial_gen1_size() { return _initial_gen1_size; } + void set_initial_gen1_size(size_t v) { _initial_gen1_size = v; } + size_t max_gen1_size() { return _max_gen1_size; } + void set_max_gen1_size(size_t v) { _max_gen1_size = v; } + // Inherited methods TwoGenerationCollectorPolicy* as_two_generation_policy() { return this; } @@ -246,6 +273,10 @@ class TwoGenerationCollectorPolicy : public GenCollectorPolicy { virtual CollectorPolicy::Name kind() { return CollectorPolicy::TwoGenerationCollectorPolicyKind; } + + // Returns true is gen0 sizes were adjusted + bool adjust_gen0_sizes(size_t* gen0_size_ptr, size_t* gen1_size_ptr, + size_t heap_size, size_t min_gen1_size); }; class MarkSweepPolicy : public TwoGenerationCollectorPolicy { diff --git a/hotspot/src/share/vm/runtime/arguments.cpp b/hotspot/src/share/vm/runtime/arguments.cpp index 0e631006212..c4a1c624ac6 100644 --- a/hotspot/src/share/vm/runtime/arguments.cpp +++ b/hotspot/src/share/vm/runtime/arguments.cpp @@ -1000,7 +1000,7 @@ void Arguments::set_cms_and_parnew_gc_flags() { intx tenuring_default; if (CMSUseOldDefaults) { // old defaults: "old" as of 6.0 if FLAG_IS_DEFAULT(CMSYoungGenPerWorker) { - FLAG_SET_DEFAULT(CMSYoungGenPerWorker, 4*M); + FLAG_SET_ERGO(intx, CMSYoungGenPerWorker, 4*M); } young_gen_per_worker = 4*M; new_ratio = (intx)15; @@ -1025,16 +1025,20 @@ void Arguments::set_cms_and_parnew_gc_flags() { // for "short" pauses ~ 4M*ParallelGCThreads if (FLAG_IS_DEFAULT(MaxNewSize)) { // MaxNewSize not set at command-line if (!FLAG_IS_DEFAULT(NewSize)) { // NewSize explicitly set at command-line - FLAG_SET_DEFAULT(MaxNewSize, MAX2(NewSize, preferred_max_new_size)); + FLAG_SET_ERGO(uintx, MaxNewSize, MAX2(NewSize, preferred_max_new_size)); } else { - FLAG_SET_DEFAULT(MaxNewSize, preferred_max_new_size); + FLAG_SET_ERGO(uintx, MaxNewSize, preferred_max_new_size); } + if(PrintGCDetails && Verbose) { + // Too early to use gclog_or_tty + tty->print_cr("Ergo set MaxNewSize: " SIZE_FORMAT, MaxNewSize); + } } // Unless explicitly requested otherwise, prefer a large // Old to Young gen size so as to shift the collection load // to the old generation concurrent collector if (FLAG_IS_DEFAULT(NewRatio)) { - FLAG_SET_DEFAULT(NewRatio, MAX2(NewRatio, new_ratio)); + FLAG_SET_ERGO(intx, NewRatio, MAX2(NewRatio, new_ratio)); size_t min_new = align_size_up(ScaleForWordSize(min_new_default), os::vm_page_size()); size_t prev_initial_size = initial_heap_size(); @@ -1052,19 +1056,34 @@ void Arguments::set_cms_and_parnew_gc_flags() { size_t max_heap = align_size_down(MaxHeapSize, CardTableRS::ct_max_alignment_constraint()); + if(PrintGCDetails && Verbose) { + // Too early to use gclog_or_tty + tty->print_cr("CMS set min_heap_size: " SIZE_FORMAT + " initial_heap_size: " SIZE_FORMAT + " max_heap: " SIZE_FORMAT, + min_heap_size(), initial_heap_size(), max_heap); + } if (max_heap > min_new) { // Unless explicitly requested otherwise, make young gen // at least min_new, and at most preferred_max_new_size. if (FLAG_IS_DEFAULT(NewSize)) { - FLAG_SET_DEFAULT(NewSize, MAX2(NewSize, min_new)); - FLAG_SET_DEFAULT(NewSize, MIN2(preferred_max_new_size, NewSize)); + FLAG_SET_ERGO(uintx, NewSize, MAX2(NewSize, min_new)); + FLAG_SET_ERGO(uintx, NewSize, MIN2(preferred_max_new_size, NewSize)); + if(PrintGCDetails && Verbose) { + // Too early to use gclog_or_tty + tty->print_cr("Ergo set NewSize: " SIZE_FORMAT, NewSize); + } } // Unless explicitly requested otherwise, size old gen // so that it's at least 3X of NewSize to begin with; // later NewRatio will decide how it grows; see above. if (FLAG_IS_DEFAULT(OldSize)) { if (max_heap > NewSize) { - FLAG_SET_DEFAULT(OldSize, MIN2(3*NewSize, max_heap - NewSize)); + FLAG_SET_ERGO(uintx, OldSize, MIN2(3*NewSize, max_heap - NewSize)); + if(PrintGCDetails && Verbose) { + // Too early to use gclog_or_tty + tty->print_cr("Ergo set OldSize: " SIZE_FORMAT, OldSize); + } } } } @@ -1073,14 +1092,14 @@ void Arguments::set_cms_and_parnew_gc_flags() { // promote all objects surviving "tenuring_default" scavenges. if (FLAG_IS_DEFAULT(MaxTenuringThreshold) && FLAG_IS_DEFAULT(SurvivorRatio)) { - FLAG_SET_DEFAULT(MaxTenuringThreshold, tenuring_default); + FLAG_SET_ERGO(intx, MaxTenuringThreshold, tenuring_default); } // If we decided above (or user explicitly requested) // `promote all' (via MaxTenuringThreshold := 0), // prefer minuscule survivor spaces so as not to waste // space for (non-existent) survivors if (FLAG_IS_DEFAULT(SurvivorRatio) && MaxTenuringThreshold == 0) { - FLAG_SET_DEFAULT(SurvivorRatio, MAX2((intx)1024, SurvivorRatio)); + FLAG_SET_ERGO(intx, SurvivorRatio, MAX2((intx)1024, SurvivorRatio)); } // If OldPLABSize is set and CMSParPromoteBlocksToClaim is not, // set CMSParPromoteBlocksToClaim equal to OldPLABSize. @@ -1089,7 +1108,11 @@ void Arguments::set_cms_and_parnew_gc_flags() { // See CR 6362902. if (!FLAG_IS_DEFAULT(OldPLABSize)) { if (FLAG_IS_DEFAULT(CMSParPromoteBlocksToClaim)) { - FLAG_SET_CMDLINE(uintx, CMSParPromoteBlocksToClaim, OldPLABSize); + // OldPLABSize is not the default value but CMSParPromoteBlocksToClaim + // is. In this situtation let CMSParPromoteBlocksToClaim follow + // the value (either from the command line or ergonomics) of + // OldPLABSize. Following OldPLABSize is an ergonomics decision. + FLAG_SET_ERGO(uintx, CMSParPromoteBlocksToClaim, OldPLABSize); } else { // OldPLABSize and CMSParPromoteBlocksToClaim are both set. @@ -1211,12 +1234,13 @@ void Arguments::set_parallel_gc_flags() { if (UseParallelOldGC) { // Par compact uses lower default values since they are treated as - // minimums. + // minimums. These are different defaults because of the different + // interpretation and are not ergonomically set. if (FLAG_IS_DEFAULT(MarkSweepDeadRatio)) { - MarkSweepDeadRatio = 1; + FLAG_SET_DEFAULT(MarkSweepDeadRatio, 1); } if (FLAG_IS_DEFAULT(PermMarkSweepDeadRatio)) { - PermMarkSweepDeadRatio = 5; + FLAG_SET_DEFAULT(PermMarkSweepDeadRatio, 5); } } } @@ -2452,7 +2476,7 @@ jint Arguments::parse(const JavaVMInitArgs* args) { return JNI_EINVAL; } - if (UseParallelGC) { + if (UseParallelGC || UseParallelOldGC) { // Set some flags for ParallelGC if needed. set_parallel_gc_flags(); } else if (UseConcMarkSweepGC) { diff --git a/hotspot/src/share/vm/runtime/globals.cpp b/hotspot/src/share/vm/runtime/globals.cpp index 50bf7658b11..139fe1c41f5 100644 --- a/hotspot/src/share/vm/runtime/globals.cpp +++ b/hotspot/src/share/vm/runtime/globals.cpp @@ -205,6 +205,18 @@ bool CommandLineFlagsEx::is_default(CommandLineFlag flag) { return (f->origin == DEFAULT); } +bool CommandLineFlagsEx::is_ergo(CommandLineFlag flag) { + assert((size_t)flag < Flag::numFlags, "bad command line flag index"); + Flag* f = &Flag::flags[flag]; + return (f->origin == ERGONOMIC); +} + +bool CommandLineFlagsEx::is_cmdline(CommandLineFlag flag) { + assert((size_t)flag < Flag::numFlags, "bad command line flag index"); + Flag* f = &Flag::flags[flag]; + return (f->origin == COMMAND_LINE); +} + bool CommandLineFlags::wasSetOnCmdline(const char* name, bool* value) { Flag* result = Flag::find_flag((char*)name, strlen(name)); if (result == NULL) return false; diff --git a/hotspot/src/share/vm/runtime/globals_extension.hpp b/hotspot/src/share/vm/runtime/globals_extension.hpp index 10d22537077..d6cc1cf58d0 100644 --- a/hotspot/src/share/vm/runtime/globals_extension.hpp +++ b/hotspot/src/share/vm/runtime/globals_extension.hpp @@ -154,6 +154,8 @@ RUNTIME_OS_FLAGS(RUNTIME_DEVELOP_FLAG_MEMBER_WITH_TYPE, RUNTIME_PD_DEVELOP_FLAG_ } CommandLineFlagWithType; #define FLAG_IS_DEFAULT(name) (CommandLineFlagsEx::is_default(FLAG_MEMBER(name))) +#define FLAG_IS_ERGO(name) (CommandLineFlagsEx::is_ergo(FLAG_MEMBER(name))) +#define FLAG_IS_CMDLINE(name) (CommandLineFlagsEx::is_cmdline(FLAG_MEMBER(name))) #define FLAG_SET_DEFAULT(name, value) ((name) = (value)) @@ -171,4 +173,6 @@ class CommandLineFlagsEx : CommandLineFlags { static void ccstrAtPut(CommandLineFlagWithType flag, ccstr value, FlagValueOrigin origin); static bool is_default(CommandLineFlag flag); + static bool is_ergo(CommandLineFlag flag); + static bool is_cmdline(CommandLineFlag flag); }; From 59cc274f16e67c317fbf2c1dc6750ea2e54f018b Mon Sep 17 00:00:00 2001 From: Steve Bohne Date: Mon, 3 Mar 2008 14:47:02 -0500 Subject: [PATCH 036/258] 6655385: Disable frame pointer omission in jvm.dll on Windows for better crash logs Add /Oy- C++ compiler option on Windows Reviewed-by: phh, never, ysr --- hotspot/build/windows/makefiles/compile.make | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/hotspot/build/windows/makefiles/compile.make b/hotspot/build/windows/makefiles/compile.make index 6bc4ed1ddce..7292774e1b5 100644 --- a/hotspot/build/windows/makefiles/compile.make +++ b/hotspot/build/windows/makefiles/compile.make @@ -44,6 +44,10 @@ CPP=cl.exe # /Od Disable all optimizations # # NOTE: Normally following any of the above with a '-' will turn off that flag +# +# 6655385: For VS2003/2005 we now specify /Oy- (disable frame pointer +# omission.) This has little to no effect on performance while vastly +# improving the quality of crash log stack traces involving jvm.dll. # These are always used in all compiles CPP_FLAGS=/nologo /W3 /WX @@ -141,14 +145,14 @@ DEBUG_OPT_OPTION = /Od !endif !if "$(COMPILER_NAME)" == "VS2003" -PRODUCT_OPT_OPTION = /O2 -FASTDEBUG_OPT_OPTION = /O2 +PRODUCT_OPT_OPTION = /O2 /Oy- +FASTDEBUG_OPT_OPTION = /O2 /Oy- DEBUG_OPT_OPTION = /Od !endif !if "$(COMPILER_NAME)" == "VS2005" -PRODUCT_OPT_OPTION = /O2 -FASTDEBUG_OPT_OPTION = /O2 +PRODUCT_OPT_OPTION = /O2 /Oy- +FASTDEBUG_OPT_OPTION = /O2 /Oy- DEBUG_OPT_OPTION = /Od GX_OPTION = /EHsc # This VS2005 compiler has /GS as a default and requires bufferoverflowU.lib @@ -165,8 +169,8 @@ CPP_FLAGS=$(CPP_FLAGS) /D _CRT_SECURE_NO_DEPRECATE # Compile for space above time. !if "$(Variant)" == "kernel" -PRODUCT_OPT_OPTION = /O1 -FASTDEBUG_OPT_OPTION = /O1 +PRODUCT_OPT_OPTION = /O1 /Oy- +FASTDEBUG_OPT_OPTION = /O1 /Oy- DEBUG_OPT_OPTION = /Od !endif From c953a1e7b819f2e85c90b538528bda2e2996888c Mon Sep 17 00:00:00 2001 From: Steve Bohne Date: Tue, 4 Mar 2008 09:44:24 -0500 Subject: [PATCH 037/258] 6666698: EnableBiasedLocking with BiasedLockingStartupDelay can block Watcher thread Enqueue VM_EnableBiasedLocking operation asynchronously Reviewed-by: never, xlu, kbr, acorn --- hotspot/src/share/vm/runtime/biasedLocking.cpp | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/hotspot/src/share/vm/runtime/biasedLocking.cpp b/hotspot/src/share/vm/runtime/biasedLocking.cpp index bfb3b790432..5d72f76749c 100644 --- a/hotspot/src/share/vm/runtime/biasedLocking.cpp +++ b/hotspot/src/share/vm/runtime/biasedLocking.cpp @@ -38,8 +38,11 @@ static void enable_biased_locking(klassOop k) { class VM_EnableBiasedLocking: public VM_Operation { public: - VM_EnableBiasedLocking() {} - VMOp_Type type() const { return VMOp_EnableBiasedLocking; } + VM_EnableBiasedLocking() {} + VMOp_Type type() const { return VMOp_EnableBiasedLocking; } + Mode evaluation_mode() const { return _async_safepoint; } + bool is_cheap_allocated() const { return true; } + void doit() { // Iterate the system dictionary enabling biased locking for all // currently loaded classes @@ -62,8 +65,10 @@ class EnableBiasedLockingTask : public PeriodicTask { EnableBiasedLockingTask(size_t interval_time) : PeriodicTask(interval_time) {} virtual void task() { - VM_EnableBiasedLocking op; - VMThread::execute(&op); + // Use async VM operation to avoid blocking the Watcher thread. + // VM Thread will free C heap storage. + VM_EnableBiasedLocking *op = new VM_EnableBiasedLocking(); + VMThread::execute(op); // Reclaim our storage and disenroll ourself delete this; From 17458c966079a65a7d56da554ec229c9a20549e7 Mon Sep 17 00:00:00 2001 From: Vladimir Kozlov Date: Wed, 5 Mar 2008 11:33:31 -0800 Subject: [PATCH 038/258] 6671250: In Parse::do_if() old Cmp node 'c' should be replaced with new one after BoolNode transformation In Parse::do_if() 'c' (CmpNode) node may be changed during BoolNode transformation so 'c' may became dead but the node is referenced later in the code. Reviewed-by: never --- hotspot/src/share/vm/opto/parse2.cpp | 25 +++++++++++++++++++++---- 1 file changed, 21 insertions(+), 4 deletions(-) diff --git a/hotspot/src/share/vm/opto/parse2.cpp b/hotspot/src/share/vm/opto/parse2.cpp index ae8615d0152..d66a68741da 100644 --- a/hotspot/src/share/vm/opto/parse2.cpp +++ b/hotspot/src/share/vm/opto/parse2.cpp @@ -1022,10 +1022,27 @@ void Parse::do_if(BoolTest::mask btest, Node* c) { Node* tst = _gvn.transform(tst0); BoolTest::mask taken_btest = BoolTest::illegal; BoolTest::mask untaken_btest = BoolTest::illegal; - if (btest == BoolTest::ne) { - // For now, these are the only cases of btest that matter. (More later.) - taken_btest = taken_if_true ? btest : BoolTest::eq; - untaken_btest = taken_if_true ? BoolTest::eq : btest; + + if (tst->is_Bool()) { + // Refresh c from the transformed bool node, since it may be + // simpler than the original c. Also re-canonicalize btest. + // This wins when (Bool ne (Conv2B p) 0) => (Bool ne (CmpP p NULL)). + // That can arise from statements like: if (x instanceof C) ... + if (tst != tst0) { + // Canonicalize one more time since transform can change it. + btest = tst->as_Bool()->_test._test; + if (!BoolTest(btest).is_canonical()) { + // Reverse edges one more time... + tst = _gvn.transform( tst->as_Bool()->negate(&_gvn) ); + btest = tst->as_Bool()->_test._test; + assert(BoolTest(btest).is_canonical(), "sanity"); + taken_if_true = !taken_if_true; + } + c = tst->in(1); + } + BoolTest::mask neg_btest = BoolTest(btest).negate(); + taken_btest = taken_if_true ? btest : neg_btest; + untaken_btest = taken_if_true ? neg_btest : btest; } // Generate real control flow From bf7f5e18873942c8ac65b3fb4bd13fd3dd4a4997 Mon Sep 17 00:00:00 2001 From: Vladimir Kozlov Date: Thu, 6 Mar 2008 10:30:17 -0800 Subject: [PATCH 039/258] 6667610: (Escape Analysis) retry compilation without EA if it fails During split unique types EA could exceed nodes limit and fail the method compilation. Reviewed-by: rasbold --- hotspot/src/share/vm/includeDB_compiler2 | 1 + hotspot/src/share/vm/opto/c2compiler.cpp | 13 ++++++++++-- hotspot/src/share/vm/opto/c2compiler.hpp | 1 + hotspot/src/share/vm/opto/compile.cpp | 16 ++++++++++++--- hotspot/src/share/vm/opto/compile.hpp | 9 ++++---- hotspot/src/share/vm/opto/escape.cpp | 26 +++++++++++++++++++++++- hotspot/src/share/vm/opto/parse1.cpp | 2 +- 7 files changed, 57 insertions(+), 11 deletions(-) diff --git a/hotspot/src/share/vm/includeDB_compiler2 b/hotspot/src/share/vm/includeDB_compiler2 index 01a6b9c94ce..514f6883b27 100644 --- a/hotspot/src/share/vm/includeDB_compiler2 +++ b/hotspot/src/share/vm/includeDB_compiler2 @@ -410,6 +410,7 @@ domgraph.cpp vectset.hpp escape.cpp allocation.hpp escape.cpp bcEscapeAnalyzer.hpp +escape.cpp c2compiler.hpp escape.cpp callnode.hpp escape.cpp cfgnode.hpp escape.cpp compile.hpp diff --git a/hotspot/src/share/vm/opto/c2compiler.cpp b/hotspot/src/share/vm/opto/c2compiler.cpp index 6543e692bde..591b7ea05c2 100644 --- a/hotspot/src/share/vm/opto/c2compiler.cpp +++ b/hotspot/src/share/vm/opto/c2compiler.cpp @@ -35,6 +35,9 @@ extern const int register_save_type[]; const char* C2Compiler::retry_no_subsuming_loads() { return "retry without subsuming loads"; } +const char* C2Compiler::retry_no_escape_analysis() { + return "retry without escape analysis"; +} void C2Compiler::initialize_runtime() { // Check assumptions used while running ADLC @@ -101,17 +104,23 @@ void C2Compiler::compile_method(ciEnv* env, initialize(); } bool subsume_loads = true; + bool do_escape_analysis = DoEscapeAnalysis; while (!env->failing()) { // Attempt to compile while subsuming loads into machine instructions. - Compile C(env, this, target, entry_bci, subsume_loads); + Compile C(env, this, target, entry_bci, subsume_loads, do_escape_analysis); // Check result and retry if appropriate. if (C.failure_reason() != NULL) { - if (C.failure_reason_is(retry_no_subsuming_loads())) { + if (C.failure_reason_is(retry_no_subsuming_loads())) { assert(subsume_loads, "must make progress"); subsume_loads = false; continue; // retry } + if (C.failure_reason_is(retry_no_escape_analysis())) { + assert(do_escape_analysis, "must make progress"); + do_escape_analysis = false; + continue; // retry + } // Pass any other failure reason up to the ciEnv. // Note that serious, irreversible failures are already logged // on the ciEnv via env->record_method_not_compilable(). diff --git a/hotspot/src/share/vm/opto/c2compiler.hpp b/hotspot/src/share/vm/opto/c2compiler.hpp index dc5851082a4..a1d578797af 100644 --- a/hotspot/src/share/vm/opto/c2compiler.hpp +++ b/hotspot/src/share/vm/opto/c2compiler.hpp @@ -50,6 +50,7 @@ public: // sentinel value used to trigger backtracking in compile_method(). static const char* retry_no_subsuming_loads(); + static const char* retry_no_escape_analysis(); // Print compilation timers and statistics void print_timers(); diff --git a/hotspot/src/share/vm/opto/compile.cpp b/hotspot/src/share/vm/opto/compile.cpp index d62dbf3442f..475b281a89a 100644 --- a/hotspot/src/share/vm/opto/compile.cpp +++ b/hotspot/src/share/vm/opto/compile.cpp @@ -333,6 +333,12 @@ void Compile::print_compile_messages() { tty->print_cr("** Bailout: Recompile without subsuming loads **"); tty->print_cr("*********************************************************"); } + if (_do_escape_analysis != DoEscapeAnalysis && PrintOpto) { + // Recompiling without escape analysis + tty->print_cr("*********************************************************"); + tty->print_cr("** Bailout: Recompile without escape analysis **"); + tty->print_cr("*********************************************************"); + } if (env()->break_at_compile()) { // Open the debugger when compiing this method. tty->print("### Breaking when compiling: "); @@ -415,7 +421,7 @@ debug_only( int Compile::_debug_idx = 100000; ) // the continuation bci for on stack replacement. -Compile::Compile( ciEnv* ci_env, C2Compiler* compiler, ciMethod* target, int osr_bci, bool subsume_loads ) +Compile::Compile( ciEnv* ci_env, C2Compiler* compiler, ciMethod* target, int osr_bci, bool subsume_loads, bool do_escape_analysis ) : Phase(Compiler), _env(ci_env), _log(ci_env->log()), @@ -430,6 +436,7 @@ Compile::Compile( ciEnv* ci_env, C2Compiler* compiler, ciMethod* target, int osr _for_igvn(NULL), _warm_calls(NULL), _subsume_loads(subsume_loads), + _do_escape_analysis(do_escape_analysis), _failure_reason(NULL), _code_buffer("Compile::Fill_buffer"), _orig_pc_slot(0), @@ -487,7 +494,7 @@ Compile::Compile( ciEnv* ci_env, C2Compiler* compiler, ciMethod* target, int osr PhaseGVN gvn(node_arena(), estimated_size); set_initial_gvn(&gvn); - if (DoEscapeAnalysis) + if (_do_escape_analysis) _congraph = new ConnectionGraph(this); { // Scope for timing the parser @@ -577,6 +584,8 @@ Compile::Compile( ciEnv* ci_env, C2Compiler* compiler, ciMethod* target, int osr if (_congraph != NULL) { NOT_PRODUCT( TracePhase t2("escapeAnalysis", &_t_escapeAnalysis, TimeCompiler); ) _congraph->compute_escape(); + if (failing()) return; + #ifndef PRODUCT if (PrintEscapeAnalysis) { _congraph->dump(); @@ -675,6 +684,7 @@ Compile::Compile( ciEnv* ci_env, _orig_pc_slot(0), _orig_pc_slot_offset_in_bytes(0), _subsume_loads(true), + _do_escape_analysis(false), _failure_reason(NULL), _code_buffer("Compile::Fill_buffer"), _node_bundling_limit(0), @@ -822,7 +832,7 @@ void Compile::Init(int aliaslevel) { // Type::update_loaded_types(_method, _method->constants()); // Init alias_type map. - if (!DoEscapeAnalysis && aliaslevel == 3) + if (!_do_escape_analysis && aliaslevel == 3) aliaslevel = 2; // No unique types without escape analysis _AliasLevel = aliaslevel; const int grow_ats = 16; diff --git a/hotspot/src/share/vm/opto/compile.hpp b/hotspot/src/share/vm/opto/compile.hpp index fcab3a37864..a4e4c1401f3 100644 --- a/hotspot/src/share/vm/opto/compile.hpp +++ b/hotspot/src/share/vm/opto/compile.hpp @@ -31,6 +31,7 @@ class InlineTree; class Int_Array; class Matcher; class MachNode; +class MachSafePointNode; class Node; class Node_Array; class Node_Notes; @@ -52,9 +53,6 @@ class TypeFunc; class Unique_Node_List; class nmethod; class WarmCallInfo; -#ifdef ENABLE_ZAP_DEAD_LOCALS -class MachSafePointNode; -#endif //------------------------------Compile---------------------------------------- // This class defines a top-level Compiler invocation. @@ -127,6 +125,7 @@ class Compile : public Phase { const int _compile_id; const bool _save_argument_registers; // save/restore arg regs for trampolines const bool _subsume_loads; // Load can be matched as part of a larger op. + const bool _do_escape_analysis; // Do escape analysis. ciMethod* _method; // The method being compiled. int _entry_bci; // entry bci for osr methods. const TypeFunc* _tf; // My kind of signature @@ -260,6 +259,8 @@ class Compile : public Phase { // instructions that subsume a load may result in an unschedulable // instruction sequence. bool subsume_loads() const { return _subsume_loads; } + // Do escape analysis. + bool do_escape_analysis() const { return _do_escape_analysis; } bool save_argument_registers() const { return _save_argument_registers; } @@ -560,7 +561,7 @@ class Compile : public Phase { // replacement, entry_bci indicates the bytecode for which to compile a // continuation. Compile(ciEnv* ci_env, C2Compiler* compiler, ciMethod* target, - int entry_bci, bool subsume_loads); + int entry_bci, bool subsume_loads, bool do_escape_analysis); // Second major entry point. From the TypeFunc signature, generate code // to pass arguments from the Java calling convention to the C calling diff --git a/hotspot/src/share/vm/opto/escape.cpp b/hotspot/src/share/vm/opto/escape.cpp index 62d0c0f1ac5..d66dd3f9866 100644 --- a/hotspot/src/share/vm/opto/escape.cpp +++ b/hotspot/src/share/vm/opto/escape.cpp @@ -395,6 +395,15 @@ PhiNode *ConnectionGraph::create_split_phi(PhiNode *orig_phi, int alias_idx, Gro if (result != NULL && C->get_alias_index(result->adr_type()) == alias_idx) { return result; } + if ((int)C->unique() + 2*NodeLimitFudgeFactor > MaxNodeLimit) { + if (C->do_escape_analysis() == true && !C->failing()) { + // Retry compilation without escape analysis. + // If this is the first failure, the sentinel string will "stick" + // to the Compile object, and the C2Compiler will see it and retry. + C->record_failure(C2Compiler::retry_no_escape_analysis()); + } + return NULL; + } orig_phi_worklist.append_if_missing(orig_phi); result = PhiNode::make(orig_phi->in(0), NULL, Type::MEMORY, atype); @@ -443,6 +452,9 @@ PhiNode *ConnectionGraph::split_memory_phi(PhiNode *orig_phi, int alias_idx, Gro mem = nphi; } } + if (C->failing()) { + return NULL; + } result->set_req(idx++, mem); } #ifdef ASSERT @@ -672,6 +684,9 @@ void ConnectionGraph::split_unique_types(GrowableArray &alloc_worklist) if (mem->is_Phi()) { mem = split_memory_phi(mem->as_Phi(), alias_idx, orig_phis, igvn); } + if (_compile->failing()) { + return; + } if (mem != n->in(MemNode::Memory)) set_map(n->_idx, mem); if (n->is_Load()) { @@ -742,7 +757,11 @@ void ConnectionGraph::split_unique_types(GrowableArray &alloc_worklist) if((uint)_compile->get_general_index(ni) == i) { Node *m = (ni >= nmm->req()) ? nmm->empty_memory() : nmm->in(ni); if (nmm->is_empty_memory(m)) { - nmm->set_memory_at(ni, split_memory_phi(mem->as_Phi(), ni, orig_phis, igvn)); + m = split_memory_phi(mem->as_Phi(), ni, orig_phis, igvn); + if (_compile->failing()) { + return; + } + nmm->set_memory_at(ni, m); } } } @@ -881,6 +900,11 @@ void ConnectionGraph::compute_escape() { // Now use the escape information to create unique types for // unescaped objects split_unique_types(alloc_worklist); + if (_compile->failing()) return; + + // Clean up after split unique types. + ResourceMark rm; + PhaseRemoveUseless pru(_compile->initial_gvn(), _compile->for_igvn()); } Node * ConnectionGraph::skip_casts(Node *n) { diff --git a/hotspot/src/share/vm/opto/parse1.cpp b/hotspot/src/share/vm/opto/parse1.cpp index 4f8e93162cc..e3edece1a15 100644 --- a/hotspot/src/share/vm/opto/parse1.cpp +++ b/hotspot/src/share/vm/opto/parse1.cpp @@ -1836,7 +1836,7 @@ PhiNode *Parse::ensure_phi(int idx, bool nocreate) { PhiNode* phi = PhiNode::make(region, o, t); gvn().set_type(phi, t); - if (DoEscapeAnalysis) record_for_igvn(phi); + if (C->do_escape_analysis()) record_for_igvn(phi); map->set_req(idx, phi); return phi; } From 277c3322f6b6c0e232ca813e806b819ca5fd6bd8 Mon Sep 17 00:00:00 2001 From: Vladimir Kozlov Date: Thu, 6 Mar 2008 10:53:33 -0800 Subject: [PATCH 040/258] 6667612: (Escape Analysis) disable loop cloning if it has a scalar replaceable allocation Cloning an allocation will not allow scalar replacement since memory operations could not be associated with one allocation. Reviewed-by: rasbold --- hotspot/src/share/vm/opto/callnode.cpp | 1 + hotspot/src/share/vm/opto/callnode.hpp | 2 ++ hotspot/src/share/vm/opto/escape.cpp | 5 +++++ hotspot/src/share/vm/opto/loopTransform.cpp | 1 + hotspot/src/share/vm/opto/loopnode.cpp | 10 ++++++++-- hotspot/src/share/vm/opto/loopnode.hpp | 4 +++- 6 files changed, 20 insertions(+), 3 deletions(-) diff --git a/hotspot/src/share/vm/opto/callnode.cpp b/hotspot/src/share/vm/opto/callnode.cpp index 7fb60044039..f32562de0e4 100644 --- a/hotspot/src/share/vm/opto/callnode.cpp +++ b/hotspot/src/share/vm/opto/callnode.cpp @@ -832,6 +832,7 @@ AllocateNode::AllocateNode(Compile* C, const TypeFunc *atype, { init_class_id(Class_Allocate); init_flags(Flag_is_macro); + _is_scalar_replaceable = false; Node *topnode = C->top(); init_req( TypeFunc::Control , ctrl ); diff --git a/hotspot/src/share/vm/opto/callnode.hpp b/hotspot/src/share/vm/opto/callnode.hpp index c8315f94c96..d07a4d78d0e 100644 --- a/hotspot/src/share/vm/opto/callnode.hpp +++ b/hotspot/src/share/vm/opto/callnode.hpp @@ -626,6 +626,8 @@ public: return TypeFunc::make(domain, range); } + bool _is_scalar_replaceable; // Result of Escape Analysis + virtual uint size_of() const; // Size is bigger AllocateNode(Compile* C, const TypeFunc *atype, Node *ctrl, Node *mem, Node *abio, Node *size, Node *klass_node, Node *initial_test); diff --git a/hotspot/src/share/vm/opto/escape.cpp b/hotspot/src/share/vm/opto/escape.cpp index d66dd3f9866..7e2a18d8539 100644 --- a/hotspot/src/share/vm/opto/escape.cpp +++ b/hotspot/src/share/vm/opto/escape.cpp @@ -601,6 +601,11 @@ void ConnectionGraph::split_unique_types(GrowableArray &alloc_worklist) if (es != PointsToNode::NoEscape || !ptn._unique_type) { continue; // can't make a unique type } + if (alloc->is_Allocate()) { + // Set the scalar_replaceable flag before the next check. + alloc->as_Allocate()->_is_scalar_replaceable = true; + } + set_map(alloc->_idx, n); set_map(n->_idx, alloc); const TypeInstPtr *t = igvn->type(n)->isa_instptr(); diff --git a/hotspot/src/share/vm/opto/loopTransform.cpp b/hotspot/src/share/vm/opto/loopTransform.cpp index 3de4e0cd752..de54863b5ba 100644 --- a/hotspot/src/share/vm/opto/loopTransform.cpp +++ b/hotspot/src/share/vm/opto/loopTransform.cpp @@ -1714,6 +1714,7 @@ void IdealLoopTree::iteration_split( PhaseIdealLoop *phase, Node_List &old_new ) // Gate unrolling, RCE and peeling efforts. if( !_child && // If not an inner loop, do not split !_irreducible && + _allow_optimizations && !tail()->is_top() ) { // Also ignore the occasional dead backedge if (!_has_call) { iteration_split_impl( phase, old_new ); diff --git a/hotspot/src/share/vm/opto/loopnode.cpp b/hotspot/src/share/vm/opto/loopnode.cpp index 96140fae598..3ae7a41143e 100644 --- a/hotspot/src/share/vm/opto/loopnode.cpp +++ b/hotspot/src/share/vm/opto/loopnode.cpp @@ -1561,7 +1561,7 @@ PhaseIdealLoop::PhaseIdealLoop( PhaseIterGVN &igvn, const PhaseIdealLoop *verify // on just their loop-phi's for this pass of loop opts if( SplitIfBlocks && do_split_ifs ) { if (lpt->policy_range_check(this)) { - lpt->_rce_candidate = true; + lpt->_rce_candidate = 1; // = true } } } @@ -2145,7 +2145,7 @@ int PhaseIdealLoop::build_loop_tree_impl( Node *n, int pre_order ) { // as well? If so, then I found another entry into the loop. while( is_postvisited(l->_head) ) { // found irreducible - l->_irreducible = true; + l->_irreducible = 1; // = true l = l->_parent; _has_irreducible_loops = true; // Check for bad CFG here to prevent crash, and bailout of compile @@ -2199,6 +2199,12 @@ int PhaseIdealLoop::build_loop_tree_impl( Node *n, int pre_order ) { (iff->as_If()->_prob >= 0.01) ) innermost->_has_call = 1; } + } else if( n->is_Allocate() && n->as_Allocate()->_is_scalar_replaceable ) { + // Disable loop optimizations if the loop has a scalar replaceable + // allocation. This disabling may cause a potential performance lost + // if the allocation is not eliminated for some reason. + innermost->_allow_optimizations = false; + innermost->_has_call = 1; // = true } } } diff --git a/hotspot/src/share/vm/opto/loopnode.hpp b/hotspot/src/share/vm/opto/loopnode.hpp index 60944afeee8..4bee9655d9f 100644 --- a/hotspot/src/share/vm/opto/loopnode.hpp +++ b/hotspot/src/share/vm/opto/loopnode.hpp @@ -289,13 +289,15 @@ public: _has_sfpt:1, // True if has non-call safepoint _rce_candidate:1; // True if candidate for range check elimination - Node_List* _required_safept; // A inner loop cannot delete these safepts; + Node_List* _required_safept; // A inner loop cannot delete these safepts; + bool _allow_optimizations; // Allow loop optimizations IdealLoopTree( PhaseIdealLoop* phase, Node *head, Node *tail ) : _parent(0), _next(0), _child(0), _head(head), _tail(tail), _phase(phase), _required_safept(NULL), + _allow_optimizations(true), _nest(0), _irreducible(0), _has_call(0), _has_sfpt(0), _rce_candidate(0) { } From 37b9a97e0882cd4e463349c50b172b21e6f03c91 Mon Sep 17 00:00:00 2001 From: Vladimir Kozlov Date: Thu, 6 Mar 2008 20:58:16 -0800 Subject: [PATCH 041/258] 6670459: Fix Node::dump() performance Dump full ideal graph takes forever. Reviewed-by: never, rasbold --- hotspot/src/share/vm/opto/node.cpp | 112 ++++++++--------------------- hotspot/src/share/vm/opto/node.hpp | 2 +- 2 files changed, 30 insertions(+), 84 deletions(-) diff --git a/hotspot/src/share/vm/opto/node.cpp b/hotspot/src/share/vm/opto/node.cpp index 14e112e2101..f361ef8b888 100644 --- a/hotspot/src/share/vm/opto/node.cpp +++ b/hotspot/src/share/vm/opto/node.cpp @@ -1462,26 +1462,6 @@ void Node::dump_out() const { } //------------------------------dump_nodes------------------------------------- - -// Helper class for dump_nodes. Wraps an old and new VectorSet. -class OldNewVectorSet : public StackObj { - Arena* _node_arena; - VectorSet _old_vset, _new_vset; - VectorSet* select(Node* n) { - return _node_arena->contains(n) ? &_new_vset : &_old_vset; - } - public: - OldNewVectorSet(Arena* node_arena, ResourceArea* area) : - _node_arena(node_arena), - _old_vset(area), _new_vset(area) {} - - void set(Node* n) { select(n)->set(n->_idx); } - bool test_set(Node* n) { return select(n)->test_set(n->_idx) != 0; } - bool test(Node* n) { return select(n)->test(n->_idx) != 0; } - void del(Node* n) { (*select(n)) >>= n->_idx; } -}; - - static void dump_nodes(const Node* start, int d, bool only_ctrl) { Node* s = (Node*)start; // remove const if (NotANode(s)) return; @@ -1489,75 +1469,41 @@ static void dump_nodes(const Node* start, int d, bool only_ctrl) { uint depth = (uint)ABS(d); int direction = d; Compile* C = Compile::current(); - ResourceArea *area = Thread::current()->resource_area(); - Node_Stack stack(area, MIN2(depth, C->unique() >> 1)); - OldNewVectorSet dumped(C->node_arena(), area); - OldNewVectorSet on_stack(C->node_arena(), area); + GrowableArray nstack(C->unique()); - on_stack.set(s); - stack.push(s, 0); - if (direction < 0) { - dumped.set(s); - s->dump(); - } + nstack.append(s); + int begin = 0; + int end = 0; + for(uint i = 0; i < depth; i++) { + end = nstack.length(); + for(int j = begin; j < end; j++) { + Node* tp = nstack.at(j); + uint limit = direction > 0 ? tp->len() : tp->outcnt(); + for(uint k = 0; k < limit; k++) { + Node* n = direction > 0 ? tp->in(k) : tp->raw_out(k); - // Do a depth first walk over edges - while (stack.is_nonempty()) { - Node* tp = stack.node(); - uint idx = stack.index(); - uint limit; - // Limit depth - if (stack.size() < depth) { - limit = direction > 0 ? tp->len() : tp->outcnt(); - } else { - limit = 0; // reached depth limit. - } - if (idx >= limit) { - // no more arcs to visit - if (direction > 0 && !dumped.test_set(tp)) tp->dump(); - on_stack.del(tp); - stack.pop(); - } else { - // process the "idx"th arc - stack.set_index(idx + 1); - Node* n = direction > 0 ? tp->in(idx) : tp->raw_out(idx); + if (NotANode(n)) continue; + // do not recurse through top or the root (would reach unrelated stuff) + if (n->is_Root() || n->is_top()) continue; + if (only_ctrl && !n->is_CFG()) continue; - if (NotANode(n)) continue; - // do not recurse through top or the root (would reach unrelated stuff) - if (n->is_Root() || n->is_top()) continue; - if (only_ctrl && !n->is_CFG()) continue; - - if (!on_stack.test(n)) { // forward arc - if (direction < 0 && !dumped.test_set(n)) n->dump(); - stack.push(n, 0); - on_stack.set(n); - } else { // back or cross arc - // print loop if there are no phis or regions in the mix - bool found_loop_breaker = false; - int k; - for (k = stack.size() - 1; k >= 0; k--) { - Node* m = stack.node_at(k); - if (m->is_Phi() || m->is_Region() || m->is_Root() || m->is_Start()) { - found_loop_breaker = true; - break; - } - if (m == n) // Found loop head - break; - } - assert(k >= 0, "n must be on stack"); - - if (!found_loop_breaker) { - tty->print("# %s LOOP FOUND:", only_ctrl ? "CONTROL" : "DATA"); - for (int i = stack.size() - 1; i >= k; i--) { - Node* m = stack.node_at(i); - bool mnew = C->node_arena()->contains(m); - tty->print(" %s%d:%s", (mnew? "": "o"), m->_idx, m->Name()); - if (i != 0) tty->print(direction > 0? " <-": " ->"); - } - tty->cr(); + bool on_stack = nstack.contains(n); + if (!on_stack) { + nstack.append(n); } } } + begin = end; + } + end = nstack.length(); + if (direction > 0) { + for(int j = end-1; j >= 0; j--) { + nstack.at(j)->dump(); + } + } else { + for(int j = 0; j < end; j++) { + nstack.at(j)->dump(); + } } } diff --git a/hotspot/src/share/vm/opto/node.hpp b/hotspot/src/share/vm/opto/node.hpp index 8066da703ba..881de4d21b9 100644 --- a/hotspot/src/share/vm/opto/node.hpp +++ b/hotspot/src/share/vm/opto/node.hpp @@ -1384,7 +1384,7 @@ public: _inode_top->indx = i; } uint size_max() const { return (uint)pointer_delta(_inode_max, _inodes, sizeof(INode)); } // Max size - uint size() const { return (uint)pointer_delta(_inode_top, _inodes, sizeof(INode)) + 1; } // Current size + uint size() const { return (uint)pointer_delta((_inode_top+1), _inodes, sizeof(INode)); } // Current size bool is_nonempty() const { return (_inode_top >= _inodes); } bool is_empty() const { return (_inode_top < _inodes); } void clear() { _inode_top = _inodes - 1; } // retain storage From 9ec574b7e69a5d964a8185d71f8c5e602deb66f1 Mon Sep 17 00:00:00 2001 From: Vladimir Kozlov Date: Fri, 7 Mar 2008 11:09:13 -0800 Subject: [PATCH 042/258] 6667605: (Escape Analysis) inline java constructors when EA is on Java constructors should be inlined to be able scalar replace a new object Reviewed-by: rasbold --- hotspot/src/share/vm/opto/bytecodeInfo.cpp | 95 +++++++++++++++++----- hotspot/src/share/vm/opto/parse.hpp | 6 +- hotspot/src/share/vm/opto/phaseX.cpp | 80 ++---------------- 3 files changed, 85 insertions(+), 96 deletions(-) diff --git a/hotspot/src/share/vm/opto/bytecodeInfo.cpp b/hotspot/src/share/vm/opto/bytecodeInfo.cpp index 10648c654ac..1b12ee877ad 100644 --- a/hotspot/src/share/vm/opto/bytecodeInfo.cpp +++ b/hotspot/src/share/vm/opto/bytecodeInfo.cpp @@ -79,8 +79,20 @@ static void print_indent(int depth) { for (int i = depth; i != 0; --i) tty->print(" "); } +static bool is_init_with_ea(ciMethod* callee_method, + ciMethod* caller_method, Compile* C) { + // True when EA is ON and a java constructor is called or + // a super constructor is called from an inlined java constructor. + return DoEscapeAnalysis && EliminateAllocations && + ( callee_method->is_initializer() || + (caller_method->is_initializer() && + caller_method != C->method() && + caller_method->holder()->is_subclass_of(callee_method->holder())) + ); +} + // positive filter: should send be inlined? returns NULL, if yes, or rejection msg -const char* InlineTree::shouldInline(ciMethod* callee_method, int caller_bci, ciCallProfile& profile, WarmCallInfo* wci_result) const { +const char* InlineTree::shouldInline(ciMethod* callee_method, ciMethod* caller_method, int caller_bci, ciCallProfile& profile, WarmCallInfo* wci_result) const { // Allows targeted inlining if(callee_method->should_inline()) { *wci_result = *(WarmCallInfo::always_hot()); @@ -97,7 +109,8 @@ const char* InlineTree::shouldInline(ciMethod* callee_method, int caller_bci, ci int size = callee_method->code_size(); // Check for too many throws (and not too huge) - if(callee_method->interpreter_throwout_count() > InlineThrowCount && size < InlineThrowMaxSize ) { + if(callee_method->interpreter_throwout_count() > InlineThrowCount && + size < InlineThrowMaxSize ) { wci_result->set_profit(wci_result->profit() * 100); if (PrintInlining && Verbose) { print_indent(inline_depth()); @@ -114,8 +127,12 @@ const char* InlineTree::shouldInline(ciMethod* callee_method, int caller_bci, ci int invoke_count = method()->interpreter_invocation_count(); assert( invoke_count != 0, "Require invokation count greater than zero"); int freq = call_site_count/invoke_count; + // bump the max size if the call is frequent - if ((freq >= InlineFrequencyRatio) || (call_site_count >= InlineFrequencyCount)) { + if ((freq >= InlineFrequencyRatio) || + (call_site_count >= InlineFrequencyCount) || + is_init_with_ea(callee_method, caller_method, C)) { + max_size = C->freq_inline_size(); if (size <= max_size && TraceFrequencyInlining) { print_indent(inline_depth()); @@ -126,7 +143,8 @@ const char* InlineTree::shouldInline(ciMethod* callee_method, int caller_bci, ci } } else { // Not hot. Check for medium-sized pre-existing nmethod at cold sites. - if (callee_method->has_compiled_code() && callee_method->instructions_size() > InlineSmallCode/4) + if (callee_method->has_compiled_code() && + callee_method->instructions_size() > InlineSmallCode/4) return "already compiled into a medium method"; } if (size > max_size) { @@ -139,7 +157,7 @@ const char* InlineTree::shouldInline(ciMethod* callee_method, int caller_bci, ci // negative filter: should send NOT be inlined? returns NULL, ok to inline, or rejection msg -const char* InlineTree::shouldNotInline(ciMethod *callee_method, WarmCallInfo* wci_result) const { +const char* InlineTree::shouldNotInline(ciMethod *callee_method, ciMethod* caller_method, WarmCallInfo* wci_result) const { // negative filter: should send NOT be inlined? returns NULL (--> inline) or rejection msg if (!UseOldInlining) { const char* fail = NULL; @@ -204,9 +222,23 @@ const char* InlineTree::shouldNotInline(ciMethod *callee_method, WarmCallInfo* w // use frequency-based objections only for non-trivial methods if (callee_method->code_size() <= MaxTrivialSize) return NULL; - if (UseInterpreter && !CompileTheWorld) { // don't use counts with -Xcomp or CTW - if (!callee_method->has_compiled_code() && !callee_method->was_executed_more_than(0)) return "never executed"; - if (!callee_method->was_executed_more_than(MIN2(MinInliningThreshold, CompileThreshold >> 1))) return "executed < MinInliningThreshold times"; + + // don't use counts with -Xcomp or CTW + if (UseInterpreter && !CompileTheWorld) { + + if (!callee_method->has_compiled_code() && + !callee_method->was_executed_more_than(0)) { + return "never executed"; + } + + if (is_init_with_ea(callee_method, caller_method, C)) { + + // Escape Analysis: inline all executed constructors + + } else if (!callee_method->was_executed_more_than(MIN2(MinInliningThreshold, + CompileThreshold >> 1))) { + return "executed < MinInliningThreshold times"; + } } if (callee_method->should_not_inline()) { @@ -219,8 +251,7 @@ const char* InlineTree::shouldNotInline(ciMethod *callee_method, WarmCallInfo* w //-----------------------------try_to_inline----------------------------------- // return NULL if ok, reason for not inlining otherwise // Relocated from "InliningClosure::try_to_inline" -const char* InlineTree::try_to_inline(ciMethod* callee_method, int caller_bci, ciCallProfile& profile, WarmCallInfo* wci_result) { - ciMethod* caller_method = method(); +const char* InlineTree::try_to_inline(ciMethod* callee_method, ciMethod* caller_method, int caller_bci, ciCallProfile& profile, WarmCallInfo* wci_result) { // Old algorithm had funny accumulating BC-size counters if (UseOldInlining && ClipInlining @@ -229,25 +260,47 @@ const char* InlineTree::try_to_inline(ciMethod* callee_method, int caller_bci, c } const char *msg = NULL; - if ((msg = shouldInline(callee_method, caller_bci, profile, wci_result)) != NULL) return msg; - if ((msg = shouldNotInline(callee_method, wci_result)) != NULL) return msg; + if ((msg = shouldInline(callee_method, caller_method, caller_bci, + profile, wci_result)) != NULL) { + return msg; + } + if ((msg = shouldNotInline(callee_method, caller_method, + wci_result)) != NULL) { + return msg; + } bool is_accessor = InlineAccessors && callee_method->is_accessor(); // suppress a few checks for accessors and trivial methods if (!is_accessor && callee_method->code_size() > MaxTrivialSize) { - // don't inline into giant methods - if (C->unique() > (uint)NodeCountInliningCutoff) return "NodeCountInliningCutoff"; - // don't inline unreached call sites - if (profile.count() == 0) return "call site not reached"; + // don't inline into giant methods + if (C->unique() > (uint)NodeCountInliningCutoff) { + return "NodeCountInliningCutoff"; + } + + if ((!UseInterpreter || CompileTheWorld) && + is_init_with_ea(callee_method, caller_method, C)) { + + // Escape Analysis stress testing when running Xcomp or CTW: + // inline constructors even if they are not reached. + + } else if (profile.count() == 0) { + // don't inline unreached call sites + return "call site not reached"; + } } - if (!C->do_inlining() && InlineAccessors && !is_accessor) return "not an accessor"; - - if( inline_depth() > MaxInlineLevel ) return "inlining too deep"; + if (!C->do_inlining() && InlineAccessors && !is_accessor) { + return "not an accessor"; + } + if( inline_depth() > MaxInlineLevel ) { + return "inlining too deep"; + } if( method() == callee_method && - inline_depth() > MaxRecursiveInlineLevel ) return "recursively inlining too deep"; + inline_depth() > MaxRecursiveInlineLevel ) { + return "recursively inlining too deep"; + } int size = callee_method->code_size(); @@ -336,7 +389,7 @@ WarmCallInfo* InlineTree::ok_to_inline(ciMethod* callee_method, JVMState* jvms, // Check if inlining policy says no. WarmCallInfo wci = *(initial_wci); - failure_msg = try_to_inline(callee_method, caller_bci, profile, &wci); + failure_msg = try_to_inline(callee_method, caller_method, caller_bci, profile, &wci); if (failure_msg != NULL && C->log() != NULL) { C->log()->begin_elem("inline_fail reason='"); C->log()->text("%s", failure_msg); diff --git a/hotspot/src/share/vm/opto/parse.hpp b/hotspot/src/share/vm/opto/parse.hpp index 60ffdf17dd7..df2bc6cd54a 100644 --- a/hotspot/src/share/vm/opto/parse.hpp +++ b/hotspot/src/share/vm/opto/parse.hpp @@ -54,9 +54,9 @@ protected: InlineTree *build_inline_tree_for_callee(ciMethod* callee_method, JVMState* caller_jvms, int caller_bci); - const char* try_to_inline(ciMethod* callee_method, int caller_bci, ciCallProfile& profile, WarmCallInfo* wci_result); - const char* shouldInline(ciMethod* callee_method, int caller_bci, ciCallProfile& profile, WarmCallInfo* wci_result) const; - const char* shouldNotInline(ciMethod* callee_method, WarmCallInfo* wci_result) const; + const char* try_to_inline(ciMethod* callee_method, ciMethod* caller_method, int caller_bci, ciCallProfile& profile, WarmCallInfo* wci_result); + const char* shouldInline(ciMethod* callee_method, ciMethod* caller_method, int caller_bci, ciCallProfile& profile, WarmCallInfo* wci_result) const; + const char* shouldNotInline(ciMethod* callee_method, ciMethod* caller_method, WarmCallInfo* wci_result) const; void print_inlining(ciMethod *callee_method, int caller_bci, const char *failure_msg) const PRODUCT_RETURN; InlineTree *caller_tree() const { return _caller_tree; } diff --git a/hotspot/src/share/vm/opto/phaseX.cpp b/hotspot/src/share/vm/opto/phaseX.cpp index 3c5cd2cca13..90b34d4afad 100644 --- a/hotspot/src/share/vm/opto/phaseX.cpp +++ b/hotspot/src/share/vm/opto/phaseX.cpp @@ -648,79 +648,9 @@ ConNode* PhaseTransform::zerocon(BasicType bt) { //============================================================================= //------------------------------transform-------------------------------------- // Return a node which computes the same function as this node, but in a -// faster or cheaper fashion. The Node passed in here must have no other -// pointers to it, as its storage will be reclaimed if the Node can be -// optimized away. +// faster or cheaper fashion. Node *PhaseGVN::transform( Node *n ) { - NOT_PRODUCT( set_transforms(); ) - - // Apply the Ideal call in a loop until it no longer applies - Node *k = n; - NOT_PRODUCT( uint loop_count = 0; ) - while( 1 ) { - Node *i = k->Ideal(this, /*can_reshape=*/false); - if( !i ) break; - assert( i->_idx >= k->_idx, "Idealize should return new nodes, use Identity to return old nodes" ); - // Can never reclaim storage for Ideal calls, because the Ideal call - // returns a new Node, bumping the High Water Mark and our old Node - // is caught behind the new one. - //if( k != i ) { - //k->destruct(); // Reclaim storage for recent node - k = i; - //} - assert(loop_count++ < K, "infinite loop in PhaseGVN::transform"); - } - NOT_PRODUCT( if( loop_count != 0 ) { set_progress(); } ) - - // If brand new node, make space in type array. - ensure_type_or_null(k); - - // Cache result of Value call since it can be expensive - // (abstract interpretation of node 'k' using phase->_types[ inputs ]) - const Type *t = k->Value(this); // Get runtime Value set - assert(t != NULL, "value sanity"); - if (type_or_null(k) != t) { -#ifndef PRODUCT - // Do not record transformation or value construction on first visit - if (type_or_null(k) == NULL) { - inc_new_values(); - set_progress(); - } -#endif - set_type(k, t); - // If k is a TypeNode, capture any more-precise type permanently into Node - k->raise_bottom_type(t); - } - - if( t->singleton() && !k->is_Con() ) { - //k->destruct(); // Reclaim storage for recent node - NOT_PRODUCT( set_progress(); ) - return makecon(t); // Turn into a constant - } - - // Now check for Identities - Node *i = k->Identity(this); // Look for a nearby replacement - if( i != k ) { // Found? Return replacement! - //k->destruct(); // Reclaim storage for recent node - NOT_PRODUCT( set_progress(); ) - return i; - } - - // Try Global Value Numbering - i = hash_find_insert(k); // Found older value when i != NULL - if( i && i != k ) { // Hit? Return the old guy - NOT_PRODUCT( set_progress(); ) - return i; - } - - // Collect points-to information for escape analysys - ConnectionGraph *cgr = C->congraph(); - if (cgr != NULL) { - cgr->record_escape(k, this); - } - - // Return Idealized original - return k; + return transform_no_reclaim(n); } //------------------------------transform-------------------------------------- @@ -784,6 +714,12 @@ Node *PhaseGVN::transform_no_reclaim( Node *n ) { return i; } + // Collect points-to information for escape analysys + ConnectionGraph *cgr = C->congraph(); + if (cgr != NULL) { + cgr->record_escape(k, this); + } + // Return Idealized original return k; } From 50708126d473ff321b2bf1d3bf22c175ff4e297e Mon Sep 17 00:00:00 2001 From: Vladimir Kozlov Date: Tue, 11 Mar 2008 11:04:40 -0700 Subject: [PATCH 043/258] 6623167: C2 crashed in StoreCMNode::Value C2 crashed in StoreCMNode::Value because n->in(MemNode::OopStore) is 0. Reviewed-by: rasbold, never --- hotspot/src/share/vm/opto/memnode.cpp | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/hotspot/src/share/vm/opto/memnode.cpp b/hotspot/src/share/vm/opto/memnode.cpp index 03f43d88595..2cfa4281c48 100644 --- a/hotspot/src/share/vm/opto/memnode.cpp +++ b/hotspot/src/share/vm/opto/memnode.cpp @@ -1771,9 +1771,16 @@ Node *StoreCMNode::Identity( PhaseTransform *phase ) { //------------------------------Value----------------------------------------- const Type *StoreCMNode::Value( PhaseTransform *phase ) const { + // Either input is TOP ==> the result is TOP + const Type *t = phase->type( in(MemNode::Memory) ); + if( t == Type::TOP ) return Type::TOP; + t = phase->type( in(MemNode::Address) ); + if( t == Type::TOP ) return Type::TOP; + t = phase->type( in(MemNode::ValueIn) ); + if( t == Type::TOP ) return Type::TOP; // If extra input is TOP ==> the result is TOP - const Type *t1 = phase->type( in(MemNode::OopStore) ); - if( t1 == Type::TOP ) return Type::TOP; + t = phase->type( in(MemNode::OopStore) ); + if( t == Type::TOP ) return Type::TOP; return StoreNode::Value( phase ); } From 96e8bcb6aaf54d9c7d7354c800e42ccf855afd43 Mon Sep 17 00:00:00 2001 From: Vladimir Kozlov Date: Tue, 11 Mar 2008 11:25:13 -0700 Subject: [PATCH 044/258] 6667620: (Escape Analysis) fix deoptimization for scalar replaced objects Deoptimization code for reallocation and relocking scalar replaced objects has to be fixed. Reviewed-by: rasbold, never --- hotspot/src/share/vm/ci/ciInstanceKlass.cpp | 35 ++++- hotspot/src/share/vm/ci/ciInstanceKlass.hpp | 9 ++ hotspot/src/share/vm/code/debugInfo.cpp | 9 +- hotspot/src/share/vm/code/scopeDesc.cpp | 4 +- hotspot/src/share/vm/oops/instanceKlass.cpp | 26 +++- .../src/share/vm/runtime/deoptimization.cpp | 135 ++++++++++++------ 6 files changed, 163 insertions(+), 55 deletions(-) diff --git a/hotspot/src/share/vm/ci/ciInstanceKlass.cpp b/hotspot/src/share/vm/ci/ciInstanceKlass.cpp index 375d5bf94b1..9710b8dd407 100644 --- a/hotspot/src/share/vm/ci/ciInstanceKlass.cpp +++ b/hotspot/src/share/vm/ci/ciInstanceKlass.cpp @@ -34,7 +34,9 @@ // ciInstanceKlass::ciInstanceKlass // // Loaded instance klass. -ciInstanceKlass::ciInstanceKlass(KlassHandle h_k) : ciKlass(h_k) { +ciInstanceKlass::ciInstanceKlass(KlassHandle h_k) : + ciKlass(h_k), _non_static_fields(NULL) +{ assert(get_Klass()->oop_is_instance(), "wrong type"); instanceKlass* ik = get_instanceKlass(); @@ -335,6 +337,37 @@ ciField* ciInstanceKlass::get_field_by_offset(int field_offset, bool is_static) return field; } +// ------------------------------------------------------------------ +// ciInstanceKlass::non_static_fields. + +class NonStaticFieldFiller: public FieldClosure { + GrowableArray* _arr; + ciEnv* _curEnv; +public: + NonStaticFieldFiller(ciEnv* curEnv, GrowableArray* arr) : + _curEnv(curEnv), _arr(arr) + {} + void do_field(fieldDescriptor* fd) { + ciField* field = new (_curEnv->arena()) ciField(fd); + _arr->append(field); + } +}; + +GrowableArray* ciInstanceKlass::non_static_fields() { + if (_non_static_fields == NULL) { + VM_ENTRY_MARK; + ciEnv* curEnv = ciEnv::current(); + instanceKlass* ik = get_instanceKlass(); + int max_n_fields = ik->fields()->length()/instanceKlass::next_offset; + + _non_static_fields = + new (curEnv->arena()) GrowableArray(max_n_fields); + NonStaticFieldFiller filler(curEnv, _non_static_fields); + ik->do_nonstatic_fields(&filler); + } + return _non_static_fields; +} + static int sort_field_by_offset(ciField** a, ciField** b) { return (*a)->offset_in_bytes() - (*b)->offset_in_bytes(); // (no worries about 32-bit overflow...) diff --git a/hotspot/src/share/vm/ci/ciInstanceKlass.hpp b/hotspot/src/share/vm/ci/ciInstanceKlass.hpp index 3a084ab410b..d52818feca7 100644 --- a/hotspot/src/share/vm/ci/ciInstanceKlass.hpp +++ b/hotspot/src/share/vm/ci/ciInstanceKlass.hpp @@ -46,6 +46,7 @@ private: bool _has_subklass; ciFlags _flags; jint _nonstatic_field_size; + jint _nonstatic_oop_map_size; // Lazy fields get filled in only upon request. ciInstanceKlass* _super; @@ -58,6 +59,8 @@ private: ciInstanceKlass* _implementors[implementors_limit]; jint _nof_implementors; + GrowableArray* _non_static_fields; + protected: ciInstanceKlass(KlassHandle h_k); ciInstanceKlass(ciSymbol* name, jobject loader, jobject protection_domain); @@ -129,6 +132,9 @@ public: jint nonstatic_field_size() { assert(is_loaded(), "must be loaded"); return _nonstatic_field_size; } + jint nonstatic_oop_map_size() { + assert(is_loaded(), "must be loaded"); + return _nonstatic_oop_map_size; } ciInstanceKlass* super(); jint nof_implementors() { assert(is_loaded(), "must be loaded"); @@ -138,6 +144,9 @@ public: ciInstanceKlass* get_canonical_holder(int offset); ciField* get_field_by_offset(int field_offset, bool is_static); + + GrowableArray* non_static_fields(); + // total number of nonstatic fields (including inherited): int nof_nonstatic_fields() { if (_nonstatic_fields == NULL) diff --git a/hotspot/src/share/vm/code/debugInfo.cpp b/hotspot/src/share/vm/code/debugInfo.cpp index 2a2e1a56369..a84cee16fab 100644 --- a/hotspot/src/share/vm/code/debugInfo.cpp +++ b/hotspot/src/share/vm/code/debugInfo.cpp @@ -47,7 +47,8 @@ ScopeValue* DebugInfoReadStream::read_object_value() { } #endif ObjectValue* result = new ObjectValue(id); - _obj_pool->append(result); + // Cache the object since an object field could reference it. + _obj_pool->push(result); result->read_object(this); return result; } @@ -56,9 +57,9 @@ ScopeValue* DebugInfoReadStream::get_cached_object() { int id = read_int(); assert(_obj_pool != NULL, "object pool does not exist"); for (int i = _obj_pool->length() - 1; i >= 0; i--) { - ObjectValue* sv = (ObjectValue*) _obj_pool->at(i); - if (sv->id() == id) { - return sv; + ObjectValue* ov = (ObjectValue*) _obj_pool->at(i); + if (ov->id() == id) { + return ov; } } ShouldNotReachHere(); diff --git a/hotspot/src/share/vm/code/scopeDesc.cpp b/hotspot/src/share/vm/code/scopeDesc.cpp index 23a7e7d8d1a..96942b2ec59 100644 --- a/hotspot/src/share/vm/code/scopeDesc.cpp +++ b/hotspot/src/share/vm/code/scopeDesc.cpp @@ -91,7 +91,9 @@ GrowableArray* ScopeDesc::decode_object_values(int decode_offset) { DebugInfoReadStream* stream = new DebugInfoReadStream(_code, decode_offset, result); int length = stream->read_int(); for (int index = 0; index < length; index++) { - result->push(ScopeValue::read_from(stream)); + // Objects values are pushed to 'result' array during read so that + // object's fields could reference it (OBJECT_ID_CODE). + (void)ScopeValue::read_from(stream); } assert(result->length() == length, "inconsistent debug information"); return result; diff --git a/hotspot/src/share/vm/oops/instanceKlass.cpp b/hotspot/src/share/vm/oops/instanceKlass.cpp index a1105d49486..beeb60641c6 100644 --- a/hotspot/src/share/vm/oops/instanceKlass.cpp +++ b/hotspot/src/share/vm/oops/instanceKlass.cpp @@ -791,17 +791,39 @@ void instanceKlass::do_local_static_fields_impl(instanceKlassHandle this_oop, vo } +static int compare_fields_by_offset(int* a, int* b) { + return a[0] - b[0]; +} + void instanceKlass::do_nonstatic_fields(FieldClosure* cl) { - fieldDescriptor fd; instanceKlass* super = superklass(); if (super != NULL) { super->do_nonstatic_fields(cl); } + fieldDescriptor fd; int length = fields()->length(); + // In DebugInfo nonstatic fields are sorted by offset. + int* fields_sorted = NEW_C_HEAP_ARRAY(int, 2*(length+1)); + int j = 0; for (int i = 0; i < length; i += next_offset) { fd.initialize(as_klassOop(), i); - if (!(fd.is_static())) cl->do_field(&fd); + if (!fd.is_static()) { + fields_sorted[j + 0] = fd.offset(); + fields_sorted[j + 1] = i; + j += 2; + } } + if (j > 0) { + length = j; + // _sort_Fn is defined in growableArray.hpp. + qsort(fields_sorted, length/2, 2*sizeof(int), (_sort_Fn)compare_fields_by_offset); + for (int i = 0; i < length; i += 2) { + fd.initialize(as_klassOop(), fields_sorted[i + 1]); + assert(!fd.is_static() && fd.offset() == fields_sorted[i], "only nonstatic fields"); + cl->do_field(&fd); + } + } + FREE_C_HEAP_ARRAY(int, fields_sorted); } diff --git a/hotspot/src/share/vm/runtime/deoptimization.cpp b/hotspot/src/share/vm/runtime/deoptimization.cpp index a4c3a181a1f..444925938be 100644 --- a/hotspot/src/share/vm/runtime/deoptimization.cpp +++ b/hotspot/src/share/vm/runtime/deoptimization.cpp @@ -141,41 +141,45 @@ Deoptimization::UnrollBlock* Deoptimization::fetch_unroll_info_helper(JavaThread #ifdef COMPILER2 // Reallocate the non-escaping objects and restore their fields. Then // relock objects if synchronization on them was eliminated. - if (DoEscapeAnalysis && EliminateAllocations) { - GrowableArray* objects = chunk->at(0)->scope()->objects(); - bool reallocated = false; - if (objects != NULL) { - JRT_BLOCK - reallocated = realloc_objects(thread, &deoptee, objects, THREAD); - JRT_END - } - if (reallocated) { - reassign_fields(&deoptee, &map, objects); -#ifndef PRODUCT - if (TraceDeoptimization) { - ttyLocker ttyl; - tty->print_cr("REALLOC OBJECTS in thread " INTPTR_FORMAT, thread); - print_objects(objects); + if (DoEscapeAnalysis) { + if (EliminateAllocations) { + GrowableArray* objects = chunk->at(0)->scope()->objects(); + bool reallocated = false; + if (objects != NULL) { + JRT_BLOCK + reallocated = realloc_objects(thread, &deoptee, objects, THREAD); + JRT_END } -#endif - } - for (int i = 0; i < chunk->length(); i++) { - GrowableArray* monitors = chunk->at(i)->scope()->monitors(); - if (monitors != NULL) { - relock_objects(&deoptee, &map, monitors); + if (reallocated) { + reassign_fields(&deoptee, &map, objects); #ifndef PRODUCT if (TraceDeoptimization) { ttyLocker ttyl; - tty->print_cr("RELOCK OBJECTS in thread " INTPTR_FORMAT, thread); - for (int j = 0; i < monitors->length(); i++) { - MonitorValue* mv = monitors->at(i); - if (mv->eliminated()) { - StackValue* owner = StackValue::create_stack_value(&deoptee, &map, mv->owner()); - tty->print_cr(" object <" INTPTR_FORMAT "> locked", owner->get_obj()()); + tty->print_cr("REALLOC OBJECTS in thread " INTPTR_FORMAT, thread); + print_objects(objects); + } +#endif + } + } + if (EliminateLocks) { + for (int i = 0; i < chunk->length(); i++) { + GrowableArray* monitors = chunk->at(i)->scope()->monitors(); + if (monitors != NULL) { + relock_objects(&deoptee, &map, monitors); +#ifndef PRODUCT + if (TraceDeoptimization) { + ttyLocker ttyl; + tty->print_cr("RELOCK OBJECTS in thread " INTPTR_FORMAT, thread); + for (int j = 0; j < monitors->length(); j++) { + MonitorValue* mv = monitors->at(j); + if (mv->eliminated()) { + StackValue* owner = StackValue::create_stack_value(&deoptee, &map, mv->owner()); + tty->print_cr(" object <" INTPTR_FORMAT "> locked", owner->get_obj()()); + } } } - } #endif + } } } } @@ -656,6 +660,7 @@ public: void do_field(fieldDescriptor* fd) { + intptr_t val; StackValue* value = StackValue::create_stack_value(_fr, _reg_map, _sv->field_at(i())); int offset = fd->offset(); @@ -669,24 +674,36 @@ public: assert(value->type() == T_INT, "Agreement."); StackValue* low = StackValue::create_stack_value(_fr, _reg_map, _sv->field_at(++_i)); +#ifdef _LP64 + jlong res = (jlong)low->get_int(); +#else +#ifdef SPARC + // For SPARC we have to swap high and low words. + jlong res = jlong_from((jint)low->get_int(), (jint)value->get_int()); +#else jlong res = jlong_from((jint)value->get_int(), (jint)low->get_int()); +#endif //SPARC +#endif _obj->long_field_put(offset, res); break; } - + // Have to cast to INT (32 bits) pointer to avoid little/big-endian problem. case T_INT: case T_FLOAT: // 4 bytes. assert(value->type() == T_INT, "Agreement."); - _obj->int_field_put(offset, (jint)value->get_int()); + val = value->get_int(); + _obj->int_field_put(offset, (jint)*((jint*)&val)); break; case T_SHORT: case T_CHAR: // 2 bytes assert(value->type() == T_INT, "Agreement."); - _obj->short_field_put(offset, (jshort)value->get_int()); + val = value->get_int(); + _obj->short_field_put(offset, (jshort)*((jint*)&val)); break; - case T_BOOLEAN: // 1 byte + case T_BOOLEAN: case T_BYTE: // 1 byte assert(value->type() == T_INT, "Agreement."); - _obj->bool_field_put(offset, (jboolean)value->get_int()); + val = value->get_int(); + _obj->bool_field_put(offset, (jboolean)*((jint*)&val)); break; default: @@ -698,25 +715,49 @@ public: // restore elements of an eliminated type array void Deoptimization::reassign_type_array_elements(frame* fr, RegisterMap* reg_map, ObjectValue* sv, typeArrayOop obj, BasicType type) { - StackValue* low; - jlong lval; int index = 0; + intptr_t val; for (int i = 0; i < sv->field_size(); i++) { StackValue* value = StackValue::create_stack_value(fr, reg_map, sv->field_at(i)); switch(type) { - case T_BOOLEAN: obj->bool_at_put (index, (jboolean) value->get_int()); break; - case T_BYTE: obj->byte_at_put (index, (jbyte) value->get_int()); break; - case T_CHAR: obj->char_at_put (index, (jchar) value->get_int()); break; - case T_SHORT: obj->short_at_put(index, (jshort) value->get_int()); break; - case T_INT: obj->int_at_put (index, (jint) value->get_int()); break; - case T_FLOAT: obj->float_at_put(index, (jfloat) value->get_int()); break; - case T_LONG: - case T_DOUBLE: - low = StackValue::create_stack_value(fr, reg_map, sv->field_at(++i)); - lval = jlong_from((jint)value->get_int(), (jint)low->get_int()); - sv->value()->long_field_put(index, lval); - break; + case T_LONG: case T_DOUBLE: { + assert(value->type() == T_INT, "Agreement."); + StackValue* low = + StackValue::create_stack_value(fr, reg_map, sv->field_at(++i)); +#ifdef _LP64 + jlong res = (jlong)low->get_int(); +#else +#ifdef SPARC + // For SPARC we have to swap high and low words. + jlong res = jlong_from((jint)low->get_int(), (jint)value->get_int()); +#else + jlong res = jlong_from((jint)value->get_int(), (jint)low->get_int()); +#endif //SPARC +#endif + obj->long_at_put(index, res); + break; + } + + // Have to cast to INT (32 bits) pointer to avoid little/big-endian problem. + case T_INT: case T_FLOAT: // 4 bytes. + assert(value->type() == T_INT, "Agreement."); + val = value->get_int(); + obj->int_at_put(index, (jint)*((jint*)&val)); + break; + + case T_SHORT: case T_CHAR: // 2 bytes + assert(value->type() == T_INT, "Agreement."); + val = value->get_int(); + obj->short_at_put(index, (jshort)*((jint*)&val)); + break; + + case T_BOOLEAN: case T_BYTE: // 1 byte + assert(value->type() == T_INT, "Agreement."); + val = value->get_int(); + obj->bool_at_put(index, (jboolean)*((jint*)&val)); + break; + default: ShouldNotReachHere(); } From 3bf59e9c0a92fceaef110efb9e5d29a113394e76 Mon Sep 17 00:00:00 2001 From: Jon Masamitsu Date: Tue, 11 Mar 2008 14:19:53 -0700 Subject: [PATCH 045/258] 6673975: Disable ZapUnusedHeapArea to reduce GC execution times of debug JVM's Mangling the unused space is having an adverse affect on testing with fastdebug builds so turn it off by default. Reviewed-by: ysr, tonyp --- hotspot/src/share/vm/runtime/globals.hpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/hotspot/src/share/vm/runtime/globals.hpp b/hotspot/src/share/vm/runtime/globals.hpp index 80f9541bc39..67cb3285da5 100644 --- a/hotspot/src/share/vm/runtime/globals.hpp +++ b/hotspot/src/share/vm/runtime/globals.hpp @@ -586,7 +586,7 @@ class CommandLineFlags { develop(bool, ZapJNIHandleArea, trueInDebug, \ "Zap freed JNI handle space with 0xFEFEFEFE") \ \ - develop(bool, ZapUnusedHeapArea, trueInDebug, \ + develop(bool, ZapUnusedHeapArea, false, \ "Zap unused heap space with 0xBAADBABE") \ \ develop(bool, PrintVMMessages, true, \ From b64d5e42097faa1a162c5532571e5caa41cc961d Mon Sep 17 00:00:00 2001 From: Vladimir Kozlov Date: Tue, 11 Mar 2008 19:00:38 -0700 Subject: [PATCH 046/258] 6667615: (Escape Analysis) extend MDO to cache arguments escape state Use MDO to cache arguments escape state determined by the byte code escape analyzer. Reviewed-by: never --- hotspot/src/share/vm/ci/bcEscapeAnalyzer.cpp | 124 ++++++++++++++++--- hotspot/src/share/vm/ci/bcEscapeAnalyzer.hpp | 11 ++ hotspot/src/share/vm/ci/ciMethodData.cpp | 65 +++++++++- hotspot/src/share/vm/ci/ciMethodData.hpp | 18 ++- hotspot/src/share/vm/classfile/vmSymbols.cpp | 8 +- hotspot/src/share/vm/classfile/vmSymbols.hpp | 5 +- hotspot/src/share/vm/oops/methodDataOop.cpp | 57 ++++++++- hotspot/src/share/vm/oops/methodDataOop.hpp | 47 ++++++- 8 files changed, 306 insertions(+), 29 deletions(-) diff --git a/hotspot/src/share/vm/ci/bcEscapeAnalyzer.cpp b/hotspot/src/share/vm/ci/bcEscapeAnalyzer.cpp index 5a414028b28..8b9d0d7f31e 100644 --- a/hotspot/src/share/vm/ci/bcEscapeAnalyzer.cpp +++ b/hotspot/src/share/vm/ci/bcEscapeAnalyzer.cpp @@ -104,7 +104,7 @@ public: }; void BCEscapeAnalyzer::set_returned(ArgumentMap vars) { - for (int i = 0; i <= _arg_size; i++) { + for (int i = 0; i < _arg_size; i++) { if (vars.contains(i)) _arg_returned.set_bit(i); } @@ -112,10 +112,9 @@ void BCEscapeAnalyzer::set_returned(ArgumentMap vars) { _return_allocated = _return_allocated && vars.contains_allocated() && !(vars.contains_unknown() || vars.contains_vars()); } - // return true if any element of vars is an argument bool BCEscapeAnalyzer::is_argument(ArgumentMap vars) { - for (int i = 0; i <= _arg_size; i++) { + for (int i = 0; i < _arg_size; i++) { if (vars.contains(i)) return true; } @@ -126,7 +125,7 @@ bool BCEscapeAnalyzer::is_argument(ArgumentMap vars) { bool BCEscapeAnalyzer::is_arg_stack(ArgumentMap vars){ if (_conservative) return true; - for (int i = 0; i <= _arg_size; i++) { + for (int i = 0; i < _arg_size; i++) { if (vars.contains(i) && _arg_stack.at(i)) return true; } @@ -134,12 +133,13 @@ bool BCEscapeAnalyzer::is_arg_stack(ArgumentMap vars){ } void BCEscapeAnalyzer::clear_bits(ArgumentMap vars, BitMap &bm) { - for (int i = 0; i <= _arg_size; i++) { + for (int i = 0; i < _arg_size; i++) { if (vars.contains(i)) { bm.clear_bit(i); } } } + void BCEscapeAnalyzer::set_method_escape(ArgumentMap vars) { clear_bits(vars, _arg_local); } @@ -155,6 +155,17 @@ void BCEscapeAnalyzer::set_dirty(ArgumentMap vars) { clear_bits(vars, _dirty); } +void BCEscapeAnalyzer::set_modified(ArgumentMap vars, int offs, int size) { + + for (int i = 0; i < _arg_size; i++) { + if (vars.contains(i)) { + set_arg_modified(i, offs, size); + } + } + if (vars.contains_unknown()) + _unknown_modified = true; +} + bool BCEscapeAnalyzer::is_recursive_call(ciMethod* callee) { for (BCEscapeAnalyzer* scope = this; scope != NULL; scope = scope->_parent) { if (scope->method() == callee) { @@ -164,6 +175,40 @@ bool BCEscapeAnalyzer::is_recursive_call(ciMethod* callee) { return false; } +bool BCEscapeAnalyzer::is_arg_modified(int arg, int offset, int size_in_bytes) { + if (offset == OFFSET_ANY) + return _arg_modified[arg] != 0; + assert(arg >= 0 && arg < _arg_size, "must be an argument."); + bool modified = false; + int l = offset / HeapWordSize; + int h = round_to(offset + size_in_bytes, HeapWordSize) / HeapWordSize; + if (l > ARG_OFFSET_MAX) + l = ARG_OFFSET_MAX; + if (h > ARG_OFFSET_MAX+1) + h = ARG_OFFSET_MAX + 1; + for (int i = l; i < h; i++) { + modified = modified || (_arg_modified[arg] & (1 << i)) != 0; + } + return modified; +} + +void BCEscapeAnalyzer::set_arg_modified(int arg, int offset, int size_in_bytes) { + if (offset == OFFSET_ANY) { + _arg_modified[arg] = (uint) -1; + return; + } + assert(arg >= 0 && arg < _arg_size, "must be an argument."); + int l = offset / HeapWordSize; + int h = round_to(offset + size_in_bytes, HeapWordSize) / HeapWordSize; + if (l > ARG_OFFSET_MAX) + l = ARG_OFFSET_MAX; + if (h > ARG_OFFSET_MAX+1) + h = ARG_OFFSET_MAX + 1; + for (int i = l; i < h; i++) { + _arg_modified[arg] |= (1 << i); + } +} + void BCEscapeAnalyzer::invoke(StateInfo &state, Bytecodes::Code code, ciMethod* target, ciKlass* holder) { int i; @@ -197,6 +242,7 @@ void BCEscapeAnalyzer::invoke(StateInfo &state, Bytecodes::Code code, ciMethod* for (i = 0; i < arg_size; i++) { set_method_escape(state.raw_pop()); } + _unknown_modified = true; // assume the worst since we don't analyze the called method return; } @@ -224,6 +270,11 @@ void BCEscapeAnalyzer::invoke(StateInfo &state, Bytecodes::Code code, ciMethod* ArgumentMap arg = state.raw_pop(); if (!is_argument(arg)) continue; + for (int j = 0; j < _arg_size; j++) { + if (arg.contains(j)) { + _arg_modified[j] |= analyzer._arg_modified[i]; + } + } if (!is_arg_stack(arg)) { // arguments have already been recognized as escaping } else if (analyzer.is_arg_stack(i) && !analyzer.is_arg_returned(i)) { @@ -233,6 +284,7 @@ void BCEscapeAnalyzer::invoke(StateInfo &state, Bytecodes::Code code, ciMethod* set_global_escape(arg); } } + _unknown_modified = _unknown_modified || analyzer.has_non_arg_side_affects(); // record dependencies if at least one parameter retained stack-allocatable if (must_record_dependencies) { @@ -250,8 +302,10 @@ void BCEscapeAnalyzer::invoke(StateInfo &state, Bytecodes::Code code, ciMethod* ArgumentMap arg = state.raw_pop(); if (!is_argument(arg)) continue; + set_modified(arg, OFFSET_ANY, type2size[T_INT]*HeapWordSize); set_global_escape(arg); } + _unknown_modified = true; // assume the worst since we don't know the called method } } @@ -421,6 +475,7 @@ void BCEscapeAnalyzer::iterate_one_block(ciBlock *blk, StateInfo &state, Growabl state.spop(); ArgumentMap arr = state.apop(); set_method_escape(arr); + set_modified(arr, OFFSET_ANY, type2size[T_INT]*HeapWordSize); break; } case Bytecodes::_lastore: @@ -430,6 +485,7 @@ void BCEscapeAnalyzer::iterate_one_block(ciBlock *blk, StateInfo &state, Growabl state.spop(); ArgumentMap arr = state.apop(); set_method_escape(arr); + set_modified(arr, OFFSET_ANY, type2size[T_LONG]*HeapWordSize); break; } case Bytecodes::_aastore: @@ -437,6 +493,7 @@ void BCEscapeAnalyzer::iterate_one_block(ciBlock *blk, StateInfo &state, Growabl set_global_escape(state.apop()); state.spop(); ArgumentMap arr = state.apop(); + set_modified(arr, OFFSET_ANY, type2size[T_OBJECT]*HeapWordSize); break; } case Bytecodes::_pop: @@ -762,6 +819,7 @@ void BCEscapeAnalyzer::iterate_one_block(ciBlock *blk, StateInfo &state, Growabl if (s.cur_bc() != Bytecodes::_putstatic) { ArgumentMap p = state.apop(); set_method_escape(p); + set_modified(p, will_link ? field->offset() : OFFSET_ANY, type2size[field_type]*HeapWordSize); } } break; @@ -872,7 +930,7 @@ void BCEscapeAnalyzer::iterate_one_block(ciBlock *blk, StateInfo &state, Growabl } void BCEscapeAnalyzer::merge_block_states(StateInfo *blockstates, ciBlock *dest, StateInfo *s_state) { - StateInfo *d_state = blockstates+dest->index(); + StateInfo *d_state = blockstates + dest->index(); int nlocals = _method->max_locals(); // exceptions may cause transfer of control to handlers in the middle of a @@ -916,6 +974,7 @@ void BCEscapeAnalyzer::merge_block_states(StateInfo *blockstates, ciBlock *dest, } for (int i = 0; i < s_state->_stack_height; i++) { ArgumentMap t; + //extra_vars |= !d_state->_vars[i] & s_state->_vars[i]; t.clear(); t = s_state->_stack[i]; t.set_difference(d_state->_stack[i]); @@ -933,7 +992,7 @@ void BCEscapeAnalyzer::iterate_blocks(Arena *arena) { int datacount = (numblocks + 1) * (stkSize + numLocals); int datasize = datacount * sizeof(ArgumentMap); - StateInfo *blockstates = (StateInfo *) arena->Amalloc(_methodBlocks->num_blocks() * sizeof(StateInfo)); + StateInfo *blockstates = (StateInfo *) arena->Amalloc(numblocks * sizeof(StateInfo)); ArgumentMap *statedata = (ArgumentMap *) arena->Amalloc(datasize); for (int i = 0; i < datacount; i++) ::new ((void*)&statedata[i]) ArgumentMap(); ArgumentMap *dp = statedata; @@ -961,33 +1020,35 @@ void BCEscapeAnalyzer::iterate_blocks(Arena *arena) { ArgumentMap allVars; // all oop arguments to method ciSignature* sig = method()->signature(); int j = 0; + ciBlock* first_blk = _methodBlocks->block_containing(0); + int fb_i = first_blk->index(); if (!method()->is_static()) { // record information for "this" - blockstates[0]._vars[j].set(j); + blockstates[fb_i]._vars[j].set(j); allVars.add(j); j++; } for (int i = 0; i < sig->count(); i++) { ciType* t = sig->type_at(i); if (!t->is_primitive_type()) { - blockstates[0]._vars[j].set(j); + blockstates[fb_i]._vars[j].set(j); allVars.add(j); } j += t->size(); } - blockstates[0]._initialized = true; + blockstates[fb_i]._initialized = true; assert(j == _arg_size, "just checking"); ArgumentMap unknown_map; unknown_map.add_unknown(); - worklist.push(_methodBlocks->block_containing(0)); + worklist.push(first_blk); while(worklist.length() > 0) { ciBlock *blk = worklist.pop(); - StateInfo *blkState = blockstates+blk->index(); + StateInfo *blkState = blockstates + blk->index(); if (blk->is_handler() || blk->is_ret_target()) { // for an exception handler or a target of a ret instruction, we assume the worst case, - // that any variable or stack slot could contain any argument + // that any variable could contain any argument for (int i = 0; i < numLocals; i++) { state._vars[i] = allVars; } @@ -997,6 +1058,7 @@ void BCEscapeAnalyzer::iterate_blocks(Arena *arena) { state._stack_height = blkState->_stack_height; } for (int i = 0; i < state._stack_height; i++) { +// ??? should this be unknown_map ??? state._stack[i] = allVars; } } else { @@ -1053,6 +1115,7 @@ vmIntrinsics::ID BCEscapeAnalyzer::known_intrinsic() { vmIntrinsics::ID iid = method()->intrinsic_id(); if (iid == vmIntrinsics::_getClass || + iid == vmIntrinsics::_fillInStackTrace || iid == vmIntrinsics::_hashCode) return iid; else @@ -1060,12 +1123,16 @@ vmIntrinsics::ID BCEscapeAnalyzer::known_intrinsic() { } bool BCEscapeAnalyzer::compute_escape_for_intrinsic(vmIntrinsics::ID iid) { - ArgumentMap empty; - empty.clear(); + ArgumentMap arg; + arg.clear(); switch (iid) { case vmIntrinsics::_getClass: _return_local = false; break; + case vmIntrinsics::_fillInStackTrace: + arg.set(0); // 'this' + set_returned(arg); + break; case vmIntrinsics::_hashCode: // initialized state is correct break; @@ -1109,15 +1176,21 @@ void BCEscapeAnalyzer::initialize() { _return_allocated = true; } _allocated_escapes = false; + _unknown_modified = false; } void BCEscapeAnalyzer::clear_escape_info() { ciSignature* sig = method()->signature(); int arg_count = sig->count(); ArgumentMap var; + if (!method()->is_static()) { + arg_count++; // allow for "this" + } for (int i = 0; i < arg_count; i++) { + set_arg_modified(i, OFFSET_ANY, 4); var.clear(); var.set(i); + set_modified(var, OFFSET_ANY, 4); set_global_escape(var); } _arg_local.clear(); @@ -1126,6 +1199,7 @@ void BCEscapeAnalyzer::clear_escape_info() { _return_local = false; _return_allocated = false; _allocated_escapes = true; + _unknown_modified = true; } @@ -1205,8 +1279,17 @@ void BCEscapeAnalyzer::compute_escape_info() { } else { tty->print_cr(" non-local return values"); } + tty->print(" modified args: "); + for (int i = 0; i < _arg_size; i++) { + if (_arg_modified[i] == 0) + tty->print(" 0"); + else + tty->print(" 0x%x", _arg_modified[i]); + } tty->cr(); tty->print(" flags: "); + if (_unknown_modified) + tty->print(" unknown_modified"); if (_return_allocated) tty->print(" return_allocated"); tty->cr(); @@ -1228,6 +1311,7 @@ void BCEscapeAnalyzer::compute_escape_info() { if (_arg_returned.at(i)) { methodData()->set_arg_returned(i); } + methodData()->set_arg_modified(i, _arg_modified[i]); } if (_return_local) { methodData()->set_eflag(methodDataOopDesc::return_local); @@ -1244,6 +1328,7 @@ void BCEscapeAnalyzer::read_escape_info() { _arg_local.at_put(i, methodData()->is_arg_local(i)); _arg_stack.at_put(i, methodData()->is_arg_stack(i)); _arg_returned.at_put(i, methodData()->is_arg_returned(i)); + _arg_modified[i] = methodData()->arg_modified(i); } _return_local = methodData()->eflag_set(methodDataOopDesc::return_local); @@ -1261,6 +1346,12 @@ void BCEscapeAnalyzer::read_escape_info() { tty->print_cr(" non-local return values"); } tty->print(" modified args: "); + for (int i = 0; i < _arg_size; i++) { + if (_arg_modified[i] == 0) + tty->print(" 0"); + else + tty->print(" 0x%x", _arg_modified[i]); + } tty->cr(); } #endif @@ -1281,6 +1372,7 @@ BCEscapeAnalyzer::BCEscapeAnalyzer(ciMethod* method, BCEscapeAnalyzer* parent) , _return_local(false) , _return_allocated(false) , _allocated_escapes(false) + , _unknown_modified(false) , _dependencies() , _parent(parent) , _level(parent == NULL ? 0 : parent->level() + 1) { @@ -1290,6 +1382,8 @@ BCEscapeAnalyzer::BCEscapeAnalyzer(ciMethod* method, BCEscapeAnalyzer* parent) _arg_returned.clear(); _dirty.clear(); Arena* arena = CURRENT_ENV->arena(); + _arg_modified = (uint *) arena->Amalloc(_arg_size * sizeof(uint)); + Copy::zero_to_bytes(_arg_modified, _arg_size * sizeof(uint)); if (methodData() == NULL) return; diff --git a/hotspot/src/share/vm/ci/bcEscapeAnalyzer.hpp b/hotspot/src/share/vm/ci/bcEscapeAnalyzer.hpp index 4f9802bfa51..53fe46ad88a 100644 --- a/hotspot/src/share/vm/ci/bcEscapeAnalyzer.hpp +++ b/hotspot/src/share/vm/ci/bcEscapeAnalyzer.hpp @@ -46,9 +46,12 @@ class BCEscapeAnalyzer : public ResourceObj { BitMap _arg_stack; BitMap _arg_returned; BitMap _dirty; + enum{ ARG_OFFSET_MAX = 31}; + uint *_arg_modified; bool _return_local; bool _allocated_escapes; + bool _unknown_modified; bool _return_allocated; ciObjectList _dependencies; @@ -80,6 +83,7 @@ class BCEscapeAnalyzer : public ResourceObj { void set_method_escape(ArgumentMap vars); void set_global_escape(ArgumentMap vars); void set_dirty(ArgumentMap vars); + void set_modified(ArgumentMap vars, int offs, int size); bool is_recursive_call(ciMethod* callee); void add_dependence(ciKlass *klass, ciMethod *meth); @@ -140,6 +144,13 @@ class BCEscapeAnalyzer : public ResourceObj { return !_conservative && _return_allocated && !_allocated_escapes; } + // Tracking of argument modification + + enum {OFFSET_ANY = -1}; + bool is_arg_modified(int arg, int offset, int size_in_bytes); + void set_arg_modified(int arg, int offset, int size_in_bytes); + bool has_non_arg_side_affects() { return _unknown_modified; } + // Copy dependencies from this analysis into "deps" void copy_dependencies(Dependencies *deps); }; diff --git a/hotspot/src/share/vm/ci/ciMethodData.cpp b/hotspot/src/share/vm/ci/ciMethodData.cpp index b1ee47716a7..68591961bce 100644 --- a/hotspot/src/share/vm/ci/ciMethodData.cpp +++ b/hotspot/src/share/vm/ci/ciMethodData.cpp @@ -42,6 +42,8 @@ ciMethodData::ciMethodData(methodDataHandle h_md) : ciObject(h_md) { // Set an initial hint. Don't use set_hint_di() because // first_di() may be out of bounds if data_size is 0. _hint_di = first_di(); + // Initialize the escape information (to "don't know."); + _eflags = _arg_local = _arg_stack = _arg_returned = 0; } // ------------------------------------------------------------------ @@ -59,6 +61,8 @@ ciMethodData::ciMethodData() : ciObject() { // Set an initial hint. Don't use set_hint_di() because // first_di() may be out of bounds if data_size is 0. _hint_di = first_di(); + // Initialize the escape information (to "don't know."); + _eflags = _arg_local = _arg_stack = _arg_returned = 0; } void ciMethodData::load_data() { @@ -142,6 +146,8 @@ ciProfileData* ciMethodData::data_at(int data_index) { return new ciBranchData(data_layout); case DataLayout::multi_branch_data_tag: return new ciMultiBranchData(data_layout); + case DataLayout::arg_info_data_tag: + return new ciArgInfoData(data_layout); }; } @@ -172,6 +178,9 @@ ciProfileData* ciMethodData::bci_to_data(int bci) { _saw_free_extra_data = true; // observed an empty slot (common case) return NULL; } + if (dp->tag() == DataLayout::arg_info_data_tag) { + break; // ArgInfoData is at the end of extra data section. + } if (dp->bci() == bci) { assert(dp->tag() == DataLayout::bit_data_tag, "sane"); return new ciBitData(dp); @@ -217,8 +226,14 @@ int ciMethodData::trap_recompiled_at(ciProfileData* data) { void ciMethodData::clear_escape_info() { VM_ENTRY_MARK; methodDataOop mdo = get_methodDataOop(); - if (mdo != NULL) + if (mdo != NULL) { mdo->clear_escape_info(); + ArgInfoData *aid = arg_info(); + int arg_count = (aid == NULL) ? 0 : aid->number_of_args(); + for (int i = 0; i < arg_count; i++) { + set_arg_modified(i, 0); + } + } _eflags = _arg_local = _arg_stack = _arg_returned = 0; } @@ -231,6 +246,10 @@ void ciMethodData::update_escape_info() { mdo->set_arg_local(_arg_local); mdo->set_arg_stack(_arg_stack); mdo->set_arg_returned(_arg_returned); + int arg_count = mdo->method()->size_of_parameters(); + for (int i = 0; i < arg_count; i++) { + mdo->set_arg_modified(i, arg_modified(i)); + } } } @@ -262,6 +281,14 @@ void ciMethodData::set_arg_returned(int i) { set_nth_bit(_arg_returned, i); } +void ciMethodData::set_arg_modified(int arg, uint val) { + ArgInfoData *aid = arg_info(); + if (aid == NULL) + return; + assert(arg >= 0 && arg < aid->number_of_args(), "valid argument number"); + aid->set_arg_modified(arg, val); +} + bool ciMethodData::is_arg_local(int i) const { return is_set_nth_bit(_arg_local, i); } @@ -274,6 +301,14 @@ bool ciMethodData::is_arg_returned(int i) const { return is_set_nth_bit(_arg_returned, i); } +uint ciMethodData::arg_modified(int arg) const { + ArgInfoData *aid = arg_info(); + if (aid == NULL) + return 0; + assert(arg >= 0 && arg < aid->number_of_args(), "valid argument number"); + return aid->arg_modified(arg); +} + ByteSize ciMethodData::offset_of_slot(ciProfileData* data, ByteSize slot_offset_in_data) { // Get offset within methodDataOop of the data array ByteSize data_offset = methodDataOopDesc::data_offset(); @@ -287,6 +322,18 @@ ByteSize ciMethodData::offset_of_slot(ciProfileData* data, ByteSize slot_offset_ return in_ByteSize(offset); } +ciArgInfoData *ciMethodData::arg_info() const { + // Should be last, have to skip all traps. + DataLayout* dp = data_layout_at(data_size()); + DataLayout* end = data_layout_at(data_size() + extra_data_size()); + for (; dp < end; dp = methodDataOopDesc::next_extra(dp)) { + if (dp->tag() == DataLayout::arg_info_data_tag) + return new ciArgInfoData(dp); + } + return NULL; +} + + // Implementation of the print method. void ciMethodData::print_impl(outputStream* st) { ciObject::print_impl(st); @@ -305,6 +352,22 @@ void ciMethodData::print_data_on(outputStream* st) { st->fill_to(6); data->print_data_on(st); } + st->print_cr("--- Extra data:"); + DataLayout* dp = data_layout_at(data_size()); + DataLayout* end = data_layout_at(data_size() + extra_data_size()); + for (; dp < end; dp = methodDataOopDesc::next_extra(dp)) { + if (dp->tag() == DataLayout::no_tag) continue; + if (dp->tag() == DataLayout::bit_data_tag) { + data = new BitData(dp); + } else { + assert(dp->tag() == DataLayout::arg_info_data_tag, "must be BitData or ArgInfo"); + data = new ciArgInfoData(dp); + dp = end; // ArgInfoData is at the end of extra data section. + } + st->print("%d", dp_to_di(data->dp())); + st->fill_to(6); + data->print_data_on(st); + } } void ciReceiverTypeData::print_receiver_data_on(outputStream* st) { diff --git a/hotspot/src/share/vm/ci/ciMethodData.hpp b/hotspot/src/share/vm/ci/ciMethodData.hpp index 7e16d2f0974..91ed83f61eb 100644 --- a/hotspot/src/share/vm/ci/ciMethodData.hpp +++ b/hotspot/src/share/vm/ci/ciMethodData.hpp @@ -30,6 +30,7 @@ class ciRetData; class ciBranchData; class ciArrayData; class ciMultiBranchData; +class ciArgInfoData; typedef ProfileData ciProfileData; @@ -121,6 +122,11 @@ public: ciMultiBranchData(DataLayout* layout) : MultiBranchData(layout) {}; }; +class ciArgInfoData : public ArgInfoData { +public: + ciArgInfoData(DataLayout* layout) : ArgInfoData(layout) {}; +}; + // ciMethodData // // This class represents a methodDataOop in the HotSpot virtual @@ -163,9 +169,9 @@ private: ciMethodData(); // Accessors - int data_size() { return _data_size; } - int extra_data_size() { return _extra_data_size; } - intptr_t * data() { return _data; } + int data_size() const { return _data_size; } + int extra_data_size() const { return _extra_data_size; } + intptr_t * data() const { return _data; } methodDataOop get_methodDataOop() const { if (handle() == NULL) return NULL; @@ -178,7 +184,7 @@ private: void print_impl(outputStream* st); - DataLayout* data_layout_at(int data_index) { + DataLayout* data_layout_at(int data_index) const { assert(data_index % sizeof(intptr_t) == 0, "unaligned"); return (DataLayout*) (((address)_data) + data_index); } @@ -207,6 +213,8 @@ private: // What is the index of the first data entry? int first_di() { return 0; } + ciArgInfoData *arg_info() const; + public: bool is_method_data() { return true; } bool is_empty() { return _state == empty_state; } @@ -270,10 +278,12 @@ public: void set_arg_local(int i); void set_arg_stack(int i); void set_arg_returned(int i); + void set_arg_modified(int arg, uint val); bool is_arg_local(int i) const; bool is_arg_stack(int i) const; bool is_arg_returned(int i) const; + uint arg_modified(int arg) const; // Code generation helper ByteSize offset_of_slot(ciProfileData* data, ByteSize slot_offset_in_data); diff --git a/hotspot/src/share/vm/classfile/vmSymbols.cpp b/hotspot/src/share/vm/classfile/vmSymbols.cpp index 36ab6d9ddd0..36bab9ae5ac 100644 --- a/hotspot/src/share/vm/classfile/vmSymbols.cpp +++ b/hotspot/src/share/vm/classfile/vmSymbols.cpp @@ -318,6 +318,11 @@ inline bool match_F_SN(jshort flags) { const int neg = JVM_ACC_SYNCHRONIZED; return (flags & (req | neg)) == req; } +inline bool match_F_RNY(jshort flags) { + const int req = JVM_ACC_NATIVE | JVM_ACC_SYNCHRONIZED; + const int neg = JVM_ACC_STATIC; + return (flags & (req | neg)) == req; +} // These are for forming case labels: #define ID3(x, y, z) (( jint)(z) + \ @@ -359,6 +364,7 @@ const char* vmIntrinsics::short_name_as_C_string(vmIntrinsics::ID id, char* buf, case F_RN: fname = "native "; break; case F_SN: fname = "native static "; break; case F_S: fname = "static "; break; + case F_RNY:fname = "native synchronized "; break; } const char* kptr = strrchr(kname, '/'); if (kptr != NULL) kname = kptr + 1; @@ -485,7 +491,7 @@ void vmIntrinsics::verify_method(ID actual_id, methodOop m) { if (PrintMiscellaneous && (WizardMode || Verbose)) { tty->print_cr("*** misidentified method; %s(%d) should be %s(%d):", declared_name, declared_id, actual_name, actual_id); - m->print_short_name(tty); + mh()->print_short_name(tty); tty->cr(); } } diff --git a/hotspot/src/share/vm/classfile/vmSymbols.hpp b/hotspot/src/share/vm/classfile/vmSymbols.hpp index 75e7f1860d6..00a131f4e97 100644 --- a/hotspot/src/share/vm/classfile/vmSymbols.hpp +++ b/hotspot/src/share/vm/classfile/vmSymbols.hpp @@ -584,6 +584,8 @@ do_name( attemptUpdate_name, "attemptUpdate") \ do_signature(attemptUpdate_signature, "(JJ)Z") \ \ + do_intrinsic(_fillInStackTrace, java_lang_Throwable, fillInStackTrace_name, void_throwable_signature, F_RNY) \ + \ /* support for sun.misc.Unsafe */ \ do_class(sun_misc_Unsafe, "sun/misc/Unsafe") \ \ @@ -871,7 +873,8 @@ class vmIntrinsics: AllStatic { F_R, // !static !synchronized (R="regular") F_S, // static !synchronized F_RN, // !static native !synchronized - F_SN // static native !synchronized + F_SN, // static native !synchronized + F_RNY // !static native synchronized }; public: diff --git a/hotspot/src/share/vm/oops/methodDataOop.cpp b/hotspot/src/share/vm/oops/methodDataOop.cpp index f149335940a..77f10e0587d 100644 --- a/hotspot/src/share/vm/oops/methodDataOop.cpp +++ b/hotspot/src/share/vm/oops/methodDataOop.cpp @@ -32,7 +32,7 @@ // Some types of data layouts need a length field. bool DataLayout::needs_array_len(u1 tag) { - return (tag == multi_branch_data_tag); + return (tag == multi_branch_data_tag) || (tag == arg_info_data_tag); } // Perform generic initialization of the data. More specific @@ -404,6 +404,17 @@ void MultiBranchData::print_data_on(outputStream* st) { } #endif +#ifndef PRODUCT +void ArgInfoData::print_data_on(outputStream* st) { + print_shared(st, "ArgInfoData"); + int nargs = number_of_args(); + for (int i = 0; i < nargs; i++) { + st->print(" 0x%x", arg_modified(i)); + } + st->cr(); +} + +#endif // ================================================================== // methodDataOop // @@ -508,6 +519,9 @@ int methodDataOopDesc::compute_allocation_size_in_bytes(methodHandle method) { int extra_data_count = compute_extra_data_count(data_size, empty_bc_count); object_size += extra_data_count * DataLayout::compute_size_in_bytes(0); + // Add a cell to record information about modified arguments. + int arg_size = method->size_of_parameters(); + object_size += DataLayout::compute_size_in_bytes(arg_size+1); return object_size; } @@ -626,6 +640,8 @@ ProfileData* methodDataOopDesc::data_at(int data_index) { return new BranchData(data_layout); case DataLayout::multi_branch_data_tag: return new MultiBranchData(data_layout); + case DataLayout::arg_info_data_tag: + return new ArgInfoData(data_layout); }; } @@ -681,7 +697,17 @@ void methodDataOopDesc::initialize(methodHandle method) { // Add some extra DataLayout cells (at least one) to track stray traps. int extra_data_count = compute_extra_data_count(data_size, empty_bc_count); - object_size += extra_data_count * DataLayout::compute_size_in_bytes(0); + int extra_size = extra_data_count * DataLayout::compute_size_in_bytes(0); + + // Add a cell to record information about modified arguments. + // Set up _args_modified array after traps cells so that + // the code for traps cells works. + DataLayout *dp = data_layout_at(data_size + extra_size); + + int arg_size = method->size_of_parameters(); + dp->initialize(DataLayout::arg_info_data_tag, 0, arg_size+1); + + object_size += extra_size + DataLayout::compute_size_in_bytes(arg_size+1); // Set an initial hint. Don't use set_hint_di() because // first_di() may be out of bounds if data_size is 0. @@ -764,6 +790,10 @@ ProfileData* methodDataOopDesc::bci_to_extra_data(int bci, bool create_if_missin // No need for "OrderAccess::load_acquire" ops, // since the data structure is monotonic. if (dp->tag() == DataLayout::no_tag) break; + if (dp->tag() == DataLayout::arg_info_data_tag) { + dp = end; // ArgInfoData is at the end of extra data section. + break; + } if (dp->bci() == bci) { assert(dp->tag() == DataLayout::bit_data_tag, "sane"); return new BitData(dp); @@ -785,6 +815,16 @@ ProfileData* methodDataOopDesc::bci_to_extra_data(int bci, bool create_if_missin return NULL; } +ArgInfoData *methodDataOopDesc::arg_info() { + DataLayout* dp = extra_data_base(); + DataLayout* end = extra_data_limit(); + for (; dp < end; dp = next_extra(dp)) { + if (dp->tag() == DataLayout::arg_info_data_tag) + return new ArgInfoData(dp); + } + return NULL; +} + #ifndef PRODUCT void methodDataOopDesc::print_data_on(outputStream* st) { ResourceMark rm; @@ -794,15 +834,20 @@ void methodDataOopDesc::print_data_on(outputStream* st) { st->fill_to(6); data->print_data_on(st); } + st->print_cr("--- Extra data:"); DataLayout* dp = extra_data_base(); DataLayout* end = extra_data_limit(); for (; dp < end; dp = next_extra(dp)) { // No need for "OrderAccess::load_acquire" ops, // since the data structure is monotonic. - if (dp->tag() == DataLayout::no_tag) break; - if (dp == extra_data_base()) - st->print_cr("--- Extra data:"); - data = new BitData(dp); + if (dp->tag() == DataLayout::no_tag) continue; + if (dp->tag() == DataLayout::bit_data_tag) { + data = new BitData(dp); + } else { + assert(dp->tag() == DataLayout::arg_info_data_tag, "must be BitData or ArgInfo"); + data = new ArgInfoData(dp); + dp = end; // ArgInfoData is at the end of extra data section. + } st->print("%d", dp_to_di(data->dp())); st->fill_to(6); data->print_data_on(st); diff --git a/hotspot/src/share/vm/oops/methodDataOop.hpp b/hotspot/src/share/vm/oops/methodDataOop.hpp index 2896a1410aa..bcc1ac27eca 100644 --- a/hotspot/src/share/vm/oops/methodDataOop.hpp +++ b/hotspot/src/share/vm/oops/methodDataOop.hpp @@ -101,7 +101,8 @@ public: virtual_call_data_tag, ret_data_tag, branch_data_tag, - multi_branch_data_tag + multi_branch_data_tag, + arg_info_data_tag }; enum { @@ -245,6 +246,7 @@ class JumpData; class BranchData; class ArrayData; class MultiBranchData; +class ArgInfoData; // ProfileData @@ -376,6 +378,8 @@ public: virtual bool is_BranchData() { return false; } virtual bool is_ArrayData() { return false; } virtual bool is_MultiBranchData() { return false; } + virtual bool is_ArgInfoData() { return false; } + BitData* as_BitData() { assert(is_BitData(), "wrong type"); @@ -413,6 +417,10 @@ public: assert(is_MultiBranchData(), "wrong type"); return is_MultiBranchData() ? (MultiBranchData*)this : NULL; } + ArgInfoData* as_ArgInfoData() { + assert(is_ArgInfoData(), "wrong type"); + return is_ArgInfoData() ? (ArgInfoData*)this : NULL; + } // Subclass specific initialization @@ -1047,6 +1055,33 @@ public: #endif }; +class ArgInfoData : public ArrayData { + +public: + ArgInfoData(DataLayout* layout) : ArrayData(layout) { + assert(layout->tag() == DataLayout::arg_info_data_tag, "wrong type"); + } + + virtual bool is_ArgInfoData() { return true; } + + + int number_of_args() { + return array_len(); + } + + uint arg_modified(int arg) { + return array_uint_at(arg); + } + + void set_arg_modified(int arg, uint val) { + array_set_int_at(arg, val); + } + +#ifndef PRODUCT + void print_data_on(outputStream* st); +#endif +}; + // methodDataOop // // A methodDataOop holds information which has been collected about @@ -1183,6 +1218,9 @@ private: // Find or create an extra ProfileData: ProfileData* bci_to_extra_data(int bci, bool create_if_missing); + // return the argument info cell + ArgInfoData *arg_info(); + public: static int header_size() { return sizeof(methodDataOopDesc)/wordSize; @@ -1222,11 +1260,18 @@ public: intx arg_local() { return _arg_local; } intx arg_stack() { return _arg_stack; } intx arg_returned() { return _arg_returned; } + uint arg_modified(int a) { ArgInfoData *aid = arg_info(); + assert(a >= 0 && a < aid->number_of_args(), "valid argument number"); + return aid->arg_modified(a); } void set_eflags(intx v) { _eflags = v; } void set_arg_local(intx v) { _arg_local = v; } void set_arg_stack(intx v) { _arg_stack = v; } void set_arg_returned(intx v) { _arg_returned = v; } + void set_arg_modified(int a, uint v) { ArgInfoData *aid = arg_info(); + assert(a >= 0 && a < aid->number_of_args(), "valid argument number"); + + aid->set_arg_modified(a, v); } void clear_escape_info() { _eflags = _arg_local = _arg_stack = _arg_returned = 0; } From 0f1d30354af3246865a6c85a8f06ceebd02cf51e Mon Sep 17 00:00:00 2001 From: "Daniel D. Daugherty" Date: Wed, 12 Mar 2008 18:06:50 -0700 Subject: [PATCH 047/258] 6497639: 4/3 Profiling Swing application caused JVM crash Make RedefineClasses() interoperate better with class sharing. Reviewed-by: sspitsyn, jmasa --- hotspot/src/share/vm/classfile/dictionary.cpp | 4 +- .../share/vm/memory/compactingPermGenGen.cpp | 55 ++++++++++++++++--- hotspot/src/share/vm/oops/instanceKlass.cpp | 38 +++++++++---- hotspot/src/share/vm/oops/instanceKlass.hpp | 17 ++++-- 4 files changed, 87 insertions(+), 27 deletions(-) diff --git a/hotspot/src/share/vm/classfile/dictionary.cpp b/hotspot/src/share/vm/classfile/dictionary.cpp index 6c1d1ffce61..43d1ab9030d 100644 --- a/hotspot/src/share/vm/classfile/dictionary.cpp +++ b/hotspot/src/share/vm/classfile/dictionary.cpp @@ -155,8 +155,8 @@ bool Dictionary::do_unloading(BoolObjectClosure* is_alive) { for (int i = ik->previous_versions()->length() - 1; i >= 0; i--) { // check the previous versions array for GC'ed weak refs PreviousVersionNode * pv_node = ik->previous_versions()->at(i); - jweak cp_ref = pv_node->prev_constant_pool(); - assert(cp_ref != NULL, "weak cp ref was unexpectedly cleared"); + jobject cp_ref = pv_node->prev_constant_pool(); + assert(cp_ref != NULL, "cp ref was unexpectedly cleared"); if (cp_ref == NULL) { delete pv_node; ik->previous_versions()->remove_at(i); diff --git a/hotspot/src/share/vm/memory/compactingPermGenGen.cpp b/hotspot/src/share/vm/memory/compactingPermGenGen.cpp index 990f514a739..317908b188f 100644 --- a/hotspot/src/share/vm/memory/compactingPermGenGen.cpp +++ b/hotspot/src/share/vm/memory/compactingPermGenGen.cpp @@ -26,9 +26,27 @@ #include "incls/_compactingPermGenGen.cpp.incl" -// Recursively adjust all pointers in an object and all objects by -// referenced it. Clear marks on objects in order to prevent visiting -// any object twice. +// An ObjectClosure helper: Recursively adjust all pointers in an object +// and all objects by referenced it. Clear marks on objects in order to +// prevent visiting any object twice. This helper is used when the +// RedefineClasses() API has been called. + +class AdjustSharedObjectClosure : public ObjectClosure { +public: + void do_object(oop obj) { + if (obj->is_shared_readwrite()) { + if (obj->mark()->is_marked()) { + obj->init_mark(); // Don't revisit this object. + obj->adjust_pointers(); // Adjust this object's references. + } + } + } +}; + + +// An OopClosure helper: Recursively adjust all pointers in an object +// and all objects by referenced it. Clear marks on objects in order +// to prevent visiting any object twice. class RecursiveAdjustSharedObjectClosure : public OopClosure { public: @@ -274,15 +292,34 @@ CompactingPermGenGen::CompactingPermGenGen(ReservedSpace rs, // objects in the space will page in more objects than we need. // Instead, use the system dictionary as strong roots into the read // write space. +// +// If a RedefineClasses() call has been made, then we have to iterate +// over the entire shared read-write space in order to find all the +// objects that need to be forwarded. For example, it is possible for +// an nmethod to be found and marked in GC phase-1 only for the nmethod +// to be freed by the time we reach GC phase-3. The underlying method +// is still marked, but we can't (easily) find it in GC phase-3 so we +// blow up in GC phase-4. With RedefineClasses() we want replaced code +// (EMCP or obsolete) to go away (i.e., be collectible) once it is no +// longer being executed by any thread so we keep minimal attachments +// to the replaced code. However, we can't guarantee when those EMCP +// or obsolete methods will be collected so they may still be out there +// even after we've severed our minimal attachments. void CompactingPermGenGen::pre_adjust_pointers() { if (spec()->enable_shared_spaces()) { - RecursiveAdjustSharedObjectClosure blk; - Universe::oops_do(&blk); - StringTable::oops_do(&blk); - SystemDictionary::always_strong_classes_do(&blk); - TraversePlaceholdersClosure tpc; - SystemDictionary::placeholders_do(&tpc); + if (JvmtiExport::has_redefined_a_class()) { + // RedefineClasses() requires a brute force approach + AdjustSharedObjectClosure blk; + rw_space()->object_iterate(&blk); + } else { + RecursiveAdjustSharedObjectClosure blk; + Universe::oops_do(&blk); + StringTable::oops_do(&blk); + SystemDictionary::always_strong_classes_do(&blk); + TraversePlaceholdersClosure tpc; + SystemDictionary::placeholders_do(&tpc); + } } } diff --git a/hotspot/src/share/vm/oops/instanceKlass.cpp b/hotspot/src/share/vm/oops/instanceKlass.cpp index a1105d49486..ea85a6c630b 100644 --- a/hotspot/src/share/vm/oops/instanceKlass.cpp +++ b/hotspot/src/share/vm/oops/instanceKlass.cpp @@ -2165,12 +2165,20 @@ void instanceKlass::add_previous_version(instanceKlassHandle ikh, RC_TRACE(0x00000100, ("adding previous version ref for %s @%d, EMCP_cnt=%d", ikh->external_name(), _previous_versions->length(), emcp_method_count)); constantPoolHandle cp_h(ikh->constants()); - jweak cp_ref = JNIHandles::make_weak_global(cp_h); + jobject cp_ref; + if (cp_h->is_shared()) { + // a shared ConstantPool requires a regular reference; a weak + // reference would be collectible + cp_ref = JNIHandles::make_global(cp_h); + } else { + cp_ref = JNIHandles::make_weak_global(cp_h); + } PreviousVersionNode * pv_node = NULL; objArrayOop old_methods = ikh->methods(); if (emcp_method_count == 0) { - pv_node = new PreviousVersionNode(cp_ref, NULL); + // non-shared ConstantPool gets a weak reference + pv_node = new PreviousVersionNode(cp_ref, !cp_h->is_shared(), NULL); RC_TRACE(0x00000400, ("add: all methods are obsolete; flushing any EMCP weak refs")); } else { @@ -2190,7 +2198,8 @@ void instanceKlass::add_previous_version(instanceKlassHandle ikh, } } } - pv_node = new PreviousVersionNode(cp_ref, method_refs); + // non-shared ConstantPool gets a weak reference + pv_node = new PreviousVersionNode(cp_ref, !cp_h->is_shared(), method_refs); } _previous_versions->append(pv_node); @@ -2208,7 +2217,7 @@ void instanceKlass::add_previous_version(instanceKlassHandle ikh, // check the previous versions array for a GC'ed weak refs pv_node = _previous_versions->at(i); cp_ref = pv_node->prev_constant_pool(); - assert(cp_ref != NULL, "weak cp ref was unexpectedly cleared"); + assert(cp_ref != NULL, "cp ref was unexpectedly cleared"); if (cp_ref == NULL) { delete pv_node; _previous_versions->remove_at(i); @@ -2281,7 +2290,7 @@ void instanceKlass::add_previous_version(instanceKlassHandle ikh, // check the previous versions array for a GC'ed weak refs pv_node = _previous_versions->at(j); cp_ref = pv_node->prev_constant_pool(); - assert(cp_ref != NULL, "weak cp ref was unexpectedly cleared"); + assert(cp_ref != NULL, "cp ref was unexpectedly cleared"); if (cp_ref == NULL) { delete pv_node; _previous_versions->remove_at(j); @@ -2379,8 +2388,8 @@ bool instanceKlass::has_previous_version() const { // been GC'ed PreviousVersionNode * pv_node = _previous_versions->at(i); - jweak cp_ref = pv_node->prev_constant_pool(); - assert(cp_ref != NULL, "weak reference was unexpectedly cleared"); + jobject cp_ref = pv_node->prev_constant_pool(); + assert(cp_ref != NULL, "cp reference was unexpectedly cleared"); if (cp_ref == NULL) { continue; // robustness } @@ -2440,10 +2449,11 @@ void instanceKlass::set_methods_annotations_of(int idnum, typeArrayOop anno, obj // Construct a PreviousVersionNode entry for the array hung off // the instanceKlass. -PreviousVersionNode::PreviousVersionNode(jweak prev_constant_pool, - GrowableArray* prev_EMCP_methods) { +PreviousVersionNode::PreviousVersionNode(jobject prev_constant_pool, + bool prev_cp_is_weak, GrowableArray* prev_EMCP_methods) { _prev_constant_pool = prev_constant_pool; + _prev_cp_is_weak = prev_cp_is_weak; _prev_EMCP_methods = prev_EMCP_methods; } @@ -2451,7 +2461,11 @@ PreviousVersionNode::PreviousVersionNode(jweak prev_constant_pool, // Destroy a PreviousVersionNode PreviousVersionNode::~PreviousVersionNode() { if (_prev_constant_pool != NULL) { - JNIHandles::destroy_weak_global(_prev_constant_pool); + if (_prev_cp_is_weak) { + JNIHandles::destroy_weak_global(_prev_constant_pool); + } else { + JNIHandles::destroy_global(_prev_constant_pool); + } } if (_prev_EMCP_methods != NULL) { @@ -2471,8 +2485,8 @@ PreviousVersionInfo::PreviousVersionInfo(PreviousVersionNode *pv_node) { _prev_constant_pool_handle = constantPoolHandle(); // NULL handle _prev_EMCP_method_handles = NULL; - jweak cp_ref = pv_node->prev_constant_pool(); - assert(cp_ref != NULL, "weak constant pool ref was unexpectedly cleared"); + jobject cp_ref = pv_node->prev_constant_pool(); + assert(cp_ref != NULL, "constant pool ref was unexpectedly cleared"); if (cp_ref == NULL) { return; // robustness } diff --git a/hotspot/src/share/vm/oops/instanceKlass.hpp b/hotspot/src/share/vm/oops/instanceKlass.hpp index 29a76dc2c3b..478e8ecc1ef 100644 --- a/hotspot/src/share/vm/oops/instanceKlass.hpp +++ b/hotspot/src/share/vm/oops/instanceKlass.hpp @@ -838,11 +838,20 @@ class BreakpointInfo; // A collection point for interesting information about the previous // version(s) of an instanceKlass. This class uses weak references to // the information so that the information may be collected as needed -// by the system. A GrowableArray of PreviousVersionNodes is attached +// by the system. If the information is shared, then a regular +// reference must be used because a weak reference would be seen as +// collectible. A GrowableArray of PreviousVersionNodes is attached // to the instanceKlass as needed. See PreviousVersionWalker below. class PreviousVersionNode : public CHeapObj { private: - jweak _prev_constant_pool; + // A shared ConstantPool is never collected so we'll always have + // a reference to it so we can update items in the cache. We'll + // have a weak reference to a non-shared ConstantPool until all + // of the methods (EMCP or obsolete) have been collected; the + // non-shared ConstantPool becomes collectible at that point. + jobject _prev_constant_pool; // regular or weak reference + bool _prev_cp_is_weak; // true if not a shared ConstantPool + // If the previous version of the instanceKlass doesn't have any // EMCP methods, then _prev_EMCP_methods will be NULL. If all the // EMCP methods have been collected, then _prev_EMCP_methods can @@ -850,10 +859,10 @@ class PreviousVersionNode : public CHeapObj { GrowableArray* _prev_EMCP_methods; public: - PreviousVersionNode(jweak prev_constant_pool, + PreviousVersionNode(jobject prev_constant_pool, bool prev_cp_is_weak, GrowableArray* prev_EMCP_methods); ~PreviousVersionNode(); - jweak prev_constant_pool() const { + jobject prev_constant_pool() const { return _prev_constant_pool; } GrowableArray* prev_EMCP_methods() const { From f813016add7decf52ce97716f103dc14f8ed8f6b Mon Sep 17 00:00:00 2001 From: "Daniel D. Daugherty" Date: Wed, 12 Mar 2008 18:07:46 -0700 Subject: [PATCH 048/258] 6599425: 4/3 OopMapCache::lookup() can cause later crash or assert() failure Add should_not_be_cached() to markOop and methodOop and query that status inOopMapCache::lookup() Reviewed-by: coleenp, sspitsyn, jmasa --- hotspot/src/share/vm/includeDB_core | 1 + .../src/share/vm/interpreter/oopMapCache.cpp | 26 ++++++++--------- hotspot/src/share/vm/oops/markOop.cpp | 29 +++++++++++++++++++ hotspot/src/share/vm/oops/markOop.hpp | 3 ++ hotspot/src/share/vm/oops/methodOop.cpp | 22 ++++++++++++++ hotspot/src/share/vm/oops/methodOop.hpp | 2 ++ .../vm/prims/jvmtiRedefineClassesTrace.hpp | 2 +- 7 files changed, 71 insertions(+), 14 deletions(-) diff --git a/hotspot/src/share/vm/includeDB_core b/hotspot/src/share/vm/includeDB_core index cbf8e561a73..a49e0e99ede 100644 --- a/hotspot/src/share/vm/includeDB_core +++ b/hotspot/src/share/vm/includeDB_core @@ -3068,6 +3068,7 @@ oopMap.hpp vmreg.hpp oopMapCache.cpp allocation.inline.hpp oopMapCache.cpp handles.inline.hpp +oopMapCache.cpp jvmtiRedefineClassesTrace.hpp oopMapCache.cpp oop.inline.hpp oopMapCache.cpp oopMapCache.hpp oopMapCache.cpp resourceArea.hpp diff --git a/hotspot/src/share/vm/interpreter/oopMapCache.cpp b/hotspot/src/share/vm/interpreter/oopMapCache.cpp index 6a777dd789a..32d731ddd1c 100644 --- a/hotspot/src/share/vm/interpreter/oopMapCache.cpp +++ b/hotspot/src/share/vm/interpreter/oopMapCache.cpp @@ -532,6 +532,10 @@ void OopMapCache::flush_obsolete_entries() { if (!_array[i].is_empty() && _array[i].method()->is_old()) { // Cache entry is occupied by an old redefined method and we don't want // to pin it down so flush the entry. + RC_TRACE(0x08000000, ("flush: %s(%s): cached entry @%d", + _array[i].method()->name()->as_C_string(), + _array[i].method()->signature()->as_C_string(), i)); + _array[i].flush(); } } @@ -577,6 +581,15 @@ void OopMapCache::lookup(methodHandle method, // Entry is not in hashtable. // Compute entry and return it + if (method->should_not_be_cached()) { + // It is either not safe or not a good idea to cache this methodOop + // at this time. We give the caller of lookup() a copy of the + // interesting info via parameter entry_for, but we don't add it to + // the cache. See the gory details in methodOop.cpp. + compute_one_oop_map(method, bci, entry_for); + return; + } + // First search for an empty slot for(i = 0; i < _probe_depth; i++) { entry = entry_at(probe + i); @@ -584,12 +597,6 @@ void OopMapCache::lookup(methodHandle method, entry->fill(method, bci); entry_for->resource_copy(entry); assert(!entry_for->is_empty(), "A non-empty oop map should be returned"); - if (method->is_old()) { - // The caller of lookup() will receive a copy of the interesting - // info via entry_for, but we don't keep an old redefined method in - // the cache to avoid pinning down the method. - entry->flush(); - } return; } } @@ -623,13 +630,6 @@ void OopMapCache::lookup(methodHandle method, } assert(!entry_for->is_empty(), "A non-empty oop map should be returned"); - if (method->is_old()) { - // The caller of lookup() will receive a copy of the interesting - // info via entry_for, but we don't keep an old redefined method in - // the cache to avoid pinning down the method. - entry->flush(); - } - return; } diff --git a/hotspot/src/share/vm/oops/markOop.cpp b/hotspot/src/share/vm/oops/markOop.cpp index 855b525f4f7..75a2d506b46 100644 --- a/hotspot/src/share/vm/oops/markOop.cpp +++ b/hotspot/src/share/vm/oops/markOop.cpp @@ -37,3 +37,32 @@ void markOopDesc::print_on(outputStream* st) const { st->print("age %d)", age()); } } + + +// Give advice about whether the oop that contains this markOop +// should be cached or not. +bool markOopDesc::should_not_be_cached() const { + // the cast is because decode_pointer() isn't marked const + if (is_marked() && ((markOopDesc *)this)->decode_pointer() != NULL) { + // If the oop containing this markOop is being forwarded, then + // we are in the middle of GC and we do not want the containing + // oop to be added to a cache. We have no way of knowing whether + // the cache has already been visited by the current GC phase so + // we don't know whether the forwarded oop will be properly + // processed in this phase. If the forwarded oop is not properly + // processed, then we'll see strange crashes or asserts during + // the next GC run because the markOop will contain an unexpected + // value. + // + // This situation has been seen when we are GC'ing a methodOop + // because we use the methodOop while we're GC'ing it. Scary + // stuff. Some of the uses the methodOop cause the methodOop to + // be added to the OopMapCache in the instanceKlass as a side + // effect. This check lets the cache maintainer know when a + // cache addition would not be safe. + return true; + } + + // caching the containing oop should be just fine + return false; +} diff --git a/hotspot/src/share/vm/oops/markOop.hpp b/hotspot/src/share/vm/oops/markOop.hpp index def7c1844d3..155fb163895 100644 --- a/hotspot/src/share/vm/oops/markOop.hpp +++ b/hotspot/src/share/vm/oops/markOop.hpp @@ -357,4 +357,7 @@ class markOopDesc: public oopDesc { // Recover address of oop from encoded form used in mark inline void* decode_pointer() { if (UseBiasedLocking && has_bias_pattern()) return NULL; return clear_lock_bits(); } + + // see the definition in markOop.cpp for the gory details + bool should_not_be_cached() const; }; diff --git a/hotspot/src/share/vm/oops/methodOop.cpp b/hotspot/src/share/vm/oops/methodOop.cpp index bd23bfa772e..dfe9dee8560 100644 --- a/hotspot/src/share/vm/oops/methodOop.cpp +++ b/hotspot/src/share/vm/oops/methodOop.cpp @@ -765,6 +765,28 @@ bool methodOopDesc::is_overridden_in(klassOop k) const { } +// give advice about whether this methodOop should be cached or not +bool methodOopDesc::should_not_be_cached() const { + if (is_old()) { + // This method has been redefined. It is either EMCP or obsolete + // and we don't want to cache it because that would pin the method + // down and prevent it from being collectible if and when it + // finishes executing. + return true; + } + + if (mark()->should_not_be_cached()) { + // It is either not safe or not a good idea to cache this + // method at this time because of the state of the embedded + // markOop. See markOop.cpp for the gory details. + return true; + } + + // caching this method should be just fine + return false; +} + + methodHandle methodOopDesc:: clone_with_new_data(methodHandle m, u_char* new_code, int new_code_length, u_char* new_compressed_linenumber_table, int new_compressed_linenumber_size, TRAPS) { // Code below does not work for native methods - they should never get rewritten anyway diff --git a/hotspot/src/share/vm/oops/methodOop.hpp b/hotspot/src/share/vm/oops/methodOop.hpp index ec3d6b5e5ad..0d936e251f1 100644 --- a/hotspot/src/share/vm/oops/methodOop.hpp +++ b/hotspot/src/share/vm/oops/methodOop.hpp @@ -524,6 +524,8 @@ class methodOopDesc : public oopDesc { void set_is_old() { _access_flags.set_is_old(); } bool is_obsolete() const { return access_flags().is_obsolete(); } void set_is_obsolete() { _access_flags.set_is_obsolete(); } + // see the definition in methodOop.cpp for the gory details + bool should_not_be_cached() const; // JVMTI Native method prefixing support: bool is_prefixed_native() const { return access_flags().is_prefixed_native(); } diff --git a/hotspot/src/share/vm/prims/jvmtiRedefineClassesTrace.hpp b/hotspot/src/share/vm/prims/jvmtiRedefineClassesTrace.hpp index b527a8daec1..ed0f472b3d4 100644 --- a/hotspot/src/share/vm/prims/jvmtiRedefineClassesTrace.hpp +++ b/hotspot/src/share/vm/prims/jvmtiRedefineClassesTrace.hpp @@ -64,7 +64,7 @@ // 0x01000000 | 16777216 - impl details: nmethod evolution info // 0x02000000 | 33554432 - impl details: annotation updates // 0x04000000 | 67108864 - impl details: StackMapTable updates -// 0x08000000 | 134217728 - unused +// 0x08000000 | 134217728 - impl details: OopMapCache updates // 0x10000000 | 268435456 - unused // 0x20000000 | 536870912 - unused // 0x40000000 | 1073741824 - unused From 454bce899397f8048e63d0519876a57293c140ad Mon Sep 17 00:00:00 2001 From: "Daniel D. Daugherty" Date: Wed, 12 Mar 2008 18:09:34 -0700 Subject: [PATCH 049/258] 6453355: 4/4 new No_Safepoint_Verifier uses fail during GC (for Serguei) Clean up use of No_Safepoint_Verifier in JVM TI Reviewed-by: dcubed --- hotspot/src/share/vm/oops/instanceKlass.cpp | 73 ++++++++++++--------- hotspot/src/share/vm/oops/instanceKlass.hpp | 2 + hotspot/src/share/vm/runtime/thread.cpp | 8 +-- 3 files changed, 47 insertions(+), 36 deletions(-) diff --git a/hotspot/src/share/vm/oops/instanceKlass.cpp b/hotspot/src/share/vm/oops/instanceKlass.cpp index ea85a6c630b..74b60274f03 100644 --- a/hotspot/src/share/vm/oops/instanceKlass.cpp +++ b/hotspot/src/share/vm/oops/instanceKlass.cpp @@ -950,7 +950,6 @@ jmethodID instanceKlass::jmethod_id_for_impl(instanceKlassHandle ik_h, methodHan // These allocations will have to be freed if they are unused. // Allocate a new array of methods. - jmethodID* to_dealloc_jmeths = NULL; jmethodID* new_jmeths = NULL; if (length <= idnum) { // A new array will be needed (unless some other thread beats us to it) @@ -961,7 +960,6 @@ jmethodID instanceKlass::jmethod_id_for_impl(instanceKlassHandle ik_h, methodHan } // Allocate a new method ID. - jmethodID to_dealloc_id = NULL; jmethodID new_id = NULL; if (method_h->is_old() && !method_h->is_obsolete()) { // The method passed in is old (but not obsolete), we need to use the current version @@ -975,40 +973,51 @@ jmethodID instanceKlass::jmethod_id_for_impl(instanceKlassHandle ik_h, methodHan new_id = JNIHandles::make_jmethod_id(method_h); } - { + if (Threads::number_of_threads() == 0 || SafepointSynchronize::is_at_safepoint()) { + // No need and unsafe to lock the JmethodIdCreation_lock at safepoint. + id = get_jmethod_id(ik_h, idnum, new_id, new_jmeths); + } else { MutexLocker ml(JmethodIdCreation_lock); - - // We must not go to a safepoint while holding this lock. - debug_only(No_Safepoint_Verifier nosafepoints;) - - // Retry lookup after we got the lock - jmeths = ik_h->methods_jmethod_ids_acquire(); - if (jmeths == NULL || (length = (size_t)jmeths[0]) <= idnum) { - if (jmeths != NULL) { - // We have grown the array: copy the existing entries, and delete the old array - for (size_t index = 0; index < length; index++) { - new_jmeths[index+1] = jmeths[index+1]; - } - to_dealloc_jmeths = jmeths; // using the new jmeths, deallocate the old one - } - ik_h->release_set_methods_jmethod_ids(jmeths = new_jmeths); - } else { - id = jmeths[idnum+1]; - to_dealloc_jmeths = new_jmeths; // using the old jmeths, deallocate the new one - } - if (id == NULL) { - id = new_id; - jmeths[idnum+1] = id; // install the new method ID - } else { - to_dealloc_id = new_id; // the new id wasn't used, mark it for deallocation - } + id = get_jmethod_id(ik_h, idnum, new_id, new_jmeths); } + } + return id; +} - // Free up unneeded or no longer needed resources - FreeHeap(to_dealloc_jmeths); - if (to_dealloc_id != NULL) { - JNIHandles::destroy_jmethod_id(to_dealloc_id); + +jmethodID instanceKlass::get_jmethod_id(instanceKlassHandle ik_h, size_t idnum, + jmethodID new_id, jmethodID* new_jmeths) { + // Retry lookup after we got the lock or ensured we are at safepoint + jmethodID* jmeths = ik_h->methods_jmethod_ids_acquire(); + jmethodID id = NULL; + jmethodID to_dealloc_id = NULL; + jmethodID* to_dealloc_jmeths = NULL; + size_t length; + + if (jmeths == NULL || (length = (size_t)jmeths[0]) <= idnum) { + if (jmeths != NULL) { + // We have grown the array: copy the existing entries, and delete the old array + for (size_t index = 0; index < length; index++) { + new_jmeths[index+1] = jmeths[index+1]; + } + to_dealloc_jmeths = jmeths; // using the new jmeths, deallocate the old one } + ik_h->release_set_methods_jmethod_ids(jmeths = new_jmeths); + } else { + id = jmeths[idnum+1]; + to_dealloc_jmeths = new_jmeths; // using the old jmeths, deallocate the new one + } + if (id == NULL) { + id = new_id; + jmeths[idnum+1] = id; // install the new method ID + } else { + to_dealloc_id = new_id; // the new id wasn't used, mark it for deallocation + } + + // Free up unneeded or no longer needed resources + FreeHeap(to_dealloc_jmeths); + if (to_dealloc_id != NULL) { + JNIHandles::destroy_jmethod_id(to_dealloc_id); } return id; } diff --git a/hotspot/src/share/vm/oops/instanceKlass.hpp b/hotspot/src/share/vm/oops/instanceKlass.hpp index 478e8ecc1ef..285291dcea4 100644 --- a/hotspot/src/share/vm/oops/instanceKlass.hpp +++ b/hotspot/src/share/vm/oops/instanceKlass.hpp @@ -432,6 +432,8 @@ class instanceKlass: public Klass { _enclosing_method_method_index = method_index; } // jmethodID support + static jmethodID get_jmethod_id(instanceKlassHandle ik_h, size_t idnum, + jmethodID new_id, jmethodID* new_jmeths); static jmethodID jmethod_id_for_impl(instanceKlassHandle ik_h, methodHandle method_h); jmethodID jmethod_id_or_null(methodOop method); diff --git a/hotspot/src/share/vm/runtime/thread.cpp b/hotspot/src/share/vm/runtime/thread.cpp index 607772a0242..3667e576d13 100644 --- a/hotspot/src/share/vm/runtime/thread.cpp +++ b/hotspot/src/share/vm/runtime/thread.cpp @@ -1317,10 +1317,6 @@ JavaThread::~JavaThread() { ThreadSafepointState::destroy(this); if (_thread_profiler != NULL) delete _thread_profiler; if (_thread_stat != NULL) delete _thread_stat; - - if (jvmti_thread_state() != NULL) { - JvmtiExport::cleanup_thread(this); - } } @@ -1571,6 +1567,10 @@ void JavaThread::exit(bool destroy_vm, ExitType exit_type) { tlab().make_parsable(true); // retire TLAB } + if (jvmti_thread_state() != NULL) { + JvmtiExport::cleanup_thread(this); + } + // Remove from list of active threads list, and notify VM thread if we are the last non-daemon thread Threads::remove(this); } From 29278156581c79aacd48a8a4ad09c82f87648b1f Mon Sep 17 00:00:00 2001 From: "Daniel D. Daugherty" Date: Wed, 12 Mar 2008 18:37:03 -0700 Subject: [PATCH 050/258] 6452081: 3/4 Allow for Linux builds with Sun Studio Linux compilers (for Serguei) Allow for Linux builds with Sun Studio Linux compilers Reviewed-by: sspitsyn, ohair --- hotspot/agent/src/os/linux/ps_core.c | 8 +- hotspot/agent/src/os/linux/ps_proc.c | 8 +- hotspot/build/linux/Makefile | 5 + hotspot/build/linux/makefiles/amd64.make | 4 +- hotspot/build/linux/makefiles/buildtree.make | 6 +- hotspot/build/linux/makefiles/sparcWorks.make | 93 +++++++++++++++++++ hotspot/build/linux/platform_amd64.suncc | 17 ++++ hotspot/build/linux/platform_i486.suncc | 17 ++++ hotspot/src/cpu/x86/vm/assembler_x86_64.cpp | 4 +- .../src/os/linux/vm/attachListener_linux.cpp | 2 +- .../linux_x86/vm/bytes_linux_x86.inline.hpp | 11 +++ .../src/os_cpu/linux_x86/vm/os_linux_x86.cpp | 17 ++++ .../globalDefinitions_sparcWorks.hpp | 60 ++++++++++-- 13 files changed, 233 insertions(+), 19 deletions(-) create mode 100644 hotspot/build/linux/makefiles/sparcWorks.make create mode 100644 hotspot/build/linux/platform_amd64.suncc create mode 100644 hotspot/build/linux/platform_i486.suncc diff --git a/hotspot/agent/src/os/linux/ps_core.c b/hotspot/agent/src/os/linux/ps_core.c index b8890f15fc9..0693ffce4bb 100644 --- a/hotspot/agent/src/os/linux/ps_core.c +++ b/hotspot/agent/src/os/linux/ps_core.c @@ -518,10 +518,10 @@ static bool core_get_lwp_regs(struct ps_prochandle* ph, lwpid_t lwp_id, } static ps_prochandle_ops core_ops = { - release: core_release, - p_pread: core_read_data, - p_pwrite: core_write_data, - get_lwp_regs: core_get_lwp_regs + .release= core_release, + .p_pread= core_read_data, + .p_pwrite= core_write_data, + .get_lwp_regs= core_get_lwp_regs }; // read regs and create thread from NT_PRSTATUS entries from core file diff --git a/hotspot/agent/src/os/linux/ps_proc.c b/hotspot/agent/src/os/linux/ps_proc.c index 81ea1fb7aa0..9b226eaf00b 100644 --- a/hotspot/agent/src/os/linux/ps_proc.c +++ b/hotspot/agent/src/os/linux/ps_proc.c @@ -291,10 +291,10 @@ static void process_cleanup(struct ps_prochandle* ph) { } static ps_prochandle_ops process_ops = { - release: process_cleanup, - p_pread: process_read_data, - p_pwrite: process_write_data, - get_lwp_regs: process_get_lwp_regs + .release= process_cleanup, + .p_pread= process_read_data, + .p_pwrite= process_write_data, + .get_lwp_regs= process_get_lwp_regs }; // attach to the process. One and only one exposed stuff diff --git a/hotspot/build/linux/Makefile b/hotspot/build/linux/Makefile index 4b595a50ffc..106344f0dbe 100644 --- a/hotspot/build/linux/Makefile +++ b/hotspot/build/linux/Makefile @@ -80,6 +80,11 @@ ifneq ("$(filter $(LP64_ARCH),$(BUILDARCH))","") MFLAGS += " LP64=1 " endif +# pass USE_SUNCC further, through MFLAGS +ifdef USE_SUNCC + MFLAGS += " USE_SUNCC=1 " +endif + # The following renders pathnames in generated Makefiles valid on # machines other than the machine containing the build tree. # diff --git a/hotspot/build/linux/makefiles/amd64.make b/hotspot/build/linux/makefiles/amd64.make index 6b961fab558..d69cce70b9a 100644 --- a/hotspot/build/linux/makefiles/amd64.make +++ b/hotspot/build/linux/makefiles/amd64.make @@ -35,6 +35,8 @@ CFLAGS += -DVM_LITTLE_ENDIAN CFLAGS += -D_LP64=1 # The serviceability agent relies on frame pointer (%rbp) to walk thread stack -CFLAGS += -fno-omit-frame-pointer +ifndef USE_SUNCC + CFLAGS += -fno-omit-frame-pointer +endif OPT_CFLAGS/compactingPermGenGen.o = -O1 diff --git a/hotspot/build/linux/makefiles/buildtree.make b/hotspot/build/linux/makefiles/buildtree.make index 7e5b92df37f..a71aa64f12e 100644 --- a/hotspot/build/linux/makefiles/buildtree.make +++ b/hotspot/build/linux/makefiles/buildtree.make @@ -63,7 +63,11 @@ QUIETLY$(MAKE_VERBOSE) = @ # For now, until the compiler is less wobbly: TESTFLAGS = -Xbatch -showversion -PLATFORM_FILE = $(GAMMADIR)/build/$(OS_FAMILY)/platform_$(BUILDARCH) +ifdef USE_SUNCC +PLATFORM_FILE = $(GAMMADIR)/build/$(OS_FAMILY)/platform_$(BUILDARCH).suncc +else +PLATFORM_FILE = $(GAMMADIR)/build/$(OS_FAMILY)/platform_$(BUILDARCH) +endif ifdef FORCE_TIERED ifeq ($(VARIANT),tiered) diff --git a/hotspot/build/linux/makefiles/sparcWorks.make b/hotspot/build/linux/makefiles/sparcWorks.make new file mode 100644 index 00000000000..53819743beb --- /dev/null +++ b/hotspot/build/linux/makefiles/sparcWorks.make @@ -0,0 +1,93 @@ +# +# Copyright 1999-2007 Sun Microsystems, Inc. All Rights Reserved. +# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. +# +# This code is free software; you can redistribute it and/or modify it +# under the terms of the GNU General Public License version 2 only, as +# published by the Free Software Foundation. +# +# This code is distributed in the hope that it will be useful, but WITHOUT +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +# version 2 for more details (a copy is included in the LICENSE file that +# accompanied this code). +# +# You should have received a copy of the GNU General Public License version +# 2 along with this work; if not, write to the Free Software Foundation, +# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. +# +# Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, +# CA 95054 USA or visit www.sun.com if you need additional information or +# have any questions. +# +# + +#------------------------------------------------------------------------ +# CC, CPP & AS + +CPP = CC +CC = cc +AS = $(CC) -c + +ARCHFLAG = $(ARCHFLAG/$(BUILDARCH)) +ARCHFLAG/i486 = -m32 +ARCHFLAG/amd64 = -m64 + +CFLAGS += $(ARCHFLAG) +AOUT_FLAGS += $(ARCHFLAG) +LFLAGS += $(ARCHFLAG) +ASFLAGS += $(ARCHFLAG) + +#------------------------------------------------------------------------ +# Compiler flags + +# position-independent code +PICFLAG = -KPIC + +CFLAGS += $(PICFLAG) +# no more exceptions +CFLAGS += -features=no%except +# Reduce code bloat by reverting back to 5.0 behavior for static initializers +CFLAGS += -features=no%split_init +# allow zero sized arrays +CFLAGS += -features=zla + +# Use C++ Interpreter +ifdef CC_INTERP + CFLAGS += -DCC_INTERP +endif + +# We don't need libCstd.so and librwtools7.so, only libCrun.so +CFLAGS += -library=Crun +LIBS += -lCrun + +CFLAGS += -mt +LFLAGS += -mt + +# Compiler warnings are treated as errors +#WARNINGS_ARE_ERRORS = -errwarn=%all +CFLAGS_WARN/DEFAULT = $(WARNINGS_ARE_ERRORS) +# Special cases +CFLAGS_WARN/BYFILE = $(CFLAGS_WARN/$@)$(CFLAGS_WARN/DEFAULT$(CFLAGS_WARN/$@)) + +# The flags to use for an Optimized build +OPT_CFLAGS+=-xO4 +OPT_CFLAGS/NOOPT=-xO0 + +#------------------------------------------------------------------------ +# Linker flags + +# Use $(MAPFLAG:FILENAME=real_file_name) to specify a map file. +MAPFLAG = -Wl,--version-script=FILENAME + +# Use $(SONAMEFLAG:SONAME=soname) to specify the intrinsic name of a shared obj +SONAMEFLAG = -h SONAME + +# Build shared library +SHARED_FLAG = -G + +#------------------------------------------------------------------------ +# Debug flags +DEBUG_CFLAGS += -g +FASTDEBUG_CFLAGS = -g0 + diff --git a/hotspot/build/linux/platform_amd64.suncc b/hotspot/build/linux/platform_amd64.suncc new file mode 100644 index 00000000000..4366549571d --- /dev/null +++ b/hotspot/build/linux/platform_amd64.suncc @@ -0,0 +1,17 @@ +os_family = linux + +arch = x86 + +arch_model = x86_64 + +os_arch = linux_x86 + +os_arch_model = linux_x86_64 + +lib_arch = amd64 + +compiler = sparcWorks + +gnu_dis_arch = amd64 + +sysdefs = -DLINUX -DSPARC_WORKS -D_GNU_SOURCE -DAMD64 diff --git a/hotspot/build/linux/platform_i486.suncc b/hotspot/build/linux/platform_i486.suncc new file mode 100644 index 00000000000..325a3febd96 --- /dev/null +++ b/hotspot/build/linux/platform_i486.suncc @@ -0,0 +1,17 @@ +os_family = linux + +arch = x86 + +arch_model = x86_32 + +os_arch = linux_x86 + +os_arch_model = linux_x86_32 + +lib_arch = i386 + +compiler = sparcWorks + +gnu_dis_arch = i386 + +sysdefs = -DLINUX -DSPARC_WORKS -D_GNU_SOURCE -DIA32 diff --git a/hotspot/src/cpu/x86/vm/assembler_x86_64.cpp b/hotspot/src/cpu/x86/vm/assembler_x86_64.cpp index 0c457270632..41e157eef15 100644 --- a/hotspot/src/cpu/x86/vm/assembler_x86_64.cpp +++ b/hotspot/src/cpu/x86/vm/assembler_x86_64.cpp @@ -1304,7 +1304,7 @@ void Assembler::movl(Address dst, Register src) { emit_operand(src, dst); } -void Assembler::mov64(Register dst, int64_t imm64) { +void Assembler::mov64(Register dst, intptr_t imm64) { InstructionMark im(this); int encode = prefixq_and_encode(dst->encoding()); emit_byte(0xB8 | encode); @@ -1331,7 +1331,7 @@ void Assembler::movq(Register dst, Address src) { emit_operand(dst, src); } -void Assembler::mov64(Address dst, int64_t imm32) { +void Assembler::mov64(Address dst, intptr_t imm32) { assert(is_simm32(imm32), "lost bits"); InstructionMark im(this); prefixq(dst); diff --git a/hotspot/src/os/linux/vm/attachListener_linux.cpp b/hotspot/src/os/linux/vm/attachListener_linux.cpp index f0ffe6c8d39..81ce1cc976b 100644 --- a/hotspot/src/os/linux/vm/attachListener_linux.cpp +++ b/hotspot/src/os/linux/vm/attachListener_linux.cpp @@ -232,7 +232,7 @@ LinuxAttachOperation* LinuxAttachListener::read_request(int s) { // where is the protocol version (1), is the command // name ("load", "datadump", ...), and is an argument int expected_str_count = 2 + AttachOperation::arg_count_max; - int max_len = (strlen(ver_str) + 1) + (AttachOperation::name_length_max + 1) + + const int max_len = (sizeof(ver_str) + 1) + (AttachOperation::name_length_max + 1) + AttachOperation::arg_count_max*(AttachOperation::arg_length_max + 1); char buf[max_len]; diff --git a/hotspot/src/os_cpu/linux_x86/vm/bytes_linux_x86.inline.hpp b/hotspot/src/os_cpu/linux_x86/vm/bytes_linux_x86.inline.hpp index 1368a4c9c66..f0e0d5c4775 100644 --- a/hotspot/src/os_cpu/linux_x86/vm/bytes_linux_x86.inline.hpp +++ b/hotspot/src/os_cpu/linux_x86/vm/bytes_linux_x86.inline.hpp @@ -60,7 +60,18 @@ inline u4 Bytes::swap_u4(u4 x) { #ifdef AMD64 inline u8 Bytes::swap_u8(u8 x) { +#ifdef SPARC_WORKS + // workaround for SunStudio12 CR6615391 + __asm__ __volatile__ ( + "bswapq %0" + :"=r" (x) // output : register 0 => x + :"0" (x) // input : x => register 0 + :"0" // clobbered register + ); + return x; +#else return bswap_64(x); +#endif } #else // Helper function for swap_u8 diff --git a/hotspot/src/os_cpu/linux_x86/vm/os_linux_x86.cpp b/hotspot/src/os_cpu/linux_x86/vm/os_linux_x86.cpp index 972ee017c40..fc445ee26ca 100644 --- a/hotspot/src/os_cpu/linux_x86/vm/os_linux_x86.cpp +++ b/hotspot/src/os_cpu/linux_x86/vm/os_linux_x86.cpp @@ -62,8 +62,14 @@ #endif // AMD64 address os::current_stack_pointer() { +#ifdef SPARC_WORKS + register void *esp; + __asm__("mov %%"SPELL_REG_SP", %0":"=r"(esp)); + return (address) ((char*)esp + sizeof(long)*2); +#else register void *esp __asm__ (SPELL_REG_SP); return (address) esp; +#endif } char* os::non_memory_address_word() { @@ -139,7 +145,12 @@ frame os::get_sender_for_C_frame(frame* fr) { } intptr_t* _get_previous_fp() { +#ifdef SPARC_WORKS + register intptr_t **ebp; + __asm__("mov %%"SPELL_REG_FP", %0":"=r"(ebp)); +#else register intptr_t **ebp __asm__ (SPELL_REG_FP); +#endif return (intptr_t*) *ebp; // we want what it points to. } @@ -575,7 +586,9 @@ bool os::Linux::supports_variable_stack_size() { return true; } #else size_t os::Linux::min_stack_allowed = (48 DEBUG_ONLY(+4))*K; +#ifdef __GNUC__ #define GET_GS() ({int gs; __asm__ volatile("movw %%gs, %w0":"=q"(gs)); gs&0xffff;}) +#endif // Test if pthread library can support variable thread stack size. LinuxThreads // in fixed stack mode allocates 2M fixed slot for each thread. LinuxThreads @@ -606,7 +619,11 @@ bool os::Linux::supports_variable_stack_size() { // return true and skip _thread_safety_check(), so we may not be able to // detect stack-heap collisions. But otherwise it's harmless. // +#ifdef __GNUC__ return (GET_GS() != 0); +#else + return false; +#endif } } #endif // AMD64 diff --git a/hotspot/src/share/vm/utilities/globalDefinitions_sparcWorks.hpp b/hotspot/src/share/vm/utilities/globalDefinitions_sparcWorks.hpp index 16ae1ce9b12..a5629b2f826 100644 --- a/hotspot/src/share/vm/utilities/globalDefinitions_sparcWorks.hpp +++ b/hotspot/src/share/vm/utilities/globalDefinitions_sparcWorks.hpp @@ -37,23 +37,45 @@ # include # include # include +#ifdef SOLARIS # include +#endif # include +#ifdef LINUX +#ifndef FP_PZERO + // Linux doesn't have positive/negative zero + #define FP_PZERO FP_ZERO +#endif +#ifndef fpclass + #define fpclass fpclassify +#endif +#endif # include # include # include # include +#ifdef SOLARIS # include +#endif # include # include +#ifdef SOLARIS # include # include # include # include # include +#endif # ifdef SOLARIS_MUTATOR_LIBTHREAD # include # endif +#ifdef LINUX +# include +# include +# include +# include +#endif + // 4810578: varargs unsafe on 32-bit integer/64-bit pointer architectures // When __cplusplus is defined, NULL is defined as 0 (32-bit constant) in @@ -68,6 +90,11 @@ // pointer when it extracts the argument, then we have a problem. // // Solution: For 64-bit architectures, redefine NULL as 64-bit constant 0. +// +// Note: this fix doesn't work well on Linux because NULL will be overwritten +// whenever a system header file is included. Linux handles NULL correctly +// through a special type '__null'. +#ifdef SOLARIS #ifdef _LP64 #undef NULL #define NULL 0L @@ -76,13 +103,25 @@ #define NULL 0 #endif #endif +#endif // NULL vs NULL_WORD: // On Linux NULL is defined as a special type '__null'. Assigning __null to // integer variable will cause gcc warning. Use NULL_WORD in places where a -// pointer is stored as integer value. -#define NULL_WORD NULL +// pointer is stored as integer value. On some platforms, sizeof(intptr_t) > +// sizeof(void*), so here we want something which is integer type, but has the +// same size as a pointer. +#ifdef LINUX + #ifdef _LP64 + #define NULL_WORD 0L + #else + #define NULL_WORD 0 + #endif +#else + #define NULL_WORD NULL +#endif +#ifndef LINUX // Compiler-specific primitive types typedef unsigned short uint16_t; #ifndef _UINT32_T @@ -100,6 +139,7 @@ typedef unsigned int uintptr_t; // If this gets an error, figure out a symbol XXX that implies the // prior definition of intptr_t, and add "&& !defined(XXX)" above. #endif +#endif // Additional Java basic types @@ -128,7 +168,7 @@ inline jdouble jdouble_cast(jlong x) { return *(jdouble*)&x; } const jlong min_jlong = CONST64(0x8000000000000000); const jlong max_jlong = CONST64(0x7fffffffffffffff); - +#ifdef SOLARIS //---------------------------------------------------------------------------------------------------- // ANSI C++ fixes // NOTE:In the ANSI committee's continuing attempt to make each version @@ -162,7 +202,7 @@ extern "C" { typedef int (*int_fnP_cond_tP_i_vP)(cond_t *cv, int scope, void *arg); typedef int (*int_fnP_cond_tP)(cond_t *cv); }; - +#endif //---------------------------------------------------------------------------------------------------- // Debugging @@ -173,7 +213,7 @@ extern "C" void breakpoint(); #define BREAKPOINT ::breakpoint() // checking for nanness - +#ifdef SOLARIS #ifdef SPARC inline int g_isnan(float f) { return isnanf(f); } #else @@ -182,6 +222,12 @@ inline int g_isnan(float f) { return isnand(f); } #endif inline int g_isnan(double f) { return isnand(f); } +#elif LINUX +inline int g_isnan(float f) { return isnanf(f); } +inline int g_isnan(double f) { return isnan(f); } +#else +#error "missing platform-specific definition here" +#endif // Checking for finiteness @@ -195,9 +241,11 @@ inline int wcslen(const jchar* x) { return wcslen((const wchar_t*)x); } // Misc +// NOTE: This one leads to an infinite recursion on Linux +#ifndef LINUX int local_vsnprintf(char* buf, size_t count, const char* fmt, va_list argptr); #define vsnprintf local_vsnprintf - +#endif // Portability macros #define PRAGMA_INTERFACE From 63a8cc420e57c2b76f2b9ddfa973a31ac4cd006a Mon Sep 17 00:00:00 2001 From: "Daniel D. Daugherty" Date: Wed, 12 Mar 2008 18:39:05 -0700 Subject: [PATCH 051/258] 6667089: 3/3 multiple redefinitions of a class break reflection Use instanceKlass::method_with_idnum() instead of slot() to work with RedefineClasses(). Reviewed-by: sspitsyn --- hotspot/src/share/vm/runtime/reflection.cpp | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/hotspot/src/share/vm/runtime/reflection.cpp b/hotspot/src/share/vm/runtime/reflection.cpp index 55cf925e6e2..b0e8a996822 100644 --- a/hotspot/src/share/vm/runtime/reflection.cpp +++ b/hotspot/src/share/vm/runtime/reflection.cpp @@ -1548,10 +1548,11 @@ oop Reflection::invoke_method(oop method_mirror, Handle receiver, objArrayHandle } instanceKlassHandle klass(THREAD, java_lang_Class::as_klassOop(mirror)); - if (!klass->methods()->is_within_bounds(slot)) { + methodOop m = klass->method_with_idnum(slot); + if (m == NULL) { THROW_MSG_0(vmSymbols::java_lang_InternalError(), "invoke"); } - methodHandle method(THREAD, methodOop(klass->methods()->obj_at(slot))); + methodHandle method(THREAD, m); return invoke(klass, method, receiver, override, ptypes, rtype, args, true, THREAD); } @@ -1564,10 +1565,11 @@ oop Reflection::invoke_constructor(oop constructor_mirror, objArrayHandle args, objArrayHandle ptypes(THREAD, objArrayOop(java_lang_reflect_Constructor::parameter_types(constructor_mirror))); instanceKlassHandle klass(THREAD, java_lang_Class::as_klassOop(mirror)); - if (!klass->methods()->is_within_bounds(slot)) { + methodOop m = klass->method_with_idnum(slot); + if (m == NULL) { THROW_MSG_0(vmSymbols::java_lang_InternalError(), "invoke"); } - methodHandle method(THREAD, methodOop(klass->methods()->obj_at(slot))); + methodHandle method(THREAD, m); assert(method->name() == vmSymbols::object_initializer_name(), "invalid constructor"); // Make sure klass gets initialize From 000ac830a034a03ab0b3bfe1e01fcc86296544b9 Mon Sep 17 00:00:00 2001 From: Vladimir Kozlov Date: Thu, 13 Mar 2008 16:06:34 -0700 Subject: [PATCH 052/258] 6671807: (Escape Analysis) Add new ideal node to represent the state of a scalarized object at a safepoint Values of non-static fields of a scalarized object should be saved in debug info to reallocate the object during deoptimization. Reviewed-by: never --- hotspot/src/share/vm/opto/callnode.cpp | 161 ++++++++++++++++++++++--- hotspot/src/share/vm/opto/callnode.hpp | 58 ++++++++- hotspot/src/share/vm/opto/classes.hpp | 1 + hotspot/src/share/vm/opto/compile.hpp | 16 ++- hotspot/src/share/vm/opto/graphKit.cpp | 8 ++ hotspot/src/share/vm/opto/macro.cpp | 17 ++- hotspot/src/share/vm/opto/matcher.cpp | 1 + hotspot/src/share/vm/opto/node.hpp | 3 + hotspot/src/share/vm/opto/output.cpp | 83 ++++++++++++- 9 files changed, 322 insertions(+), 26 deletions(-) diff --git a/hotspot/src/share/vm/opto/callnode.cpp b/hotspot/src/share/vm/opto/callnode.cpp index f32562de0e4..b0bcf4ee8da 100644 --- a/hotspot/src/share/vm/opto/callnode.cpp +++ b/hotspot/src/share/vm/opto/callnode.cpp @@ -230,6 +230,7 @@ JVMState::JVMState(ciMethod* method, JVMState* caller) { _locoff = TypeFunc::Parms; _stkoff = _locoff + _method->max_locals(); _monoff = _stkoff + _method->max_stack(); + _scloff = _monoff; _endoff = _monoff; _sp = 0; } @@ -242,6 +243,7 @@ JVMState::JVMState(int stack_size) { _locoff = TypeFunc::Parms; _stkoff = _locoff; _monoff = _stkoff + stack_size; + _scloff = _monoff; _endoff = _monoff; _sp = 0; } @@ -297,12 +299,22 @@ uint JVMState::debug_depth() const { return total; } +#ifndef PRODUCT + //------------------------------format_helper---------------------------------- // Given an allocation (a Chaitin object) and a Node decide if the Node carries // any defined value or not. If it does, print out the register or constant. -#ifndef PRODUCT -static void format_helper( PhaseRegAlloc *regalloc, outputStream* st, Node *n, const char *msg, uint i ) { +static void format_helper( PhaseRegAlloc *regalloc, outputStream* st, Node *n, const char *msg, uint i, GrowableArray *scobjs ) { if (n == NULL) { st->print(" NULL"); return; } + if (n->is_SafePointScalarObject()) { + // Scalar replacement. + SafePointScalarObjectNode* spobj = n->as_SafePointScalarObject(); + scobjs->append_if_missing(spobj); + int sco_n = scobjs->find(spobj); + assert(sco_n >= 0, ""); + st->print(" %s%d]=#ScObj" INT32_FORMAT, msg, i, sco_n); + return; + } if( OptoReg::is_valid(regalloc->get_reg_first(n))) { // Check for undefined char buf[50]; regalloc->dump_register(n,buf); @@ -342,10 +354,8 @@ static void format_helper( PhaseRegAlloc *regalloc, outputStream* st, Node *n, c } } } -#endif //------------------------------format----------------------------------------- -#ifndef PRODUCT void JVMState::format(PhaseRegAlloc *regalloc, const Node *n, outputStream* st) const { st->print(" #"); if( _method ) { @@ -356,24 +366,25 @@ void JVMState::format(PhaseRegAlloc *regalloc, const Node *n, outputStream* st) return; } if (n->is_MachSafePoint()) { + GrowableArray scobjs; MachSafePointNode *mcall = n->as_MachSafePoint(); uint i; // Print locals for( i = 0; i < (uint)loc_size(); i++ ) - format_helper( regalloc, st, mcall->local(this, i), "L[", i ); + format_helper( regalloc, st, mcall->local(this, i), "L[", i, &scobjs ); // Print stack for (i = 0; i < (uint)stk_size(); i++) { if ((uint)(_stkoff + i) >= mcall->len()) st->print(" oob "); else - format_helper( regalloc, st, mcall->stack(this, i), "STK[", i ); + format_helper( regalloc, st, mcall->stack(this, i), "STK[", i, &scobjs ); } for (i = 0; (int)i < nof_monitors(); i++) { Node *box = mcall->monitor_box(this, i); Node *obj = mcall->monitor_obj(this, i); if ( OptoReg::is_valid(regalloc->get_reg_first(box)) ) { while( !box->is_BoxLock() ) box = box->in(1); - format_helper( regalloc, st, box, "MON-BOX[", i ); + format_helper( regalloc, st, box, "MON-BOX[", i, &scobjs ); } else { OptoReg::Name box_reg = BoxLockNode::stack_slot(box); st->print(" MON-BOX%d=%s+%d", @@ -381,15 +392,71 @@ void JVMState::format(PhaseRegAlloc *regalloc, const Node *n, outputStream* st) OptoReg::regname(OptoReg::c_frame_pointer), regalloc->reg2offset(box_reg)); } - format_helper( regalloc, st, obj, "MON-OBJ[", i ); + format_helper( regalloc, st, obj, "MON-OBJ[", i, &scobjs ); + } + + for (i = 0; i < (uint)scobjs.length(); i++) { + // Scalar replaced objects. + st->print_cr(""); + st->print(" # ScObj" INT32_FORMAT " ", i); + SafePointScalarObjectNode* spobj = scobjs.at(i); + ciKlass* cik = spobj->bottom_type()->is_oopptr()->klass(); + assert(cik->is_instance_klass() || + cik->is_array_klass(), "Not supported allocation."); + ciInstanceKlass *iklass = NULL; + if (cik->is_instance_klass()) { + cik->print_name_on(st); + iklass = cik->as_instance_klass(); + } else if (cik->is_type_array_klass()) { + cik->as_array_klass()->base_element_type()->print_name_on(st); + st->print("[%d]=", spobj->n_fields()); + } else if (cik->is_obj_array_klass()) { + ciType* cie = cik->as_array_klass()->base_element_type(); + int ndim = 1; + while (cie->is_obj_array_klass()) { + ndim += 1; + cie = cie->as_array_klass()->base_element_type(); + } + cie->print_name_on(st); + while (ndim-- > 0) { + st->print("[]"); + } + st->print("[%d]=", spobj->n_fields()); + } + st->print("{"); + uint nf = spobj->n_fields(); + if (nf > 0) { + uint first_ind = spobj->first_index(); + Node* fld_node = mcall->in(first_ind); + ciField* cifield; + if (iklass != NULL) { + st->print(" ["); + cifield = iklass->nonstatic_field_at(0); + cifield->print_name_on(st); + format_helper( regalloc, st, fld_node, ":", 0, &scobjs ); + } else { + format_helper( regalloc, st, fld_node, "[", 0, &scobjs ); + } + for (uint j = 1; j < nf; j++) { + fld_node = mcall->in(first_ind+j); + if (iklass != NULL) { + st->print(", ["); + cifield = iklass->nonstatic_field_at(j); + cifield->print_name_on(st); + format_helper( regalloc, st, fld_node, ":", j, &scobjs ); + } else { + format_helper( regalloc, st, fld_node, ", [", j, &scobjs ); + } + } + } + st->print(" }"); } } st->print_cr(""); if (caller() != NULL) caller()->format(regalloc, n, st); } -#endif -#ifndef PRODUCT + void JVMState::dump_spec(outputStream *st) const { if (_method != NULL) { bool printed = false; @@ -419,9 +486,8 @@ void JVMState::dump_spec(outputStream *st) const { } if (caller() != NULL) caller()->dump_spec(st); } -#endif -#ifndef PRODUCT + void JVMState::dump_on(outputStream* st) const { if (_map && !((uintptr_t)_map & 1)) { if (_map->len() > _map->req()) { // _map->has_exceptions() @@ -434,8 +500,8 @@ void JVMState::dump_on(outputStream* st) const { } _map->dump(2); } - st->print("JVMS depth=%d loc=%d stk=%d mon=%d end=%d mondepth=%d sp=%d bci=%d method=", - depth(), locoff(), stkoff(), monoff(), endoff(), monitor_depth(), sp(), bci()); + st->print("JVMS depth=%d loc=%d stk=%d mon=%d scalar=%d end=%d mondepth=%d sp=%d bci=%d method=", + depth(), locoff(), stkoff(), monoff(), scloff(), endoff(), monitor_depth(), sp(), bci()); if (_method == NULL) { st->print_cr("(none)"); } else { @@ -465,6 +531,7 @@ JVMState* JVMState::clone_shallow(Compile* C) const { n->set_locoff(_locoff); n->set_stkoff(_stkoff); n->set_monoff(_monoff); + n->set_scloff(_scloff); n->set_endoff(_endoff); n->set_sp(_sp); n->set_map(_map); @@ -765,6 +832,7 @@ const RegMask &SafePointNode::out_RegMask() const { void SafePointNode::grow_stack(JVMState* jvms, uint grow_by) { assert((int)grow_by > 0, "sanity"); int monoff = jvms->monoff(); + int scloff = jvms->scloff(); int endoff = jvms->endoff(); assert(endoff == (int)req(), "no other states or debug info after me"); Node* top = Compile::current()->top(); @@ -772,6 +840,7 @@ void SafePointNode::grow_stack(JVMState* jvms, uint grow_by) { ins_req(monoff, top); } jvms->set_monoff(monoff + grow_by); + jvms->set_scloff(scloff + grow_by); jvms->set_endoff(endoff + grow_by); } @@ -781,6 +850,7 @@ void SafePointNode::push_monitor(const FastLockNode *lock) { const int MonitorEdges = 2; assert(JVMState::logMonitorEdges == exact_log2(MonitorEdges), "correct MonitorEdges"); assert(req() == jvms()->endoff(), "correct sizing"); + int nextmon = jvms()->scloff(); if (GenerateSynchronizationCode) { add_req(lock->box_node()); add_req(lock->obj_node()); @@ -788,6 +858,7 @@ void SafePointNode::push_monitor(const FastLockNode *lock) { add_req(NULL); add_req(NULL); } + jvms()->set_scloff(nextmon+MonitorEdges); jvms()->set_endoff(req()); } @@ -795,10 +866,13 @@ void SafePointNode::pop_monitor() { // Delete last monitor from debug info debug_only(int num_before_pop = jvms()->nof_monitors()); const int MonitorEdges = (1<scloff(); int endoff = jvms()->endoff(); + int new_scloff = scloff - MonitorEdges; int new_endoff = endoff - MonitorEdges; + jvms()->set_scloff(new_scloff); jvms()->set_endoff(new_endoff); - while (endoff > new_endoff) del_req(--endoff); + while (scloff > new_scloff) del_req(--scloff); assert(jvms()->nof_monitors() == num_before_pop-1, ""); } @@ -822,6 +896,63 @@ uint SafePointNode::match_edge(uint idx) const { return (TypeFunc::Parms == idx); } +//============== SafePointScalarObjectNode ============== + +SafePointScalarObjectNode::SafePointScalarObjectNode(const TypeOopPtr* tp, +#ifdef ASSERT + AllocateNode* alloc, +#endif + uint first_index, + uint n_fields) : + TypeNode(tp, 1), // 1 control input -- seems required. Get from root. +#ifdef ASSERT + _alloc(alloc), +#endif + _first_index(first_index), + _n_fields(n_fields) +{ + init_class_id(Class_SafePointScalarObject); +} + + +uint SafePointScalarObjectNode::ideal_reg() const { + return 0; // No matching to machine instruction +} + +const RegMask &SafePointScalarObjectNode::in_RegMask(uint idx) const { + return *(Compile::current()->matcher()->idealreg2debugmask[in(idx)->ideal_reg()]); +} + +const RegMask &SafePointScalarObjectNode::out_RegMask() const { + return RegMask::Empty; +} + +uint SafePointScalarObjectNode::match_edge(uint idx) const { + return 0; +} + +SafePointScalarObjectNode* +SafePointScalarObjectNode::clone(int jvms_adj, Dict* sosn_map) const { + void* cached = (*sosn_map)[(void*)this]; + if (cached != NULL) { + return (SafePointScalarObjectNode*)cached; + } + Compile* C = Compile::current(); + SafePointScalarObjectNode* res = (SafePointScalarObjectNode*)Node::clone(); + res->_first_index += jvms_adj; + sosn_map->Insert((void*)this, (void*)res); + return res; +} + + +#ifndef PRODUCT +void SafePointScalarObjectNode::dump_spec(outputStream *st) const { + st->print(" # fields@[%d..%d]", first_index(), + first_index() + n_fields() - 1); +} + +#endif + //============================================================================= uint AllocateNode::size_of() const { return sizeof(*this); } diff --git a/hotspot/src/share/vm/opto/callnode.hpp b/hotspot/src/share/vm/opto/callnode.hpp index d07a4d78d0e..179ad06b007 100644 --- a/hotspot/src/share/vm/opto/callnode.hpp +++ b/hotspot/src/share/vm/opto/callnode.hpp @@ -184,6 +184,7 @@ private: uint _locoff; // Offset to locals in input edge mapping uint _stkoff; // Offset to stack in input edge mapping uint _monoff; // Offset to monitors in input edge mapping + uint _scloff; // Offset to fields of scalar objs in input edge mapping uint _endoff; // Offset to end of input edge mapping uint _sp; // Jave Expression Stack Pointer for this state int _bci; // Byte Code Index of this JVM point @@ -207,16 +208,19 @@ public: uint stkoff() const { return _stkoff; } uint argoff() const { return _stkoff + _sp; } uint monoff() const { return _monoff; } + uint scloff() const { return _scloff; } uint endoff() const { return _endoff; } uint oopoff() const { return debug_end(); } int loc_size() const { return _stkoff - _locoff; } int stk_size() const { return _monoff - _stkoff; } - int mon_size() const { return _endoff - _monoff; } + int mon_size() const { return _scloff - _monoff; } + int scl_size() const { return _endoff - _scloff; } bool is_loc(uint i) const { return i >= _locoff && i < _stkoff; } bool is_stk(uint i) const { return i >= _stkoff && i < _monoff; } - bool is_mon(uint i) const { return i >= _monoff && i < _endoff; } + bool is_mon(uint i) const { return i >= _monoff && i < _scloff; } + bool is_scl(uint i) const { return i >= _scloff && i < _endoff; } uint sp() const { return _sp; } int bci() const { return _bci; } @@ -227,7 +231,9 @@ public: uint depth() const { return _depth; } uint debug_start() const; // returns locoff of root caller uint debug_end() const; // returns endoff of self - uint debug_size() const { return loc_size() + sp() + mon_size(); } + uint debug_size() const { + return loc_size() + sp() + mon_size() + scl_size(); + } uint debug_depth() const; // returns sum of debug_size values at all depths // Returns the JVM state at the desired depth (1 == root). @@ -254,8 +260,11 @@ public: void set_locoff(uint off) { _locoff = off; } void set_stkoff(uint off) { _stkoff = off; } void set_monoff(uint off) { _monoff = off; } + void set_scloff(uint off) { _scloff = off; } void set_endoff(uint off) { _endoff = off; } - void set_offsets(uint off) { _locoff = _stkoff = _monoff = _endoff = off; } + void set_offsets(uint off) { + _locoff = _stkoff = _monoff = _scloff = _endoff = off; + } void set_map(SafePointNode *map) { _map = map; } void set_sp(uint sp) { _sp = sp; } void set_bci(int bci) { _bci = bci; } @@ -399,6 +408,47 @@ public: #endif }; +//------------------------------SafePointScalarObjectNode---------------------- +// A SafePointScalarObjectNode represents the state of a scalarized object +// at a safepoint. + +class SafePointScalarObjectNode: public TypeNode { + uint _first_index; // First input edge index of a SafePoint node where + // states of the scalarized object fields are collected. + uint _n_fields; // Number of non-static fields of the scalarized object. + DEBUG_ONLY(AllocateNode* _alloc); +public: + SafePointScalarObjectNode(const TypeOopPtr* tp, +#ifdef ASSERT + AllocateNode* alloc, +#endif + uint first_index, uint n_fields); + virtual int Opcode() const; + virtual uint ideal_reg() const; + virtual const RegMask &in_RegMask(uint) const; + virtual const RegMask &out_RegMask() const; + virtual uint match_edge(uint idx) const; + + uint first_index() const { return _first_index; } + uint n_fields() const { return _n_fields; } + DEBUG_ONLY(AllocateNode* alloc() const { return _alloc; }) + + virtual uint size_of() const { return sizeof(*this); } + + // Assumes that "this" is an argument to a safepoint node "s", and that + // "new_call" is being created to correspond to "s". But the difference + // between the start index of the jvmstates of "new_call" and "s" is + // "jvms_adj". Produce and return a SafePointScalarObjectNode that + // corresponds appropriately to "this" in "new_call". Assumes that + // "sosn_map" is a map, specific to the translation of "s" to "new_call", + // mapping old SafePointScalarObjectNodes to new, to avoid multiple copies. + SafePointScalarObjectNode* clone(int jvms_adj, Dict* sosn_map) const; + +#ifndef PRODUCT + virtual void dump_spec(outputStream *st) const; +#endif +}; + //------------------------------CallNode--------------------------------------- // Call nodes now subsume the function of debug nodes at callsites, so they // contain the functionality of a full scope chain of debug nodes. diff --git a/hotspot/src/share/vm/opto/classes.hpp b/hotspot/src/share/vm/opto/classes.hpp index 26eff2b4eb9..0c5f53ba307 100644 --- a/hotspot/src/share/vm/opto/classes.hpp +++ b/hotspot/src/share/vm/opto/classes.hpp @@ -185,6 +185,7 @@ macro(Root) macro(RoundDouble) macro(RoundFloat) macro(SafePoint) +macro(SafePointScalarObject) macro(SCMemProj) macro(SinD) macro(SqrtD) diff --git a/hotspot/src/share/vm/opto/compile.hpp b/hotspot/src/share/vm/opto/compile.hpp index a4e4c1401f3..419bc68bebe 100644 --- a/hotspot/src/share/vm/opto/compile.hpp +++ b/hotspot/src/share/vm/opto/compile.hpp @@ -606,8 +606,20 @@ class Compile : public Phase { // Build OopMaps for each GC point void BuildOopMaps(); - // Append debug info for the node to the array - void FillLocArray( int idx, Node *local, GrowableArray *array ); + + // Append debug info for the node "local" at safepoint node "sfpt" to the + // "array", May also consult and add to "objs", which describes the + // scalar-replaced objects. + void FillLocArray( int idx, MachSafePointNode* sfpt, + Node *local, GrowableArray *array, + GrowableArray *objs ); + + // If "objs" contains an ObjectValue whose id is "id", returns it, else NULL. + static ObjectValue* sv_for_node_id(GrowableArray *objs, int id); + // Requres that "objs" does not contains an ObjectValue whose id matches + // that of "sv. Appends "sv". + static void set_sv_for_object_node(GrowableArray *objs, + ObjectValue* sv ); // Process an OopMap Element while emitting nodes void Process_OopMap_Node(MachNode *mach, int code_offset); diff --git a/hotspot/src/share/vm/opto/graphKit.cpp b/hotspot/src/share/vm/opto/graphKit.cpp index 45471f29fde..b7dc9e1ed73 100644 --- a/hotspot/src/share/vm/opto/graphKit.cpp +++ b/hotspot/src/share/vm/opto/graphKit.cpp @@ -857,6 +857,13 @@ void GraphKit::add_safepoint_edges(SafePointNode* call, bool must_throw) { for (j = 0; j < l; j++) call->set_req(p++, in_map->in(k+j)); + // Copy any scalar object fields. + k = in_jvms->scloff(); + l = in_jvms->scl_size(); + out_jvms->set_scloff(p); + for (j = 0; j < l; j++) + call->set_req(p++, in_map->in(k+j)); + // Finish the new jvms. out_jvms->set_endoff(p); @@ -864,6 +871,7 @@ void GraphKit::add_safepoint_edges(SafePointNode* call, bool must_throw) { assert(out_jvms->depth() == in_jvms->depth(), "depth must match"); assert(out_jvms->loc_size() == in_jvms->loc_size(), "size must match"); assert(out_jvms->mon_size() == in_jvms->mon_size(), "size must match"); + assert(out_jvms->scl_size() == in_jvms->scl_size(), "size must match"); assert(out_jvms->debug_size() == in_jvms->debug_size(), "size must match"); // Update the two tail pointers in parallel. diff --git a/hotspot/src/share/vm/opto/macro.cpp b/hotspot/src/share/vm/opto/macro.cpp index 9ba4bc3d4ff..4a8ffd1076f 100644 --- a/hotspot/src/share/vm/opto/macro.cpp +++ b/hotspot/src/share/vm/opto/macro.cpp @@ -54,15 +54,30 @@ void PhaseMacroExpand::copy_call_debug_info(CallNode *oldcall, CallNode * newcal uint new_dbg_start = newcall->tf()->domain()->cnt(); int jvms_adj = new_dbg_start - old_dbg_start; assert (new_dbg_start == newcall->req(), "argument count mismatch"); + + Dict* sosn_map = new Dict(cmpkey,hashkey); for (uint i = old_dbg_start; i < oldcall->req(); i++) { - newcall->add_req(oldcall->in(i)); + Node* old_in = oldcall->in(i); + // Clone old SafePointScalarObjectNodes, adjusting their field contents. + if (old_in->is_SafePointScalarObject()) { + SafePointScalarObjectNode* old_sosn = old_in->as_SafePointScalarObject(); + uint old_unique = C->unique(); + Node* new_in = old_sosn->clone(jvms_adj, sosn_map); + if (old_unique != C->unique()) { + new_in = transform_later(new_in); // Register new node. + } + old_in = new_in; + } + newcall->add_req(old_in); } + newcall->set_jvms(oldcall->jvms()); for (JVMState *jvms = newcall->jvms(); jvms != NULL; jvms = jvms->caller()) { jvms->set_map(newcall); jvms->set_locoff(jvms->locoff()+jvms_adj); jvms->set_stkoff(jvms->stkoff()+jvms_adj); jvms->set_monoff(jvms->monoff()+jvms_adj); + jvms->set_scloff(jvms->scloff()+jvms_adj); jvms->set_endoff(jvms->endoff()+jvms_adj); } } diff --git a/hotspot/src/share/vm/opto/matcher.cpp b/hotspot/src/share/vm/opto/matcher.cpp index a8d673a7f26..7d9cd51eff6 100644 --- a/hotspot/src/share/vm/opto/matcher.cpp +++ b/hotspot/src/share/vm/opto/matcher.cpp @@ -1647,6 +1647,7 @@ void Matcher::find_shared( Node *n ) { case Op_Phi: // Treat Phis as shared roots case Op_Parm: case Op_Proj: // All handled specially during matching + case Op_SafePointScalarObject: set_shared(n); set_dontcare(n); break; diff --git a/hotspot/src/share/vm/opto/node.hpp b/hotspot/src/share/vm/opto/node.hpp index 881de4d21b9..ac35f9b4f1b 100644 --- a/hotspot/src/share/vm/opto/node.hpp +++ b/hotspot/src/share/vm/opto/node.hpp @@ -106,6 +106,7 @@ class RegMask; class RegionNode; class RootNode; class SafePointNode; +class SafePointScalarObjectNode; class StartNode; class State; class StoreNode; @@ -575,6 +576,7 @@ public: DEFINE_CLASS_ID(ConstraintCast, Type, 1) DEFINE_CLASS_ID(CheckCastPP, Type, 2) DEFINE_CLASS_ID(CMove, Type, 3) + DEFINE_CLASS_ID(SafePointScalarObject, Type, 4) DEFINE_CLASS_ID(Mem, Node, 6) DEFINE_CLASS_ID(Load, Mem, 0) @@ -721,6 +723,7 @@ public: DEFINE_CLASS_QUERY(Region) DEFINE_CLASS_QUERY(Root) DEFINE_CLASS_QUERY(SafePoint) + DEFINE_CLASS_QUERY(SafePointScalarObject) DEFINE_CLASS_QUERY(Start) DEFINE_CLASS_QUERY(Store) DEFINE_CLASS_QUERY(Sub) diff --git a/hotspot/src/share/vm/opto/output.cpp b/hotspot/src/share/vm/opto/output.cpp index 690459e5f0b..3c06b135f9a 100644 --- a/hotspot/src/share/vm/opto/output.cpp +++ b/hotspot/src/share/vm/opto/output.cpp @@ -561,7 +561,30 @@ static LocationValue *new_loc_value( PhaseRegAlloc *ra, OptoReg::Name regnum, Lo : new LocationValue(Location::new_stk_loc(l_type, ra->reg2offset(regnum))); } -void Compile::FillLocArray( int idx, Node *local, GrowableArray *array ) { + +ObjectValue* +Compile::sv_for_node_id(GrowableArray *objs, int id) { + for (int i = 0; i < objs->length(); i++) { + assert(objs->at(i)->is_object(), "corrupt object cache"); + ObjectValue* sv = (ObjectValue*) objs->at(i); + if (sv->id() == id) { + return sv; + } + } + // Otherwise.. + return NULL; +} + +void Compile::set_sv_for_object_node(GrowableArray *objs, + ObjectValue* sv ) { + assert(sv_for_node_id(objs, sv->id()) == NULL, "Precondition"); + objs->append(sv); +} + + +void Compile::FillLocArray( int idx, MachSafePointNode* sfpt, Node *local, + GrowableArray *array, + GrowableArray *objs ) { assert( local, "use _top instead of null" ); if (array->length() != idx) { assert(array->length() == idx + 1, "Unexpected array count"); @@ -578,6 +601,29 @@ void Compile::FillLocArray( int idx, Node *local, GrowableArray *ar } const Type *t = local->bottom_type(); + // Is it a safepoint scalar object node? + if (local->is_SafePointScalarObject()) { + SafePointScalarObjectNode* spobj = local->as_SafePointScalarObject(); + + ObjectValue* sv = Compile::sv_for_node_id(objs, spobj->_idx); + if (sv == NULL) { + ciKlass* cik = t->is_oopptr()->klass(); + assert(cik->is_instance_klass() || + cik->is_array_klass(), "Not supported allocation."); + sv = new ObjectValue(spobj->_idx, + new ConstantOopWriteValue(cik->encoding())); + Compile::set_sv_for_object_node(objs, sv); + + uint first_ind = spobj->first_index(); + for (uint i = 0; i < spobj->n_fields(); i++) { + Node* fld_node = sfpt->in(first_ind+i); + (void)FillLocArray(sv->field_values()->length(), sfpt, fld_node, sv->field_values(), objs); + } + } + array->append(sv); + return; + } + // Grab the register number for the local OptoReg::Name regnum = _regalloc->get_reg_first(local); if( OptoReg::is_valid(regnum) ) {// Got a register/stack? @@ -755,6 +801,11 @@ void Compile::Process_OopMap_Node(MachNode *mach, int current_offset) { JVMState* youngest_jvms = sfn->jvms(); int max_depth = youngest_jvms->depth(); + // Allocate the object pool for scalar-replaced objects -- the map from + // small-integer keys (which can be recorded in the local and ostack + // arrays) to descriptions of the object state. + GrowableArray *objs = new GrowableArray(); + // Visit scopes from oldest to youngest. for (int depth = 1; depth <= max_depth; depth++) { JVMState* jvms = youngest_jvms->of_depth(depth); @@ -773,13 +824,13 @@ void Compile::Process_OopMap_Node(MachNode *mach, int current_offset) { // Insert locals into the locarray GrowableArray *locarray = new GrowableArray(num_locs); for( idx = 0; idx < num_locs; idx++ ) { - FillLocArray( idx, sfn->local(jvms, idx), locarray ); + FillLocArray( idx, sfn, sfn->local(jvms, idx), locarray, objs ); } // Insert expression stack entries into the exparray GrowableArray *exparray = new GrowableArray(num_exps); for( idx = 0; idx < num_exps; idx++ ) { - FillLocArray( idx, sfn->stack(jvms, idx), exparray ); + FillLocArray( idx, sfn, sfn->stack(jvms, idx), exparray, objs ); } // Add in mappings of the monitors @@ -803,7 +854,27 @@ void Compile::Process_OopMap_Node(MachNode *mach, int current_offset) { // Create ScopeValue for object ScopeValue *scval = NULL; - if( !obj_node->is_Con() ) { + + if( obj_node->is_SafePointScalarObject() ) { + SafePointScalarObjectNode* spobj = obj_node->as_SafePointScalarObject(); + scval = Compile::sv_for_node_id(objs, spobj->_idx); + if (scval == NULL) { + const Type *t = obj_node->bottom_type(); + ciKlass* cik = t->is_oopptr()->klass(); + assert(cik->is_instance_klass() || + cik->is_array_klass(), "Not supported allocation."); + ObjectValue* sv = new ObjectValue(spobj->_idx, + new ConstantOopWriteValue(cik->encoding())); + Compile::set_sv_for_object_node(objs, sv); + + uint first_ind = spobj->first_index(); + for (uint i = 0; i < spobj->n_fields(); i++) { + Node* fld_node = sfn->in(first_ind+i); + (void)FillLocArray(sv->field_values()->length(), sfn, fld_node, sv->field_values(), objs); + } + scval = sv; + } + } else if( !obj_node->is_Con() ) { OptoReg::Name obj_reg = _regalloc->get_reg_first(obj_node); scval = new_loc_value( _regalloc, obj_reg, Location::oop ); } else { @@ -814,6 +885,9 @@ void Compile::Process_OopMap_Node(MachNode *mach, int current_offset) { monarray->append(new MonitorValue(scval, Location::new_stk_loc(Location::normal,_regalloc->reg2offset(box_reg)))); } + // We dump the object pool first, since deoptimization reads it in first. + debug_info()->dump_object_pool(objs); + // Build first class objects to pass to scope DebugToken *locvals = debug_info()->create_scope_values(locarray); DebugToken *expvals = debug_info()->create_scope_values(exparray); @@ -823,6 +897,7 @@ void Compile::Process_OopMap_Node(MachNode *mach, int current_offset) { ciMethod* scope_method = method ? method : _method; // Describe the scope here assert(jvms->bci() >= InvocationEntryBci && jvms->bci() <= 0x10000, "must be a valid or entry BCI"); + // Now we can describe the scope. debug_info()->describe_scope(safepoint_pc_offset,scope_method,jvms->bci(),locvals,expvals,monvals); } // End jvms loop From 30dc0edfc877000c0ae20384f228b45ba82807b7 Mon Sep 17 00:00:00 2001 From: Vladimir Kozlov Date: Thu, 13 Mar 2008 16:31:32 -0700 Subject: [PATCH 053/258] 6673473: (Escape Analysis) Add the instance's field information to PhiNode Avoid an infinite generation of instance's field values Phi nodes. Reviewed-by: never --- hotspot/src/share/vm/opto/cfgnode.hpp | 35 +++++- hotspot/src/share/vm/opto/loopopts.cpp | 13 ++- hotspot/src/share/vm/opto/memnode.cpp | 150 +++++++++++++++++-------- hotspot/src/share/vm/opto/memnode.hpp | 3 + hotspot/src/share/vm/opto/type.cpp | 23 ++-- hotspot/src/share/vm/opto/type.hpp | 1 + 6 files changed, 166 insertions(+), 59 deletions(-) diff --git a/hotspot/src/share/vm/opto/cfgnode.hpp b/hotspot/src/share/vm/opto/cfgnode.hpp index b198a5bf7ab..79811ee6b4d 100644 --- a/hotspot/src/share/vm/opto/cfgnode.hpp +++ b/hotspot/src/share/vm/opto/cfgnode.hpp @@ -110,14 +110,15 @@ class JProjNode : public ProjNode { // input in slot 0. class PhiNode : public TypeNode { const TypePtr* const _adr_type; // non-null only for Type::MEMORY nodes. + const int _inst_id; // Instance id of the memory slice. + const int _inst_index; // Alias index of the instance memory slice. + // Array elements references have the same alias_idx but different offset. + const int _inst_offset; // Offset of the instance memory slice. // Size is bigger to hold the _adr_type field. virtual uint hash() const; // Check the type virtual uint cmp( const Node &n ) const; virtual uint size_of() const { return sizeof(*this); } - // Determine a unique non-trivial input, if any. - // Ignore casts if it helps. Return NULL on failure. - Node* unique_input(PhaseTransform *phase); // Determine if CMoveNode::is_cmove_id can be used at this join point. Node* is_cmove_id(PhaseTransform* phase, int true_path); @@ -127,8 +128,16 @@ public: Input // Input values are [1..len) }; - PhiNode( Node *r, const Type *t, const TypePtr* at = NULL ) - : TypeNode(t,r->req()), _adr_type(at) { + PhiNode( Node *r, const Type *t, const TypePtr* at = NULL, + const int iid = TypeOopPtr::UNKNOWN_INSTANCE, + const int iidx = Compile::AliasIdxTop, + const int ioffs = Type::OffsetTop ) + : TypeNode(t,r->req()), + _adr_type(at), + _inst_id(iid), + _inst_index(iidx), + _inst_offset(ioffs) + { init_class_id(Class_Phi); init_req(0, r); verify_adr_type(); @@ -152,6 +161,10 @@ public: return NULL; // not a copy! } + // Determine a unique non-trivial input, if any. + // Ignore casts if it helps. Return NULL on failure. + Node* unique_input(PhaseTransform *phase); + // Check for a simple dead loop. enum LoopSafety { Safe = 0, Unsafe, UnsafeLoop }; LoopSafety simple_data_loop_check(Node *in) const; @@ -161,6 +174,18 @@ public: virtual int Opcode() const; virtual bool pinned() const { return in(0) != 0; } virtual const TypePtr *adr_type() const { verify_adr_type(true); return _adr_type; } + + const int inst_id() const { return _inst_id; } + const int inst_index() const { return _inst_index; } + const int inst_offset() const { return _inst_offset; } + bool is_same_inst_field(const Type* tp, int id, int index, int offset) { + return type()->basic_type() == tp->basic_type() && + inst_id() == id && + inst_index() == index && + inst_offset() == offset && + type()->higher_equal(tp); + } + virtual const Type *Value( PhaseTransform *phase ) const; virtual Node *Identity( PhaseTransform *phase ); virtual Node *Ideal(PhaseGVN *phase, bool can_reshape); diff --git a/hotspot/src/share/vm/opto/loopopts.cpp b/hotspot/src/share/vm/opto/loopopts.cpp index d7b9ec89337..d0a94b4c265 100644 --- a/hotspot/src/share/vm/opto/loopopts.cpp +++ b/hotspot/src/share/vm/opto/loopopts.cpp @@ -32,7 +32,18 @@ Node *PhaseIdealLoop::split_thru_phi( Node *n, Node *region, int policy ) { int wins = 0; assert( !n->is_CFG(), "" ); assert( region->is_Region(), "" ); - Node *phi = new (C, region->req()) PhiNode( region, n->bottom_type() ); + + const Type* type = n->bottom_type(); + const TypeOopPtr *t_oop = _igvn.type(n)->isa_oopptr(); + Node *phi; + if( t_oop != NULL && t_oop->is_instance_field() ) { + int iid = t_oop->instance_id(); + int index = C->get_alias_index(t_oop); + int offset = t_oop->offset(); + phi = new (C,region->req()) PhiNode(region, type, NULL, iid, index, offset); + } else { + phi = new (C,region->req()) PhiNode(region, type); + } uint old_unique = C->unique(); for( uint i = 1; i < region->req(); i++ ) { Node *x; diff --git a/hotspot/src/share/vm/opto/memnode.cpp b/hotspot/src/share/vm/opto/memnode.cpp index 2cfa4281c48..936a303c8d0 100644 --- a/hotspot/src/share/vm/opto/memnode.cpp +++ b/hotspot/src/share/vm/opto/memnode.cpp @@ -87,6 +87,58 @@ extern void print_alias_types(); #endif +static Node *step_through_mergemem(PhaseGVN *phase, MergeMemNode *mmem, const TypePtr *tp, const TypePtr *adr_check, outputStream *st) { + uint alias_idx = phase->C->get_alias_index(tp); + Node *mem = mmem; +#ifdef ASSERT + { + // Check that current type is consistent with the alias index used during graph construction + assert(alias_idx >= Compile::AliasIdxRaw, "must not be a bad alias_idx"); + bool consistent = adr_check == NULL || adr_check->empty() || + phase->C->must_alias(adr_check, alias_idx ); + // Sometimes dead array references collapse to a[-1], a[-2], or a[-3] + if( !consistent && adr_check != NULL && !adr_check->empty() && + tp->isa_aryptr() && tp->offset() == Type::OffsetBot && + adr_check->isa_aryptr() && adr_check->offset() != Type::OffsetBot && + ( adr_check->offset() == arrayOopDesc::length_offset_in_bytes() || + adr_check->offset() == oopDesc::klass_offset_in_bytes() || + adr_check->offset() == oopDesc::mark_offset_in_bytes() ) ) { + // don't assert if it is dead code. + consistent = true; + } + if( !consistent ) { + st->print("alias_idx==%d, adr_check==", alias_idx); + if( adr_check == NULL ) { + st->print("NULL"); + } else { + adr_check->dump(); + } + st->cr(); + print_alias_types(); + assert(consistent, "adr_check must match alias idx"); + } + } +#endif + // TypeInstPtr::NOTNULL+any is an OOP with unknown offset - generally + // means an array I have not precisely typed yet. Do not do any + // alias stuff with it any time soon. + const TypeOopPtr *tinst = tp->isa_oopptr(); + if( tp->base() != Type::AnyPtr && + !(tinst && + tinst->klass()->is_java_lang_Object() && + tinst->offset() == Type::OffsetBot) ) { + // compress paths and change unreachable cycles to TOP + // If not, we can update the input infinitely along a MergeMem cycle + // Equivalent code in PhiNode::Ideal + Node* m = phase->transform(mmem); + // If tranformed to a MergeMem, get the desired slice + // Otherwise the returned node represents memory for every slice + mem = (m->is_MergeMem())? m->as_MergeMem()->memory_at(alias_idx) : m; + // Update input if it is progress over what we have now + } + return mem; +} + //--------------------------Ideal_common--------------------------------------- // Look for degenerate control and memory inputs. Bypass MergeMem inputs. // Unhook non-raw memories from complete (macro-expanded) initializations. @@ -119,48 +171,8 @@ Node *MemNode::Ideal_common(PhaseGVN *phase, bool can_reshape) { if (mem->is_MergeMem()) { MergeMemNode* mmem = mem->as_MergeMem(); const TypePtr *tp = t_adr->is_ptr(); - uint alias_idx = phase->C->get_alias_index(tp); -#ifdef ASSERT - { - // Check that current type is consistent with the alias index used during graph construction - assert(alias_idx >= Compile::AliasIdxRaw, "must not be a bad alias_idx"); - const TypePtr *adr_t = adr_type(); - bool consistent = adr_t == NULL || adr_t->empty() || phase->C->must_alias(adr_t, alias_idx ); - // Sometimes dead array references collapse to a[-1], a[-2], or a[-3] - if( !consistent && adr_t != NULL && !adr_t->empty() && - tp->isa_aryptr() && tp->offset() == Type::OffsetBot && - adr_t->isa_aryptr() && adr_t->offset() != Type::OffsetBot && - ( adr_t->offset() == arrayOopDesc::length_offset_in_bytes() || - adr_t->offset() == oopDesc::klass_offset_in_bytes() || - adr_t->offset() == oopDesc::mark_offset_in_bytes() ) ) { - // don't assert if it is dead code. - consistent = true; - } - if( !consistent ) { - tty->print("alias_idx==%d, adr_type()==", alias_idx); if( adr_t == NULL ) { tty->print("NULL"); } else { adr_t->dump(); } - tty->cr(); - print_alias_types(); - assert(consistent, "adr_type must match alias idx"); - } - } -#endif - // TypeInstPtr::NOTNULL+any is an OOP with unknown offset - generally - // means an array I have not precisely typed yet. Do not do any - // alias stuff with it any time soon. - const TypeInstPtr *tinst = tp->isa_instptr(); - if( tp->base() != Type::AnyPtr && - !(tinst && - tinst->klass()->is_java_lang_Object() && - tinst->offset() == Type::OffsetBot) ) { - // compress paths and change unreachable cycles to TOP - // If not, we can update the input infinitely along a MergeMem cycle - // Equivalent code in PhiNode::Ideal - Node* m = phase->transform(mmem); - // If tranformed to a MergeMem, get the desired slice - // Otherwise the returned node represents memory for every slice - mem = (m->is_MergeMem())? m->as_MergeMem()->memory_at(alias_idx) : m; - // Update input if it is progress over what we have now - } + + mem = step_through_mergemem(phase, mmem, tp, adr_type(), tty); } if (mem != old_mem) { @@ -534,7 +546,10 @@ Node *MemNode::Ideal_DU_postCCP( PhaseCCP *ccp ) { const Node* call = adr->in(0); if (call->is_CallStaticJava()) { const CallStaticJavaNode* call_java = call->as_CallStaticJava(); - assert(call_java && call_java->method() == NULL, "must be runtime call"); + const TypeTuple *r = call_java->tf()->range(); + assert(r->cnt() > TypeFunc::Parms, "must return value"); + const Type* ret_type = r->field_at(TypeFunc::Parms); + assert(ret_type && ret_type->isa_ptr(), "must return pointer"); // We further presume that this is one of // new_instance_Java, new_array_Java, or // the like, but do not assert for this. @@ -732,6 +747,21 @@ Node* MemNode::can_see_stored_value(Node* st, PhaseTransform* phase) const { return NULL; } +//----------------------is_instance_field_load_with_local_phi------------------ +bool LoadNode::is_instance_field_load_with_local_phi(Node* ctrl) { + if( in(MemNode::Memory)->is_Phi() && in(MemNode::Memory)->in(0) == ctrl && + in(MemNode::Address)->is_AddP() ) { + const TypeOopPtr* t_oop = in(MemNode::Address)->bottom_type()->isa_oopptr(); + // Only instances. + if( t_oop != NULL && t_oop->is_instance_field() && + t_oop->offset() != Type::OffsetBot && + t_oop->offset() != Type::OffsetTop) { + return true; + } + } + return false; +} + //------------------------------Identity--------------------------------------- // Loads are identity if previous store is to same address Node *LoadNode::Identity( PhaseTransform *phase ) { @@ -754,6 +784,25 @@ Node *LoadNode::Identity( PhaseTransform *phase ) { // usually runs first, producing the singleton type of the Con.) return value; } + + // Search for an existing data phi which was generated before for the same + // instance's field to avoid infinite genertion of phis in a loop. + Node *region = mem->in(0); + if (is_instance_field_load_with_local_phi(region)) { + const TypePtr *addr_t = in(MemNode::Address)->bottom_type()->isa_ptr(); + int this_index = phase->C->get_alias_index(addr_t); + int this_offset = addr_t->offset(); + int this_id = addr_t->is_oopptr()->instance_id(); + const Type* this_type = bottom_type(); + for (DUIterator_Fast imax, i = region->fast_outs(imax); i < imax; i++) { + Node* phi = region->fast_out(i); + if (phi->is_Phi() && phi != mem && + phi->as_Phi()->is_same_inst_field(this_type, this_id, this_index, this_offset)) { + return phi; + } + } + } + return this; } @@ -1189,6 +1238,17 @@ const Type *LoadNode::Value( PhaseTransform *phase ) const { return value->bottom_type(); } + const TypeOopPtr *tinst = tp->isa_oopptr(); + if (tinst != NULL && tinst->is_instance_field()) { + // If we have an instance type and our memory input is the + // programs's initial memory state, there is no matching store, + // so just return a zero of the appropriate type + Node *mem = in(MemNode::Memory); + if (mem->is_Parm() && mem->in(0)->is_Start()) { + assert(mem->as_Parm()->_con == TypeFunc::Memory, "must be memory Parm"); + return Type::get_zero_type(_type->basic_type()); + } + } return _type; } @@ -1712,7 +1772,7 @@ bool StoreNode::value_never_loaded( PhaseTransform *phase) const { const TypeOopPtr *adr_oop = phase->type(adr)->isa_oopptr(); if (adr_oop == NULL) return false; - if (!adr_oop->is_instance()) + if (!adr_oop->is_instance_field()) return false; // if not a distinct instance, there may be aliases of the address for (DUIterator_Fast imax, i = adr->fast_outs(imax); i < imax; i++) { Node *use = adr->fast_out(i); @@ -3244,7 +3304,7 @@ Node *MergeMemNode::Ideal(PhaseGVN *phase, bool can_reshape) { } } - assert(verify_sparse(), "please, no dups of base"); + assert(progress || verify_sparse(), "please, no dups of base"); return progress; } diff --git a/hotspot/src/share/vm/opto/memnode.hpp b/hotspot/src/share/vm/opto/memnode.hpp index 8c8676b4d36..bff0fd93b4b 100644 --- a/hotspot/src/share/vm/opto/memnode.hpp +++ b/hotspot/src/share/vm/opto/memnode.hpp @@ -172,6 +172,9 @@ public: // Map a load opcode to its corresponding store opcode. virtual int store_Opcode() const = 0; + // Check if the load's memory input is a Phi node with the same control. + bool is_instance_field_load_with_local_phi(Node* ctrl); + #ifndef PRODUCT virtual void dump_spec(outputStream *st) const; #endif diff --git a/hotspot/src/share/vm/opto/type.cpp b/hotspot/src/share/vm/opto/type.cpp index e396c9732b0..333fb476b0f 100644 --- a/hotspot/src/share/vm/opto/type.cpp +++ b/hotspot/src/share/vm/opto/type.cpp @@ -3164,7 +3164,7 @@ const Type *TypeAryPtr::xmeet( const Type *t ) const { case TopPTR: // Compute new klass on demand, do not use tap->_klass xk = (tap->_klass_is_exact | this->_klass_is_exact); - return make( ptr, const_oop(), tary, lazy_klass, xk, off ); + return make( ptr, const_oop(), tary, lazy_klass, xk, off, iid ); case Constant: { ciObject* o = const_oop(); if( _ptr == Constant ) { @@ -3176,7 +3176,7 @@ const Type *TypeAryPtr::xmeet( const Type *t ) const { o = tap->const_oop(); } xk = true; - return TypeAryPtr::make( ptr, o, tary, tap->_klass, xk, off ); + return TypeAryPtr::make( ptr, o, tary, tap->_klass, xk, off, iid ); } case NotNull: case BotPTR: @@ -3263,14 +3263,21 @@ void TypeAryPtr::dump2( Dict &d, uint depth, outputStream *st ) const { break; } - st->print("*"); + if( _offset != 0 ) { + int header_size = objArrayOopDesc::header_size() * wordSize; + if( _offset == OffsetTop ) st->print("+undefined"); + else if( _offset == OffsetBot ) st->print("+any"); + else if( _offset < header_size ) st->print("+%d", _offset); + else { + BasicType basic_elem_type = elem()->basic_type(); + int array_base = arrayOopDesc::base_offset_in_bytes(basic_elem_type); + int elem_size = type2aelembytes(basic_elem_type); + st->print("[%d]", (_offset - array_base)/elem_size); + } + } + st->print(" *"); if (_instance_id != UNKNOWN_INSTANCE) st->print(",iid=%d",_instance_id); - if( !_offset ) return; - if( _offset == OffsetTop ) st->print("+undefined"); - else if( _offset == OffsetBot ) st->print("+any"); - else if( _offset < 12 ) st->print("+%d",_offset); - else st->print("[%d]", (_offset-12)/4 ); } #endif diff --git a/hotspot/src/share/vm/opto/type.hpp b/hotspot/src/share/vm/opto/type.hpp index 4a697311f61..c68205f8880 100644 --- a/hotspot/src/share/vm/opto/type.hpp +++ b/hotspot/src/share/vm/opto/type.hpp @@ -686,6 +686,7 @@ public: bool klass_is_exact() const { return _klass_is_exact; } bool is_instance() const { return _instance_id != UNKNOWN_INSTANCE; } uint instance_id() const { return _instance_id; } + bool is_instance_field() const { return _instance_id != UNKNOWN_INSTANCE && _offset >= 0; } virtual intptr_t get_con() const; From 387f42921bf712a1a93d0be96eae7768ebdca7b4 Mon Sep 17 00:00:00 2001 From: Steve Bohne Date: Fri, 14 Mar 2008 10:43:02 -0400 Subject: [PATCH 054/258] 6204603: Modify hotspot to use new Solaris mmap semantics for class data archive file Os::attempt_reserve_memory_at() now passes an address hint to mmap Reviewed-by: kamg, dice --- hotspot/src/os/solaris/vm/os_solaris.cpp | 49 ++++++++++++++++++------ hotspot/src/os/solaris/vm/os_solaris.hpp | 1 + 2 files changed, 39 insertions(+), 11 deletions(-) diff --git a/hotspot/src/os/solaris/vm/os_solaris.cpp b/hotspot/src/os/solaris/vm/os_solaris.cpp index e1fb6ff6204..8d0861c7091 100644 --- a/hotspot/src/os/solaris/vm/os_solaris.cpp +++ b/hotspot/src/os/solaris/vm/os_solaris.cpp @@ -2785,16 +2785,15 @@ char* os::Solaris::mmap_chunk(char *addr, size_t size, int flags, int prot) { return b; } -char* -os::reserve_memory(size_t bytes, char* requested_addr, size_t alignment_hint) { - char* addr = NULL; - int flags; +char* os::Solaris::anon_mmap(char* requested_addr, size_t bytes, size_t alignment_hint, bool fixed) { + char* addr = requested_addr; + int flags = MAP_PRIVATE | MAP_NORESERVE; - flags = MAP_PRIVATE | MAP_NORESERVE; - if (requested_addr != NULL) { - flags |= MAP_FIXED; - addr = requested_addr; - } else if (has_map_align && alignment_hint > (size_t) vm_page_size()) { + assert(!(fixed && (alignment_hint > 0)), "alignment hint meaningless with fixed mmap"); + + if (fixed) { + flags |= MAP_FIXED; + } else if (has_map_align && (alignment_hint > (size_t) vm_page_size())) { flags |= MAP_ALIGN; addr = (char*) alignment_hint; } @@ -2802,11 +2801,14 @@ os::reserve_memory(size_t bytes, char* requested_addr, size_t alignment_hint) { // Map uncommitted pages PROT_NONE so we fail early if we touch an // uncommitted page. Otherwise, the read/write might succeed if we // have enough swap space to back the physical page. - addr = Solaris::mmap_chunk(addr, bytes, flags, PROT_NONE); + return mmap_chunk(addr, bytes, flags, PROT_NONE); +} + +char* os::reserve_memory(size_t bytes, char* requested_addr, size_t alignment_hint) { + char* addr = Solaris::anon_mmap(requested_addr, bytes, alignment_hint, (requested_addr != NULL)); guarantee(requested_addr == NULL || requested_addr == addr, "OS failed to return requested mmap address."); - return addr; } @@ -2832,6 +2834,31 @@ char* os::attempt_reserve_memory_at(size_t bytes, char* requested_addr) { // in one of the methods further up the call chain. See bug 5044738. assert(bytes % os::vm_page_size() == 0, "reserving unexpected size block"); + // Since snv_84, Solaris attempts to honor the address hint - see 5003415. + // Give it a try, if the kernel honors the hint we can return immediately. + char* addr = Solaris::anon_mmap(requested_addr, bytes, 0, false); + volatile int err = errno; + if (addr == requested_addr) { + return addr; + } else if (addr != NULL) { + unmap_memory(addr, bytes); + } + + if (PrintMiscellaneous && Verbose) { + char buf[256]; + buf[0] = '\0'; + if (addr == NULL) { + jio_snprintf(buf, sizeof(buf), ": %s", strerror(err)); + } + warning("attempt_reserve_memory_at: couldn't reserve %d bytes at " + PTR_FORMAT ": reserve_memory_helper returned " PTR_FORMAT + "%s", bytes, requested_addr, addr, buf); + } + + // Address hint method didn't work. Fall back to the old method. + // In theory, once SNV becomes our oldest supported platform, this + // code will no longer be needed. + // // Repeatedly allocate blocks until the block is allocated at the // right spot. Give up after max_tries. int i; diff --git a/hotspot/src/os/solaris/vm/os_solaris.hpp b/hotspot/src/os/solaris/vm/os_solaris.hpp index 201730ee1a7..b66bcb2bf6f 100644 --- a/hotspot/src/os/solaris/vm/os_solaris.hpp +++ b/hotspot/src/os/solaris/vm/os_solaris.hpp @@ -156,6 +156,7 @@ class Solaris { static int get_dev_zero_fd() { return _dev_zero_fd; } static void set_dev_zero_fd(int fd) { _dev_zero_fd = fd; } static char* mmap_chunk(char *addr, size_t size, int flags, int prot); + static char* anon_mmap(char* requested_addr, size_t bytes, size_t alignment_hint, bool fixed); static bool mpss_sanity_check(bool warn, size_t * page_size); static bool ism_sanity_check (bool warn, size_t * page_size); From fc0117cb9af9db1539415aa8a2f45d0360a755f4 Mon Sep 17 00:00:00 2001 From: Vladimir Kozlov Date: Fri, 14 Mar 2008 15:26:33 -0700 Subject: [PATCH 055/258] 6674588: (Escape Analysis) Improve Escape Analysis code Current EA code has several problems which have to be fixed. Reviewed-by: jrose, sgoldman --- hotspot/src/share/vm/includeDB_compiler2 | 4 +- hotspot/src/share/vm/opto/c2_globals.hpp | 6 + hotspot/src/share/vm/opto/callnode.cpp | 81 + hotspot/src/share/vm/opto/callnode.hpp | 20 +- hotspot/src/share/vm/opto/compile.cpp | 10 +- hotspot/src/share/vm/opto/compile.hpp | 1 - hotspot/src/share/vm/opto/escape.cpp | 1573 ++++++++++++++------ hotspot/src/share/vm/opto/escape.hpp | 158 +- hotspot/src/share/vm/opto/node.cpp | 5 +- hotspot/src/share/vm/opto/node.hpp | 1 - hotspot/src/share/vm/opto/phaseX.cpp | 13 +- hotspot/src/share/vm/runtime/arguments.cpp | 3 + 12 files changed, 1352 insertions(+), 523 deletions(-) diff --git a/hotspot/src/share/vm/includeDB_compiler2 b/hotspot/src/share/vm/includeDB_compiler2 index 514f6883b27..43233ad41dd 100644 --- a/hotspot/src/share/vm/includeDB_compiler2 +++ b/hotspot/src/share/vm/includeDB_compiler2 @@ -164,6 +164,7 @@ callGenerator.hpp deoptimization.hpp callGenerator.hpp type.hpp callnode.cpp callnode.hpp +callnode.cpp bcEscapeAnalyzer.hpp callnode.cpp escape.hpp callnode.cpp locknode.hpp callnode.cpp machnode.hpp @@ -176,7 +177,6 @@ callnode.cpp rootnode.hpp callnode.cpp runtime.hpp callnode.hpp connode.hpp -callnode.hpp escape.hpp callnode.hpp mulnode.hpp callnode.hpp multnode.hpp callnode.hpp opcodes.hpp @@ -347,7 +347,6 @@ connode.cpp addnode.hpp connode.cpp allocation.inline.hpp connode.cpp compile.hpp connode.cpp connode.hpp -connode.cpp escape.hpp connode.cpp machnode.hpp connode.cpp matcher.hpp connode.cpp memnode.hpp @@ -844,7 +843,6 @@ phaseX.cpp block.hpp phaseX.cpp callnode.hpp phaseX.cpp cfgnode.hpp phaseX.cpp connode.hpp -phaseX.cpp escape.hpp phaseX.cpp loopnode.hpp phaseX.cpp machnode.hpp phaseX.cpp opcodes.hpp diff --git a/hotspot/src/share/vm/opto/c2_globals.hpp b/hotspot/src/share/vm/opto/c2_globals.hpp index 4cfbcca2c98..bdf07f63f48 100644 --- a/hotspot/src/share/vm/opto/c2_globals.hpp +++ b/hotspot/src/share/vm/opto/c2_globals.hpp @@ -382,6 +382,12 @@ product(bool, EliminateAllocations, true, \ "Use escape analysis to eliminate allocations") \ \ + notproduct(bool, PrintEliminateAllocations, false, \ + "Print out when allocations are eliminated") \ + \ + product(intx, EliminateAllocationArraySizeLimit, 64, \ + "Array size (number of elements) limit for scalar replacement") \ + \ product(intx, MaxLabelRootDepth, 1100, \ "Maximum times call Label_Root to prevent stack overflow") \ diff --git a/hotspot/src/share/vm/opto/callnode.cpp b/hotspot/src/share/vm/opto/callnode.cpp index b0bcf4ee8da..60a183def71 100644 --- a/hotspot/src/share/vm/opto/callnode.cpp +++ b/hotspot/src/share/vm/opto/callnode.cpp @@ -624,6 +624,87 @@ uint CallNode::match_edge(uint idx) const { return 0; } +// +// Determine whether the call could modify a memory value of the +// specified address type +// +bool CallNode::may_modify(const TypePtr *addr_t, PhaseTransform *phase) { + const TypeOopPtr *adrInst_t = addr_t->isa_oopptr(); + + // if not an InstPtr or not an instance type, assume the worst + if (adrInst_t == NULL || !adrInst_t->is_instance_field()) { + return true; + } + Compile *C = phase->C; + int offset = adrInst_t->offset(); + assert(offset >= 0, "should be valid offset"); + assert(addr_t->isa_instptr() || addr_t->isa_aryptr(), "only instances or arrays are expected"); + + int base_idx = C->get_alias_index(adrInst_t); + ciMethod * meth = is_CallStaticJava() ? as_CallStaticJava()->method() : NULL; + BCEscapeAnalyzer *bcea = (meth != NULL) ? meth->get_bcea() : NULL; + + const TypeTuple * d = tf()->domain(); + for (uint i = TypeFunc::Parms; i < d->cnt(); i++) { + const Type* t = d->field_at(i); + Node *arg = in(i); + const Type *at = phase->type(arg); + if (at == TypePtr::NULL_PTR || at == Type::TOP) + continue; // null can't affect anything + + const TypeOopPtr *at_ptr = at->isa_oopptr(); + if (!arg->is_top() && (t->isa_oopptr() != NULL || + t->isa_ptr() && at_ptr != NULL)) { + assert(at_ptr != NULL, "expecting an OopPtr"); + // If we have found an argument matching adr_base_t, check if the field + // at the specified offset is modified. Since we don't know the size, + // assume 8. + int at_idx = C->get_alias_index(at_ptr->add_offset(offset)->isa_oopptr()); + if (base_idx == at_idx && + (bcea == NULL || + bcea->is_arg_modified(i - TypeFunc::Parms, offset, 8))) { + return true; + } + } + } + return false; +} + +// Does this call have a direct reference to n other than debug information? +bool CallNode::has_non_debug_use(Node *n) { + const TypeTuple * d = tf()->domain(); + for (uint i = TypeFunc::Parms; i < d->cnt(); i++) { + Node *arg = in(i); + if (arg == n) { + return true; + } + } + return false; +} + +// Returns the unique CheckCastPP of a call +// or 'this' if there are several CheckCastPP +// or returns NULL if there is no one. +Node *CallNode::result_cast() { + Node *cast = NULL; + + Node *p = proj_out(TypeFunc::Parms); + if (p == NULL) + return NULL; + + for (DUIterator_Fast imax, i = p->fast_outs(imax); i < imax; i++) { + Node *use = p->fast_out(i); + if (use->is_CheckCastPP()) { + if (cast != NULL) { + return this; // more than 1 CheckCastPP + } + cast = use; + } + } + return cast; +} + + //============================================================================= uint CallJavaNode::size_of() const { return sizeof(*this); } uint CallJavaNode::cmp( const Node &n ) const { diff --git a/hotspot/src/share/vm/opto/callnode.hpp b/hotspot/src/share/vm/opto/callnode.hpp index 179ad06b007..ccdac0a7cc9 100644 --- a/hotspot/src/share/vm/opto/callnode.hpp +++ b/hotspot/src/share/vm/opto/callnode.hpp @@ -388,6 +388,9 @@ public: void set_next_exception(SafePointNode* n); bool has_exceptions() const { return next_exception() != NULL; } + // Does this node have a use of n other than in debug information? + virtual bool has_non_debug_use(Node *n) {return false; } + // Standard Node stuff virtual int Opcode() const; virtual bool pinned() const { return true; } @@ -457,7 +460,6 @@ public: const TypeFunc *_tf; // Function type address _entry_point; // Address of method being called float _cnt; // Estimate of number of times called - PointsToNode::EscapeState _escape_state; CallNode(const TypeFunc* tf, address addr, const TypePtr* adr_type) : SafePointNode(tf->domain()->cnt(), NULL, adr_type), @@ -467,7 +469,6 @@ public: { init_class_id(Class_Call); init_flags(Flag_is_Call); - _escape_state = PointsToNode::UnknownEscape; } const TypeFunc* tf() const { return _tf; } @@ -493,6 +494,15 @@ public: // the node the JVMState must be cloned. virtual void clone_jvms() { } // default is not to clone + // Returns true if the call may modify n + virtual bool may_modify(const TypePtr *addr_t, PhaseTransform *phase); + // Does this node have a use of n other than in debug information? + virtual bool has_non_debug_use(Node *n); + // Returns the unique CheckCastPP of a call + // or result projection is there are several CheckCastPP + // or returns NULL if there is no one. + Node *result_cast(); + virtual uint match_edge(uint idx) const; #ifndef PRODUCT @@ -689,6 +699,9 @@ public: virtual uint ideal_reg() const { return Op_RegP; } virtual bool guaranteed_safepoint() { return false; } + // allocations do not modify their arguments + virtual bool may_modify(const TypePtr *addr_t, PhaseTransform *phase) { return false;} + // Pattern-match a possible usage of AllocateNode. // Return null if no allocation is recognized. // The operand is the pointer produced by the (possible) allocation. @@ -801,6 +814,9 @@ public: // mark node as eliminated and update the counter if there is one void set_eliminated(); + // locking does not modify its arguments + virtual bool may_modify(const TypePtr *addr_t, PhaseTransform *phase){ return false;} + #ifndef PRODUCT void create_lock_counter(JVMState* s); NamedCounter* counter() const { return _counter; } diff --git a/hotspot/src/share/vm/opto/compile.cpp b/hotspot/src/share/vm/opto/compile.cpp index 475b281a89a..3fe43b53095 100644 --- a/hotspot/src/share/vm/opto/compile.cpp +++ b/hotspot/src/share/vm/opto/compile.cpp @@ -407,11 +407,6 @@ uint Compile::scratch_emit_size(const Node* n) { return buf.code_size(); } -void Compile::record_for_escape_analysis(Node* n) { - if (_congraph != NULL) - _congraph->record_for_escape_analysis(n); -} - // ============================================================================ //------------------------------Compile standard------------------------------- @@ -494,9 +489,6 @@ Compile::Compile( ciEnv* ci_env, C2Compiler* compiler, ciMethod* target, int osr PhaseGVN gvn(node_arena(), estimated_size); set_initial_gvn(&gvn); - if (_do_escape_analysis) - _congraph = new ConnectionGraph(this); - { // Scope for timing the parser TracePhase t3("parse", &_t_parser, true); @@ -581,6 +573,8 @@ Compile::Compile( ciEnv* ci_env, C2Compiler* compiler, ciMethod* target, int osr NOT_PRODUCT( verify_graph_edges(); ) // Perform escape analysis + if (_do_escape_analysis) + _congraph = new ConnectionGraph(this); if (_congraph != NULL) { NOT_PRODUCT( TracePhase t2("escapeAnalysis", &_t_escapeAnalysis, TimeCompiler); ) _congraph->compute_escape(); diff --git a/hotspot/src/share/vm/opto/compile.hpp b/hotspot/src/share/vm/opto/compile.hpp index 419bc68bebe..279b448516e 100644 --- a/hotspot/src/share/vm/opto/compile.hpp +++ b/hotspot/src/share/vm/opto/compile.hpp @@ -485,7 +485,6 @@ class Compile : public Phase { PhaseGVN* initial_gvn() { return _initial_gvn; } Unique_Node_List* for_igvn() { return _for_igvn; } inline void record_for_igvn(Node* n); // Body is after class Unique_Node_List. - void record_for_escape_analysis(Node* n); void set_initial_gvn(PhaseGVN *gvn) { _initial_gvn = gvn; } void set_for_igvn(Unique_Node_List *for_igvn) { _for_igvn = for_igvn; } diff --git a/hotspot/src/share/vm/opto/escape.cpp b/hotspot/src/share/vm/opto/escape.cpp index 7e2a18d8539..e587cee177f 100644 --- a/hotspot/src/share/vm/opto/escape.cpp +++ b/hotspot/src/share/vm/opto/escape.cpp @@ -60,9 +60,9 @@ static char *node_type_names[] = { static char *esc_names[] = { "UnknownEscape", - "NoEscape ", - "ArgEscape ", - "GlobalEscape " + "NoEscape", + "ArgEscape", + "GlobalEscape" }; static char *edge_type_suffix[] = { @@ -75,7 +75,7 @@ static char *edge_type_suffix[] = { void PointsToNode::dump() const { NodeType nt = node_type(); EscapeState es = escape_state(); - tty->print("%s %s [[", node_type_names[(int) nt], esc_names[(int) es]); + tty->print("%s %s %s [[", node_type_names[(int) nt], esc_names[(int) es], _scalar_replaceable ? "" : "NSR"); for (uint i = 0; i < edge_count(); i++) { tty->print(" %d%s", edge_target(i), edge_type_suffix[(int) edge_type(i)]); } @@ -91,9 +91,11 @@ ConnectionGraph::ConnectionGraph(Compile * C) : _processed(C->comp_arena()), _no _collecting = true; this->_compile = C; const PointsToNode &dummy = PointsToNode(); - _nodes = new(C->comp_arena()) GrowableArray(C->comp_arena(), (int) INITIAL_NODE_COUNT, 0, dummy); + int sz = C->unique(); + _nodes = new(C->comp_arena()) GrowableArray(C->comp_arena(), sz, sz, dummy); _phantom_object = C->top()->_idx; PointsToNode *phn = ptnode_adr(_phantom_object); + phn->_node = C->top(); phn->set_node_type(PointsToNode::JavaObject); phn->set_escape_state(PointsToNode::GlobalEscape); } @@ -121,8 +123,20 @@ void ConnectionGraph::add_deferred_edge(uint from_i, uint to_i) { f->add_edge(to_i, PointsToNode::DeferredEdge); } -int ConnectionGraph::type_to_offset(const Type *t) { - const TypePtr *t_ptr = t->isa_ptr(); +int ConnectionGraph::address_offset(Node* adr, PhaseTransform *phase) { + const Type *adr_type = phase->type(adr); + if (adr->is_AddP() && adr_type->isa_oopptr() == NULL && + adr->in(AddPNode::Address)->is_Proj() && + adr->in(AddPNode::Address)->in(0)->is_Allocate()) { + // We are computing a raw address for a store captured by an Initialize + // compute an appropriate address type. AddP cases #3 and #5 (see below). + int offs = (int)phase->find_intptr_t_con(adr->in(AddPNode::Offset), Type::OffsetBot); + assert(offs != Type::OffsetBot || + adr->in(AddPNode::Address)->in(0)->is_AllocateArray(), + "offset must be a constant or it is initialization of array"); + return offs; + } + const TypePtr *t_ptr = adr_type->isa_ptr(); assert(t_ptr != NULL, "must be a pointer type"); return t_ptr->offset(); } @@ -147,12 +161,28 @@ void ConnectionGraph::set_escape_state(uint ni, PointsToNode::EscapeState es) { npt->set_escape_state(es); } +void ConnectionGraph::add_node(Node *n, PointsToNode::NodeType nt, + PointsToNode::EscapeState es, bool done) { + PointsToNode* ptadr = ptnode_adr(n->_idx); + ptadr->_node = n; + ptadr->set_node_type(nt); + + // inline set_escape_state(idx, es); + PointsToNode::EscapeState old_es = ptadr->escape_state(); + if (es > old_es) + ptadr->set_escape_state(es); + + if (done) + _processed.set(n->_idx); +} + PointsToNode::EscapeState ConnectionGraph::escape_state(Node *n, PhaseTransform *phase) { uint idx = n->_idx; PointsToNode::EscapeState es; - // If we are still collecting we don't know the answer yet - if (_collecting) + // If we are still collecting or there were no non-escaping allocations + // we don't know the answer yet + if (_collecting || !_has_allocations) return PointsToNode::UnknownEscape; // if the node was created after the escape computation, return @@ -169,9 +199,9 @@ PointsToNode::EscapeState ConnectionGraph::escape_state(Node *n, PhaseTransform // compute max escape state of anything this node could point to VectorSet ptset(Thread::current()->resource_area()); PointsTo(ptset, n, phase); - for( VectorSetI i(&ptset); i.test() && es != PointsToNode::GlobalEscape; ++i ) { + for(VectorSetI i(&ptset); i.test() && es != PointsToNode::GlobalEscape; ++i) { uint pt = i.elem; - PointsToNode::EscapeState pes = _nodes->at(pt).escape_state(); + PointsToNode::EscapeState pes = _nodes->adr_at(pt)->escape_state(); if (pes > es) es = pes; } @@ -185,7 +215,7 @@ void ConnectionGraph::PointsTo(VectorSet &ptset, Node * n, PhaseTransform *phase VectorSet visited(Thread::current()->resource_area()); GrowableArray worklist; - n = skip_casts(n); + n = n->uncast(); PointsToNode npt = _nodes->at_grow(n->_idx); // If we have a JavaObject, return just that object @@ -193,39 +223,33 @@ void ConnectionGraph::PointsTo(VectorSet &ptset, Node * n, PhaseTransform *phase ptset.set(n->_idx); return; } - // we may have a Phi which has not been processed - if (npt._node == NULL) { - assert(n->is_Phi(), "unprocessed node must be a Phi"); - record_for_escape_analysis(n); - npt = _nodes->at(n->_idx); - } + assert(npt._node != NULL, "unregistered node"); + worklist.push(n->_idx); while(worklist.length() > 0) { int ni = worklist.pop(); PointsToNode pn = _nodes->at_grow(ni); - if (!visited.test(ni)) { - visited.set(ni); - + if (!visited.test_set(ni)) { // ensure that all inputs of a Phi have been processed - if (_collecting && pn._node->is_Phi()) { - PhiNode *phi = pn._node->as_Phi(); - process_phi_escape(phi, phase); - } + assert(!_collecting || !pn._node->is_Phi() || _processed.test(ni),""); int edges_processed = 0; for (uint e = 0; e < pn.edge_count(); e++) { + uint etgt = pn.edge_target(e); PointsToNode::EdgeType et = pn.edge_type(e); if (et == PointsToNode::PointsToEdge) { - ptset.set(pn.edge_target(e)); + ptset.set(etgt); edges_processed++; } else if (et == PointsToNode::DeferredEdge) { - worklist.push(pn.edge_target(e)); + worklist.push(etgt); edges_processed++; + } else { + assert(false,"neither PointsToEdge or DeferredEdge"); } } if (edges_processed == 0) { - // no deferred or pointsto edges found. Assume the value was set outside - // this method. Add the phantom object to the pointsto set. + // no deferred or pointsto edges found. Assume the value was set + // outside this method. Add the phantom object to the pointsto set. ptset.set(_phantom_object); } } @@ -239,20 +263,23 @@ void ConnectionGraph::remove_deferred(uint ni) { PointsToNode *ptn = ptnode_adr(ni); while(i < ptn->edge_count()) { + uint t = ptn->edge_target(i); + PointsToNode *ptt = ptnode_adr(t); if (ptn->edge_type(i) != PointsToNode::DeferredEdge) { i++; } else { - uint t = ptn->edge_target(i); - PointsToNode *ptt = ptnode_adr(t); ptn->remove_edge(t, PointsToNode::DeferredEdge); - if(!visited.test(t)) { - visited.set(t); + if(!visited.test_set(t)) { for (uint j = 0; j < ptt->edge_count(); j++) { uint n1 = ptt->edge_target(j); PointsToNode *pt1 = ptnode_adr(n1); switch(ptt->edge_type(j)) { case PointsToNode::PointsToEdge: - add_pointsto_edge(ni, n1); + add_pointsto_edge(ni, n1); + if(n1 == _phantom_object) { + // Special case - field set outside (globally escaping). + ptn->set_escape_state(PointsToNode::GlobalEscape); + } break; case PointsToNode::DeferredEdge: add_deferred_edge(ni, n1); @@ -291,8 +318,8 @@ void ConnectionGraph::add_edge_from_fields(uint adr_i, uint to_i, int offs) { } } -// Add a deferred edge from node given by "from_i" to any field of adr_i whose offset -// matches "offset" +// Add a deferred edge from node given by "from_i" to any field of adr_i +// whose offset matches "offset". void ConnectionGraph::add_deferred_edge_to_fields(uint from_i, uint adr_i, int offs) { PointsToNode an = _nodes->at_grow(adr_i); for (uint fe = 0; fe < an.edge_count(); fe++) { @@ -310,25 +337,108 @@ void ConnectionGraph::add_deferred_edge_to_fields(uint from_i, uint adr_i, int o } } -// -// Search memory chain of "mem" to find a MemNode whose address -// is the specified alias index. Returns the MemNode found or the -// first non-MemNode encountered. -// -Node *ConnectionGraph::find_mem(Node *mem, int alias_idx, PhaseGVN *igvn) { - if (mem == NULL) - return mem; - while (mem->is_Mem()) { - const Type *at = igvn->type(mem->in(MemNode::Address)); - if (at != Type::TOP) { - assert (at->isa_ptr() != NULL, "pointer type required."); - int idx = _compile->get_alias_index(at->is_ptr()); - if (idx == alias_idx) - break; - } - mem = mem->in(MemNode::Memory); +// Helper functions + +static Node* get_addp_base(Node *addp) { + assert(addp->is_AddP(), "must be AddP"); + // + // AddP cases for Base and Address inputs: + // case #1. Direct object's field reference: + // Allocate + // | + // Proj #5 ( oop result ) + // | + // CheckCastPP (cast to instance type) + // | | + // AddP ( base == address ) + // + // case #2. Indirect object's field reference: + // Phi + // | + // CastPP (cast to instance type) + // | | + // AddP ( base == address ) + // + // case #3. Raw object's field reference for Initialize node: + // Allocate + // | + // Proj #5 ( oop result ) + // top | + // \ | + // AddP ( base == top ) + // + // case #4. Array's element reference: + // {CheckCastPP | CastPP} + // | | | + // | AddP ( array's element offset ) + // | | + // AddP ( array's offset ) + // + // case #5. Raw object's field reference for arraycopy stub call: + // The inline_native_clone() case when the arraycopy stub is called + // after the allocation before Initialize and CheckCastPP nodes. + // Allocate + // | + // Proj #5 ( oop result ) + // | | + // AddP ( base == address ) + // + // case #6. Constant Pool or ThreadLocal or Raw object's field reference: + // ConP # Object from Constant Pool. + // top | + // \ | + // AddP ( base == top ) + // + Node *base = addp->in(AddPNode::Base)->uncast(); + if (base->is_top()) { // The AddP case #3 and #6. + base = addp->in(AddPNode::Address)->uncast(); + assert(base->Opcode() == Op_ConP || base->Opcode() == Op_ThreadLocal || + base->is_Mem() && base->bottom_type() == TypeRawPtr::NOTNULL || + base->is_Proj() && base->in(0)->is_Allocate(), "sanity"); } - return mem; + return base; +} + +static Node* find_second_addp(Node* addp, Node* n) { + assert(addp->is_AddP() && addp->outcnt() > 0, "Don't process dead nodes"); + + Node* addp2 = addp->raw_out(0); + if (addp->outcnt() == 1 && addp2->is_AddP() && + addp2->in(AddPNode::Base) == n && + addp2->in(AddPNode::Address) == addp) { + + assert(addp->in(AddPNode::Base) == n, "expecting the same base"); + // + // Find array's offset to push it on worklist first and + // as result process an array's element offset first (pushed second) + // to avoid CastPP for the array's offset. + // Otherwise the inserted CastPP (LocalVar) will point to what + // the AddP (Field) points to. Which would be wrong since + // the algorithm expects the CastPP has the same point as + // as AddP's base CheckCastPP (LocalVar). + // + // ArrayAllocation + // | + // CheckCastPP + // | + // memProj (from ArrayAllocation CheckCastPP) + // | || + // | || Int (element index) + // | || | ConI (log(element size)) + // | || | / + // | || LShift + // | || / + // | AddP (array's element offset) + // | | + // | | ConI (array's offset: #12(32-bits) or #24(64-bits)) + // | / / + // AddP (array's offset) + // | + // Load/Store (memory operation on array's element) + // + return addp2; + } + return NULL; } // @@ -336,24 +446,33 @@ Node *ConnectionGraph::find_mem(Node *mem, int alias_idx, PhaseGVN *igvn) { // address of a field of an instance // void ConnectionGraph::split_AddP(Node *addp, Node *base, PhaseGVN *igvn) { - const TypeOopPtr *t = igvn->type(addp)->isa_oopptr(); const TypeOopPtr *base_t = igvn->type(base)->isa_oopptr(); - assert(t != NULL, "expecting oopptr"); assert(base_t != NULL && base_t->is_instance(), "expecting instance oopptr"); + const TypeOopPtr *t = igvn->type(addp)->isa_oopptr(); + if (t == NULL) { + // We are computing a raw address for a store captured by an Initialize + // compute an appropriate address type. + assert(igvn->type(addp) == TypeRawPtr::NOTNULL, "must be raw pointer"); + assert(addp->in(AddPNode::Address)->is_Proj(), "base of raw address must be result projection from allocation"); + int offs = (int)igvn->find_intptr_t_con(addp->in(AddPNode::Offset), Type::OffsetBot); + assert(offs != Type::OffsetBot, "offset must be a constant"); + t = base_t->add_offset(offs)->is_oopptr(); + } uint inst_id = base_t->instance_id(); assert(!t->is_instance() || t->instance_id() == inst_id, "old type must be non-instance or match new type"); const TypeOopPtr *tinst = base_t->add_offset(t->offset())->is_oopptr(); - // ensure an alias index is allocated for the instance type + // Do NOT remove the next call: ensure an new alias index is allocated + // for the instance type int alias_idx = _compile->get_alias_index(tinst); igvn->set_type(addp, tinst); // record the allocation in the node map set_map(addp->_idx, get_map(base->_idx)); - // if the Address input is not the appropriate instance type (due to intervening - // casts,) insert a cast + // if the Address input is not the appropriate instance type + // (due to intervening casts,) insert a cast Node *adr = addp->in(AddPNode::Address); const TypeOopPtr *atype = igvn->type(adr)->isa_oopptr(); - if (atype->instance_id() != inst_id) { + if (atype != NULL && atype->instance_id() != inst_id) { assert(!atype->is_instance(), "no conflicting instances"); const TypeOopPtr *new_atype = base_t->add_offset(atype->offset())->isa_oopptr(); Node *acast = new (_compile, 2) CastPPNode(adr, new_atype); @@ -372,8 +491,9 @@ void ConnectionGraph::split_AddP(Node *addp, Node *base, PhaseGVN *igvn) { addp->set_req(AddPNode::Base, bcast); addp->set_req(AddPNode::Address, acast); igvn->hash_insert(addp); - record_for_optimizer(addp); } + // Put on IGVN worklist since at least addp's type was changed above. + record_for_optimizer(addp); } // @@ -386,12 +506,11 @@ PhiNode *ConnectionGraph::create_split_phi(PhiNode *orig_phi, int alias_idx, Gro new_created = false; int phi_alias_idx = C->get_alias_index(orig_phi->adr_type()); // nothing to do if orig_phi is bottom memory or matches alias_idx - if (phi_alias_idx == Compile::AliasIdxBot || phi_alias_idx == alias_idx) { + if (phi_alias_idx == alias_idx) { return orig_phi; } // have we already created a Phi for this alias index? PhiNode *result = get_map_phi(orig_phi->_idx); - const TypePtr *atype = C->get_adr_type(alias_idx); if (result != NULL && C->get_alias_index(result->adr_type()) == alias_idx) { return result; } @@ -404,8 +523,8 @@ PhiNode *ConnectionGraph::create_split_phi(PhiNode *orig_phi, int alias_idx, Gro } return NULL; } - orig_phi_worklist.append_if_missing(orig_phi); + const TypePtr *atype = C->get_adr_type(alias_idx); result = PhiNode::make(orig_phi->in(0), NULL, Type::MEMORY, atype); set_map_phi(orig_phi->_idx, result); igvn->set_type(result, result->bottom_type()); @@ -423,7 +542,7 @@ PhiNode *ConnectionGraph::split_memory_phi(PhiNode *orig_phi, int alias_idx, Gro assert(alias_idx != Compile::AliasIdxBot, "can't split out bottom memory"); Compile *C = _compile; bool new_phi_created; - PhiNode *result = create_split_phi(orig_phi, alias_idx, orig_phi_worklist, igvn, new_phi_created); + PhiNode *result = create_split_phi(orig_phi, alias_idx, orig_phi_worklist, igvn, new_phi_created); if (!new_phi_created) { return result; } @@ -436,20 +555,20 @@ PhiNode *ConnectionGraph::split_memory_phi(PhiNode *orig_phi, int alias_idx, Gro bool finished = false; while(!finished) { while (idx < phi->req()) { - Node *mem = find_mem(phi->in(idx), alias_idx, igvn); + Node *mem = find_inst_mem(phi->in(idx), alias_idx, orig_phi_worklist, igvn); if (mem != NULL && mem->is_Phi()) { - PhiNode *nphi = create_split_phi(mem->as_Phi(), alias_idx, orig_phi_worklist, igvn, new_phi_created); + PhiNode *newphi = create_split_phi(mem->as_Phi(), alias_idx, orig_phi_worklist, igvn, new_phi_created); if (new_phi_created) { // found an phi for which we created a new split, push current one on worklist and begin // processing new one phi_list.push(phi); cur_input.push(idx); phi = mem->as_Phi(); - result = nphi; + result = newphi; idx = 1; continue; } else { - mem = nphi; + mem = newphi; } } if (C->failing()) { @@ -461,23 +580,124 @@ PhiNode *ConnectionGraph::split_memory_phi(PhiNode *orig_phi, int alias_idx, Gro // verify that the new Phi has an input for each input of the original assert( phi->req() == result->req(), "must have same number of inputs."); assert( result->in(0) != NULL && result->in(0) == phi->in(0), "regions must match"); - for (uint i = 1; i < phi->req(); i++) { - assert((phi->in(i) == NULL) == (result->in(i) == NULL), "inputs must correspond."); - } #endif + // Check if all new phi's inputs have specified alias index. + // Otherwise use old phi. + for (uint i = 1; i < phi->req(); i++) { + Node* in = result->in(i); + assert((phi->in(i) == NULL) == (in == NULL), "inputs must correspond."); + } // we have finished processing a Phi, see if there are any more to do finished = (phi_list.length() == 0 ); if (!finished) { phi = phi_list.pop(); idx = cur_input.pop(); - PhiNode *prev_phi = get_map_phi(phi->_idx); - prev_phi->set_req(idx++, result); - result = prev_phi; + PhiNode *prev_result = get_map_phi(phi->_idx); + prev_result->set_req(idx++, result); + result = prev_result; } } return result; } + +// +// The next methods are derived from methods in MemNode. +// +static Node *step_through_mergemem(MergeMemNode *mmem, int alias_idx, const TypeOopPtr *tinst) { + Node *mem = mmem; + // TypeInstPtr::NOTNULL+any is an OOP with unknown offset - generally + // means an array I have not precisely typed yet. Do not do any + // alias stuff with it any time soon. + if( tinst->base() != Type::AnyPtr && + !(tinst->klass()->is_java_lang_Object() && + tinst->offset() == Type::OffsetBot) ) { + mem = mmem->memory_at(alias_idx); + // Update input if it is progress over what we have now + } + return mem; +} + +// +// Search memory chain of "mem" to find a MemNode whose address +// is the specified alias index. +// +Node* ConnectionGraph::find_inst_mem(Node *orig_mem, int alias_idx, GrowableArray &orig_phis, PhaseGVN *phase) { + if (orig_mem == NULL) + return orig_mem; + Compile* C = phase->C; + const TypeOopPtr *tinst = C->get_adr_type(alias_idx)->isa_oopptr(); + bool is_instance = (tinst != NULL) && tinst->is_instance(); + Node *prev = NULL; + Node *result = orig_mem; + while (prev != result) { + prev = result; + if (result->is_Mem()) { + MemNode *mem = result->as_Mem(); + const Type *at = phase->type(mem->in(MemNode::Address)); + if (at != Type::TOP) { + assert (at->isa_ptr() != NULL, "pointer type required."); + int idx = C->get_alias_index(at->is_ptr()); + if (idx == alias_idx) + break; + } + result = mem->in(MemNode::Memory); + } + if (!is_instance) + continue; // don't search further for non-instance types + // skip over a call which does not affect this memory slice + if (result->is_Proj() && result->as_Proj()->_con == TypeFunc::Memory) { + Node *proj_in = result->in(0); + if (proj_in->is_Call()) { + CallNode *call = proj_in->as_Call(); + if (!call->may_modify(tinst, phase)) { + result = call->in(TypeFunc::Memory); + } + } else if (proj_in->is_Initialize()) { + AllocateNode* alloc = proj_in->as_Initialize()->allocation(); + // Stop if this is the initialization for the object instance which + // which contains this memory slice, otherwise skip over it. + if (alloc == NULL || alloc->_idx != tinst->instance_id()) { + result = proj_in->in(TypeFunc::Memory); + } + } else if (proj_in->is_MemBar()) { + result = proj_in->in(TypeFunc::Memory); + } + } else if (result->is_MergeMem()) { + MergeMemNode *mmem = result->as_MergeMem(); + result = step_through_mergemem(mmem, alias_idx, tinst); + if (result == mmem->base_memory()) { + // Didn't find instance memory, search through general slice recursively. + result = mmem->memory_at(C->get_general_index(alias_idx)); + result = find_inst_mem(result, alias_idx, orig_phis, phase); + if (C->failing()) { + return NULL; + } + mmem->set_memory_at(alias_idx, result); + } + } else if (result->is_Phi() && + C->get_alias_index(result->as_Phi()->adr_type()) != alias_idx) { + Node *un = result->as_Phi()->unique_input(phase); + if (un != NULL) { + result = un; + } else { + break; + } + } + } + if (is_instance && result->is_Phi()) { + PhiNode *mphi = result->as_Phi(); + assert(mphi->bottom_type() == Type::MEMORY, "memory phi required"); + const TypePtr *t = mphi->adr_type(); + if (C->get_alias_index(t) != alias_idx) { + result = split_memory_phi(mphi, alias_idx, orig_phis, phase); + } + } + // the result is either MemNode, PhiNode, InitializeNode. + return result; +} + + // // Convert the types of unescaped object to instance types where possible, // propagate the new type information through the graph, and update memory @@ -576,56 +796,101 @@ void ConnectionGraph::split_unique_types(GrowableArray &alloc_worklist) VectorSet visited(Thread::current()->resource_area()); VectorSet ptset(Thread::current()->resource_area()); - // Phase 1: Process possible allocations from alloc_worklist. Create instance - // types for the CheckCastPP for allocations where possible. + + // Phase 1: Process possible allocations from alloc_worklist. + // Create instance types for the CheckCastPP for allocations where possible. while (alloc_worklist.length() != 0) { Node *n = alloc_worklist.pop(); uint ni = n->_idx; + const TypeOopPtr* tinst = NULL; if (n->is_Call()) { CallNode *alloc = n->as_Call(); // copy escape information to call node - PointsToNode ptn = _nodes->at(alloc->_idx); + PointsToNode* ptn = _nodes->adr_at(alloc->_idx); PointsToNode::EscapeState es = escape_state(alloc, igvn); - alloc->_escape_state = es; - // find CheckCastPP of call return value - n = alloc->proj_out(TypeFunc::Parms); - if (n != NULL && n->outcnt() == 1) { - n = n->unique_out(); - if (n->Opcode() != Op_CheckCastPP) { - continue; - } - } else { + // We have an allocation or call which returns a Java object, + // see if it is unescaped. + if (es != PointsToNode::NoEscape || !ptn->_scalar_replaceable) continue; - } - // we have an allocation or call which returns a Java object, see if it is unescaped - if (es != PointsToNode::NoEscape || !ptn._unique_type) { - continue; // can't make a unique type - } if (alloc->is_Allocate()) { // Set the scalar_replaceable flag before the next check. alloc->as_Allocate()->_is_scalar_replaceable = true; } - + // find CheckCastPP of call return value + n = alloc->result_cast(); + if (n == NULL || // No uses accept Initialize or + !n->is_CheckCastPP()) // not unique CheckCastPP. + continue; + // The inline code for Object.clone() casts the allocation result to + // java.lang.Object and then to the the actual type of the allocated + // object. Detect this case and use the second cast. + if (alloc->is_Allocate() && n->as_Type()->type() == TypeInstPtr::NOTNULL + && igvn->type(alloc->in(AllocateNode::KlassNode)) != TypeKlassPtr::OBJECT) { + Node *cast2 = NULL; + for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) { + Node *use = n->fast_out(i); + if (use->is_CheckCastPP()) { + cast2 = use; + break; + } + } + if (cast2 != NULL) { + n = cast2; + } else { + continue; + } + } + set_escape_state(n->_idx, es); + // in order for an object to be stackallocatable, it must be: + // - a direct allocation (not a call returning an object) + // - non-escaping + // - eligible to be a unique type + // - not determined to be ineligible by escape analysis set_map(alloc->_idx, n); set_map(n->_idx, alloc); - const TypeInstPtr *t = igvn->type(n)->isa_instptr(); - // Unique types which are arrays are not currently supported. - // The check for AllocateArray is needed in case an array - // allocation is immediately cast to Object - if (t == NULL || alloc->is_AllocateArray()) + const TypeOopPtr *t = igvn->type(n)->isa_oopptr(); + if (t == NULL) continue; // not a TypeInstPtr - const TypeOopPtr *tinst = t->cast_to_instance(ni); + tinst = t->cast_to_instance(ni); igvn->hash_delete(n); igvn->set_type(n, tinst); n->raise_bottom_type(tinst); igvn->hash_insert(n); + record_for_optimizer(n); + if (alloc->is_Allocate() && ptn->_scalar_replaceable && + (t->isa_instptr() || t->isa_aryptr())) { + // An allocation may have an Initialize which has raw stores. Scan + // the users of the raw allocation result and push AddP users + // on alloc_worklist. + Node *raw_result = alloc->proj_out(TypeFunc::Parms); + assert (raw_result != NULL, "must have an allocation result"); + for (DUIterator_Fast imax, i = raw_result->fast_outs(imax); i < imax; i++) { + Node *use = raw_result->fast_out(i); + if (use->is_AddP() && use->outcnt() > 0) { // Don't process dead nodes + Node* addp2 = find_second_addp(use, raw_result); + if (addp2 != NULL) { + assert(alloc->is_AllocateArray(),"array allocation was expected"); + alloc_worklist.append_if_missing(addp2); + } + alloc_worklist.append_if_missing(use); + } else if (use->is_Initialize()) { + memnode_worklist.append_if_missing(use); + } + } + } } else if (n->is_AddP()) { ptset.Clear(); - PointsTo(ptset, n->in(AddPNode::Address), igvn); + PointsTo(ptset, get_addp_base(n), igvn); assert(ptset.Size() == 1, "AddP address is unique"); - Node *base = get_map(ptset.getelem()); + uint elem = ptset.getelem(); // Allocation node's index + if (elem == _phantom_object) + continue; // Assume the value was set outside this method. + Node *base = get_map(elem); // CheckCastPP node split_AddP(n, base, igvn); - } else if (n->is_Phi() || n->Opcode() == Op_CastPP || n->Opcode() == Op_CheckCastPP) { + tinst = igvn->type(base)->isa_oopptr(); + } else if (n->is_Phi() || + n->is_CheckCastPP() || + (n->is_ConstraintCast() && n->Opcode() == Op_CastPP)) { if (visited.test_set(n->_idx)) { assert(n->is_Phi(), "loops only through Phi's"); continue; // already processed @@ -633,17 +898,23 @@ void ConnectionGraph::split_unique_types(GrowableArray &alloc_worklist) ptset.Clear(); PointsTo(ptset, n, igvn); if (ptset.Size() == 1) { + uint elem = ptset.getelem(); // Allocation node's index + if (elem == _phantom_object) + continue; // Assume the value was set outside this method. + Node *val = get_map(elem); // CheckCastPP node TypeNode *tn = n->as_Type(); - Node *val = get_map(ptset.getelem()); - const TypeInstPtr *val_t = igvn->type(val)->isa_instptr();; - assert(val_t != NULL && val_t->is_instance(), "instance type expected."); - const TypeInstPtr *tn_t = igvn->type(tn)->isa_instptr();; + tinst = igvn->type(val)->isa_oopptr(); + assert(tinst != NULL && tinst->is_instance() && + tinst->instance_id() == elem , "instance type expected."); + const TypeOopPtr *tn_t = igvn->type(tn)->isa_oopptr(); - if (tn_t != NULL && val_t->cast_to_instance(TypeOopPtr::UNKNOWN_INSTANCE)->higher_equal(tn_t)) { + if (tn_t != NULL && + tinst->cast_to_instance(TypeOopPtr::UNKNOWN_INSTANCE)->higher_equal(tn_t)) { igvn->hash_delete(tn); - igvn->set_type(tn, val_t); - tn->set_type(val_t); + igvn->set_type(tn, tinst); + tn->set_type(tinst); igvn->hash_insert(tn); + record_for_optimizer(n); } } } else { @@ -653,13 +924,38 @@ void ConnectionGraph::split_unique_types(GrowableArray &alloc_worklist) for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) { Node *use = n->fast_out(i); if(use->is_Mem() && use->in(MemNode::Address) == n) { - memnode_worklist.push(use); - } else if (use->is_AddP() || use->is_Phi() || use->Opcode() == Op_CastPP || use->Opcode() == Op_CheckCastPP) { - alloc_worklist.push(use); + memnode_worklist.append_if_missing(use); + } else if (use->is_Initialize()) { + memnode_worklist.append_if_missing(use); + } else if (use->is_MergeMem()) { + mergemem_worklist.append_if_missing(use); + } else if (use->is_Call() && tinst != NULL) { + // Look for MergeMem nodes for calls which reference unique allocation + // (through CheckCastPP nodes) even for debug info. + Node* m = use->in(TypeFunc::Memory); + uint iid = tinst->instance_id(); + while (m->is_Proj() && m->in(0)->is_Call() && + m->in(0) != use && !m->in(0)->_idx != iid) { + m = m->in(0)->in(TypeFunc::Memory); + } + if (m->is_MergeMem()) { + mergemem_worklist.append_if_missing(m); + } + } else if (use->is_AddP() && use->outcnt() > 0) { // No dead nodes + Node* addp2 = find_second_addp(use, n); + if (addp2 != NULL) { + alloc_worklist.append_if_missing(addp2); + } + alloc_worklist.append_if_missing(use); + } else if (use->is_Phi() || + use->is_CheckCastPP() || + (use->is_ConstraintCast() && use->Opcode() == Op_CastPP)) { + alloc_worklist.append_if_missing(use); } } } + // New alias types were created in split_AddP(). uint new_index_end = (uint) _compile->num_alias_types(); // Phase 2: Process MemNode's from memnode_worklist. compute new address type and @@ -668,32 +964,37 @@ void ConnectionGraph::split_unique_types(GrowableArray &alloc_worklist) if (memnode_worklist.length() == 0) return; // nothing to do - while (memnode_worklist.length() != 0) { Node *n = memnode_worklist.pop(); + if (visited.test_set(n->_idx)) + continue; if (n->is_Phi()) { assert(n->as_Phi()->adr_type() != TypePtr::BOTTOM, "narrow memory slice required"); // we don't need to do anything, but the users must be pushed if we haven't processed // this Phi before - if (visited.test_set(n->_idx)) + } else if (n->is_Initialize()) { + // we don't need to do anything, but the users of the memory projection must be pushed + n = n->as_Initialize()->proj_out(TypeFunc::Memory); + if (n == NULL) continue; } else { assert(n->is_Mem(), "memory node required."); Node *addr = n->in(MemNode::Address); + assert(addr->is_AddP(), "AddP required"); const Type *addr_t = igvn->type(addr); if (addr_t == Type::TOP) continue; assert (addr_t->isa_ptr() != NULL, "pointer type required."); int alias_idx = _compile->get_alias_index(addr_t->is_ptr()); - Node *mem = find_mem(n->in(MemNode::Memory), alias_idx, igvn); - if (mem->is_Phi()) { - mem = split_memory_phi(mem->as_Phi(), alias_idx, orig_phis, igvn); - } + assert ((uint)alias_idx < new_index_end, "wrong alias index"); + Node *mem = find_inst_mem(n->in(MemNode::Memory), alias_idx, orig_phis, igvn); if (_compile->failing()) { return; } - if (mem != n->in(MemNode::Memory)) + if (mem != n->in(MemNode::Memory)) { set_map(n->_idx, mem); + _nodes->adr_at(n->_idx)->_node = n; + } if (n->is_Load()) { continue; // don't push users } else if (n->is_LoadStore()) { @@ -712,29 +1013,33 @@ void ConnectionGraph::split_unique_types(GrowableArray &alloc_worklist) for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) { Node *use = n->fast_out(i); if (use->is_Phi()) { - memnode_worklist.push(use); + memnode_worklist.append_if_missing(use); } else if(use->is_Mem() && use->in(MemNode::Memory) == n) { - memnode_worklist.push(use); + memnode_worklist.append_if_missing(use); + } else if (use->is_Initialize()) { + memnode_worklist.append_if_missing(use); } else if (use->is_MergeMem()) { - mergemem_worklist.push(use); + mergemem_worklist.append_if_missing(use); } } } - // Phase 3: Process MergeMem nodes from mergemem_worklist. Walk each memory slice - // moving the first node encountered of each instance type to the - // the input corresponding to its alias index. + // Phase 3: Process MergeMem nodes from mergemem_worklist. + // Walk each memory moving the first node encountered of each + // instance type to the the input corresponding to its alias index. while (mergemem_worklist.length() != 0) { Node *n = mergemem_worklist.pop(); assert(n->is_MergeMem(), "MergeMem node required."); + if (visited.test_set(n->_idx)) + continue; MergeMemNode *nmm = n->as_MergeMem(); // Note: we don't want to use MergeMemStream here because we only want to - // scan inputs which exist at the start, not ones we add during processing + // scan inputs which exist at the start, not ones we add during processing. uint nslices = nmm->req(); igvn->hash_delete(nmm); for (uint i = Compile::AliasIdxRaw+1; i < nslices; i++) { - Node * mem = nmm->in(i); - Node * cur = NULL; + Node* mem = nmm->in(i); + Node* cur = NULL; if (mem == NULL || mem->is_top()) continue; while (mem->is_Mem()) { @@ -754,30 +1059,76 @@ void ConnectionGraph::split_unique_types(GrowableArray &alloc_worklist) mem = mem->in(MemNode::Memory); } nmm->set_memory_at(i, (cur != NULL) ? cur : mem); - if (mem->is_Phi()) { - // We have encountered a Phi, we need to split the Phi for - // any instance of the current type if we haven't encountered - // a value of the instance along the chain. - for (uint ni = new_index_start; ni < new_index_end; ni++) { - if((uint)_compile->get_general_index(ni) == i) { - Node *m = (ni >= nmm->req()) ? nmm->empty_memory() : nmm->in(ni); - if (nmm->is_empty_memory(m)) { - m = split_memory_phi(mem->as_Phi(), ni, orig_phis, igvn); - if (_compile->failing()) { - return; - } - nmm->set_memory_at(ni, m); + // Find any instance of the current type if we haven't encountered + // a value of the instance along the chain. + for (uint ni = new_index_start; ni < new_index_end; ni++) { + if((uint)_compile->get_general_index(ni) == i) { + Node *m = (ni >= nmm->req()) ? nmm->empty_memory() : nmm->in(ni); + if (nmm->is_empty_memory(m)) { + Node* result = find_inst_mem(mem, ni, orig_phis, igvn); + if (_compile->failing()) { + return; + } + nmm->set_memory_at(ni, result); + } + } + } + } + // Find the rest of instances values + for (uint ni = new_index_start; ni < new_index_end; ni++) { + const TypeOopPtr *tinst = igvn->C->get_adr_type(ni)->isa_oopptr(); + Node* result = step_through_mergemem(nmm, ni, tinst); + if (result == nmm->base_memory()) { + // Didn't find instance memory, search through general slice recursively. + result = nmm->memory_at(igvn->C->get_general_index(ni)); + result = find_inst_mem(result, ni, orig_phis, igvn); + if (_compile->failing()) { + return; + } + nmm->set_memory_at(ni, result); + } + } + igvn->hash_insert(nmm); + record_for_optimizer(nmm); + + // Propagate new memory slices to following MergeMem nodes. + for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) { + Node *use = n->fast_out(i); + if (use->is_Call()) { + CallNode* in = use->as_Call(); + if (in->proj_out(TypeFunc::Memory) != NULL) { + Node* m = in->proj_out(TypeFunc::Memory); + for (DUIterator_Fast jmax, j = m->fast_outs(jmax); j < jmax; j++) { + Node* mm = m->fast_out(j); + if (mm->is_MergeMem()) { + mergemem_worklist.append_if_missing(mm); + } + } + } + if (use->is_Allocate()) { + use = use->as_Allocate()->initialization(); + if (use == NULL) { + continue; + } + } + } + if (use->is_Initialize()) { + InitializeNode* in = use->as_Initialize(); + if (in->proj_out(TypeFunc::Memory) != NULL) { + Node* m = in->proj_out(TypeFunc::Memory); + for (DUIterator_Fast jmax, j = m->fast_outs(jmax); j < jmax; j++) { + Node* mm = m->fast_out(j); + if (mm->is_MergeMem()) { + mergemem_worklist.append_if_missing(mm); } } } } } - igvn->hash_insert(nmm); - record_for_optimizer(nmm); } - // Phase 4: Update the inputs of non-instance memory Phis and the Memory input of memnodes - // + // Phase 4: Update the inputs of non-instance memory Phis and + // the Memory input of memnodes // First update the inputs of any non-instance Phi's from // which we split out an instance Phi. Note we don't have // to recursively process Phi's encounted on the input memory @@ -789,7 +1140,10 @@ void ConnectionGraph::split_unique_types(GrowableArray &alloc_worklist) igvn->hash_delete(phi); for (uint i = 1; i < phi->req(); i++) { Node *mem = phi->in(i); - Node *new_mem = find_mem(mem, alias_idx, igvn); + Node *new_mem = find_inst_mem(mem, alias_idx, orig_phis, igvn); + if (_compile->failing()) { + return; + } if (mem != new_mem) { phi->set_req(i, new_mem); } @@ -803,7 +1157,7 @@ void ConnectionGraph::split_unique_types(GrowableArray &alloc_worklist) for (int i = 0; i < _nodes->length(); i++) { Node *nmem = get_map(i); if (nmem != NULL) { - Node *n = _nodes->at(i)._node; + Node *n = _nodes->adr_at(i)->_node; if (n != NULL && n->is_Mem()) { igvn->hash_delete(n); n->set_req(MemNode::Memory, nmem); @@ -815,59 +1169,110 @@ void ConnectionGraph::split_unique_types(GrowableArray &alloc_worklist) } void ConnectionGraph::compute_escape() { - GrowableArray worklist; - GrowableArray alloc_worklist; - VectorSet visited(Thread::current()->resource_area()); - PhaseGVN *igvn = _compile->initial_gvn(); - // process Phi nodes from the deferred list, they may not have - while(_deferred.size() > 0) { - Node * n = _deferred.pop(); - PhiNode * phi = n->as_Phi(); + // 1. Populate Connection Graph with Ideal nodes. - process_phi_escape(phi, igvn); + Unique_Node_List worklist_init; + worklist_init.map(_compile->unique(), NULL); // preallocate space + + // Initialize worklist + if (_compile->root() != NULL) { + worklist_init.push(_compile->root()); + } + + GrowableArray cg_worklist; + PhaseGVN* igvn = _compile->initial_gvn(); + bool has_allocations = false; + + // Push all useful nodes onto CG list and set their type. + for( uint next = 0; next < worklist_init.size(); ++next ) { + Node* n = worklist_init.at(next); + record_for_escape_analysis(n, igvn); + if (n->is_Call() && + _nodes->adr_at(n->_idx)->node_type() == PointsToNode::JavaObject) { + has_allocations = true; + } + if(n->is_AddP()) + cg_worklist.append(n->_idx); + for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) { + Node* m = n->fast_out(i); // Get user + worklist_init.push(m); + } + } + + if (has_allocations) { + _has_allocations = true; + } else { + _has_allocations = false; + _collecting = false; + return; // Nothing to do. + } + + // 2. First pass to create simple CG edges (doesn't require to walk CG). + for( uint next = 0; next < _delayed_worklist.size(); ++next ) { + Node* n = _delayed_worklist.at(next); + build_connection_graph(n, igvn); + } + + // 3. Pass to create fields edges (Allocate -F-> AddP). + for( int next = 0; next < cg_worklist.length(); ++next ) { + int ni = cg_worklist.at(next); + build_connection_graph(_nodes->adr_at(ni)->_node, igvn); + } + + cg_worklist.clear(); + cg_worklist.append(_phantom_object); + + // 4. Build Connection Graph which need + // to walk the connection graph. + for (uint ni = 0; ni < (uint)_nodes->length(); ni++) { + PointsToNode* ptn = _nodes->adr_at(ni); + Node *n = ptn->_node; + if (n != NULL) { // Call, AddP, LoadP, StoreP + build_connection_graph(n, igvn); + if (ptn->node_type() != PointsToNode::UnknownType) + cg_worklist.append(n->_idx); // Collect CG nodes + } } VectorSet ptset(Thread::current()->resource_area()); + GrowableArray alloc_worklist; + GrowableArray worklist; // remove deferred edges from the graph and collect // information we will need for type splitting - for (uint ni = 0; ni < (uint)_nodes->length(); ni++) { - PointsToNode * ptn = _nodes->adr_at(ni); + for( int next = 0; next < cg_worklist.length(); ++next ) { + int ni = cg_worklist.at(next); + PointsToNode* ptn = _nodes->adr_at(ni); PointsToNode::NodeType nt = ptn->node_type(); - - if (nt == PointsToNode::UnknownType) { - continue; // not a node we are interested in - } Node *n = ptn->_node; if (nt == PointsToNode::LocalVar || nt == PointsToNode::Field) { remove_deferred(ni); if (n->is_AddP()) { - // if this AddP computes an address which may point to more that one - // object, nothing the address points to can be a unique type. - Node *base = n->in(AddPNode::Base); + // If this AddP computes an address which may point to more that one + // object, nothing the address points to can be scalar replaceable. + Node *base = get_addp_base(n); ptset.Clear(); PointsTo(ptset, base, igvn); if (ptset.Size() > 1) { for( VectorSetI j(&ptset); j.test(); ++j ) { - PointsToNode *ptaddr = _nodes->adr_at(j.elem); - ptaddr->_unique_type = false; + uint pt = j.elem; + ptnode_adr(pt)->_scalar_replaceable = false; } } } - } else if (n->is_Call()) { - // initialize _escape_state of calls to GlobalEscape - n->as_Call()->_escape_state = PointsToNode::GlobalEscape; - // push call on alloc_worlist (alocations are calls) - // for processing by split_unique_types() - alloc_worklist.push(n); + } else if (nt == PointsToNode::JavaObject && n->is_Call()) { + // Push call on alloc_worlist (alocations are calls) + // for processing by split_unique_types(). + alloc_worklist.append(n); } } + // push all GlobalEscape nodes on the worklist - for (uint nj = 0; nj < (uint)_nodes->length(); nj++) { - if (_nodes->at(nj).escape_state() == PointsToNode::GlobalEscape) { - worklist.append(nj); - } + for( int next = 0; next < cg_worklist.length(); ++next ) { + int nk = cg_worklist.at(next); + if (_nodes->adr_at(nk)->escape_state() == PointsToNode::GlobalEscape) + worklist.append(nk); } // mark all node reachable from GlobalEscape nodes while(worklist.length() > 0) { @@ -875,7 +1280,7 @@ void ConnectionGraph::compute_escape() { for (uint ei = 0; ei < n.edge_count(); ei++) { uint npi = n.edge_target(ei); PointsToNode *np = ptnode_adr(npi); - if (np->escape_state() != PointsToNode::GlobalEscape) { + if (np->escape_state() < PointsToNode::GlobalEscape) { np->set_escape_state(PointsToNode::GlobalEscape); worklist.append_if_missing(npi); } @@ -883,133 +1288,191 @@ void ConnectionGraph::compute_escape() { } // push all ArgEscape nodes on the worklist - for (uint nk = 0; nk < (uint)_nodes->length(); nk++) { - if (_nodes->at(nk).escape_state() == PointsToNode::ArgEscape) + for( int next = 0; next < cg_worklist.length(); ++next ) { + int nk = cg_worklist.at(next); + if (_nodes->adr_at(nk)->escape_state() == PointsToNode::ArgEscape) worklist.push(nk); } // mark all node reachable from ArgEscape nodes while(worklist.length() > 0) { PointsToNode n = _nodes->at(worklist.pop()); - for (uint ei = 0; ei < n.edge_count(); ei++) { uint npi = n.edge_target(ei); PointsToNode *np = ptnode_adr(npi); - if (np->escape_state() != PointsToNode::ArgEscape) { + if (np->escape_state() < PointsToNode::ArgEscape) { np->set_escape_state(PointsToNode::ArgEscape); worklist.append_if_missing(npi); } } } + + // push all NoEscape nodes on the worklist + for( int next = 0; next < cg_worklist.length(); ++next ) { + int nk = cg_worklist.at(next); + if (_nodes->adr_at(nk)->escape_state() == PointsToNode::NoEscape) + worklist.push(nk); + } + // mark all node reachable from NoEscape nodes + while(worklist.length() > 0) { + PointsToNode n = _nodes->at(worklist.pop()); + for (uint ei = 0; ei < n.edge_count(); ei++) { + uint npi = n.edge_target(ei); + PointsToNode *np = ptnode_adr(npi); + if (np->escape_state() < PointsToNode::NoEscape) { + np->set_escape_state(PointsToNode::NoEscape); + worklist.append_if_missing(npi); + } + } + } + _collecting = false; - // Now use the escape information to create unique types for - // unescaped objects - split_unique_types(alloc_worklist); - if (_compile->failing()) return; + has_allocations = false; // Are there scalar replaceable allocations? - // Clean up after split unique types. - ResourceMark rm; - PhaseRemoveUseless pru(_compile->initial_gvn(), _compile->for_igvn()); -} - -Node * ConnectionGraph::skip_casts(Node *n) { - while(n->Opcode() == Op_CastPP || n->Opcode() == Op_CheckCastPP) { - n = n->in(1); - } - return n; -} - -void ConnectionGraph::process_phi_escape(PhiNode *phi, PhaseTransform *phase) { - - if (phi->type()->isa_oopptr() == NULL) - return; // nothing to do if not an oop - - PointsToNode *ptadr = ptnode_adr(phi->_idx); - int incount = phi->req(); - int non_null_inputs = 0; - - for (int i = 1; i < incount ; i++) { - if (phi->in(i) != NULL) - non_null_inputs++; - } - if (non_null_inputs == ptadr->_inputs_processed) - return; // no new inputs since the last time this node was processed, - // the current information is valid - - ptadr->_inputs_processed = non_null_inputs; // prevent recursive processing of this node - for (int j = 1; j < incount ; j++) { - Node * n = phi->in(j); - if (n == NULL) - continue; // ignore NULL - n = skip_casts(n); - if (n->is_top() || n == phi) - continue; // ignore top or inputs which go back this node - int nopc = n->Opcode(); - PointsToNode npt = _nodes->at(n->_idx); - if (_nodes->at(n->_idx).node_type() == PointsToNode::JavaObject) { - add_pointsto_edge(phi->_idx, n->_idx); - } else { - add_deferred_edge(phi->_idx, n->_idx); + for( int next = 0; next < alloc_worklist.length(); ++next ) { + Node* n = alloc_worklist.at(next); + uint ni = n->_idx; + PointsToNode* ptn = _nodes->adr_at(ni); + PointsToNode::EscapeState es = ptn->escape_state(); + if (ptn->escape_state() == PointsToNode::NoEscape && + ptn->_scalar_replaceable) { + has_allocations = true; + break; } } + if (!has_allocations) { + return; // Nothing to do. + } + + if(_compile->AliasLevel() >= 3 && EliminateAllocations) { + // Now use the escape information to create unique types for + // unescaped objects + split_unique_types(alloc_worklist); + if (_compile->failing()) return; + + // Clean up after split unique types. + ResourceMark rm; + PhaseRemoveUseless pru(_compile->initial_gvn(), _compile->for_igvn()); + +#ifdef ASSERT + } else if (PrintEscapeAnalysis || PrintEliminateAllocations) { + tty->print("=== No allocations eliminated for "); + C()->method()->print_short_name(); + if(!EliminateAllocations) { + tty->print(" since EliminateAllocations is off ==="); + } else if(_compile->AliasLevel() < 3) { + tty->print(" since AliasLevel < 3 ==="); + } + tty->cr(); +#endif + } } void ConnectionGraph::process_call_arguments(CallNode *call, PhaseTransform *phase) { - _processed.set(call->_idx); switch (call->Opcode()) { - - // arguments to allocation and locking don't escape +#ifdef ASSERT case Op_Allocate: case Op_AllocateArray: case Op_Lock: case Op_Unlock: + assert(false, "should be done already"); break; +#endif + case Op_CallLeafNoFP: + { + // Stub calls, objects do not escape but they are not scale replaceable. + // Adjust escape state for outgoing arguments. + const TypeTuple * d = call->tf()->domain(); + VectorSet ptset(Thread::current()->resource_area()); + for (uint i = TypeFunc::Parms; i < d->cnt(); i++) { + const Type* at = d->field_at(i); + Node *arg = call->in(i)->uncast(); + const Type *aat = phase->type(arg); + if (!arg->is_top() && at->isa_ptr() && aat->isa_ptr()) { + assert(aat == Type::TOP || aat == TypePtr::NULL_PTR || + aat->isa_ptr() != NULL, "expecting an Ptr"); + set_escape_state(arg->_idx, PointsToNode::ArgEscape); + if (arg->is_AddP()) { + // + // The inline_native_clone() case when the arraycopy stub is called + // after the allocation before Initialize and CheckCastPP nodes. + // + // Set AddP's base (Allocate) as not scalar replaceable since + // pointer to the base (with offset) is passed as argument. + // + arg = get_addp_base(arg); + } + ptset.Clear(); + PointsTo(ptset, arg, phase); + for( VectorSetI j(&ptset); j.test(); ++j ) { + uint pt = j.elem; + set_escape_state(pt, PointsToNode::ArgEscape); + } + } + } + break; + } case Op_CallStaticJava: // For a static call, we know exactly what method is being called. // Use bytecode estimator to record the call's escape affects { ciMethod *meth = call->as_CallJava()->method(); - if (meth != NULL) { + BCEscapeAnalyzer *call_analyzer = (meth !=NULL) ? meth->get_bcea() : NULL; + // fall-through if not a Java method or no analyzer information + if (call_analyzer != NULL) { const TypeTuple * d = call->tf()->domain(); - BCEscapeAnalyzer call_analyzer(meth); VectorSet ptset(Thread::current()->resource_area()); + bool copy_dependencies = false; for (uint i = TypeFunc::Parms; i < d->cnt(); i++) { const Type* at = d->field_at(i); int k = i - TypeFunc::Parms; if (at->isa_oopptr() != NULL) { - Node *arg = skip_casts(call->in(i)); + Node *arg = call->in(i)->uncast(); - if (!call_analyzer.is_arg_stack(k)) { + bool global_escapes = false; + bool fields_escapes = false; + if (!call_analyzer->is_arg_stack(k)) { // The argument global escapes, mark everything it could point to - ptset.Clear(); - PointsTo(ptset, arg, phase); - for( VectorSetI j(&ptset); j.test(); ++j ) { - uint pt = j.elem; - - set_escape_state(pt, PointsToNode::GlobalEscape); + set_escape_state(arg->_idx, PointsToNode::GlobalEscape); + global_escapes = true; + } else { + if (!call_analyzer->is_arg_local(k)) { + // The argument itself doesn't escape, but any fields might + fields_escapes = true; } - } else if (!call_analyzer.is_arg_local(k)) { - // The argument itself doesn't escape, but any fields might - ptset.Clear(); - PointsTo(ptset, arg, phase); - for( VectorSetI j(&ptset); j.test(); ++j ) { - uint pt = j.elem; - add_edge_from_fields(pt, _phantom_object, Type::OffsetBot); + set_escape_state(arg->_idx, PointsToNode::ArgEscape); + copy_dependencies = true; + } + + ptset.Clear(); + PointsTo(ptset, arg, phase); + for( VectorSetI j(&ptset); j.test(); ++j ) { + uint pt = j.elem; + if (global_escapes) { + //The argument global escapes, mark everything it could point to + set_escape_state(pt, PointsToNode::GlobalEscape); + } else { + if (fields_escapes) { + // The argument itself doesn't escape, but any fields might + add_edge_from_fields(pt, _phantom_object, Type::OffsetBot); + } + set_escape_state(pt, PointsToNode::ArgEscape); } } } } - call_analyzer.copy_dependencies(C()->dependencies()); + if (copy_dependencies) + call_analyzer->copy_dependencies(C()->dependencies()); break; } - // fall-through if not a Java method } default: - // Some other type of call, assume the worst case: all arguments + // Fall-through here if not a Java method or no analyzer information + // or some other type of call, assume the worst case: all arguments // globally escape. { // adjust escape state for outgoing arguments @@ -1017,15 +1480,15 @@ void ConnectionGraph::process_call_arguments(CallNode *call, PhaseTransform *pha VectorSet ptset(Thread::current()->resource_area()); for (uint i = TypeFunc::Parms; i < d->cnt(); i++) { const Type* at = d->field_at(i); - if (at->isa_oopptr() != NULL) { - Node *arg = skip_casts(call->in(i)); + Node *arg = call->in(i)->uncast(); + set_escape_state(arg->_idx, PointsToNode::GlobalEscape); ptset.Clear(); PointsTo(ptset, arg, phase); for( VectorSetI j(&ptset); j.test(); ++j ) { uint pt = j.elem; - set_escape_state(pt, PointsToNode::GlobalEscape); + PointsToNode *ptadr = ptnode_adr(pt); } } } @@ -1033,15 +1496,9 @@ void ConnectionGraph::process_call_arguments(CallNode *call, PhaseTransform *pha } } void ConnectionGraph::process_call_result(ProjNode *resproj, PhaseTransform *phase) { - CallNode *call = resproj->in(0)->as_Call(); - PointsToNode *ptadr = ptnode_adr(resproj->_idx); - ptadr->_node = resproj; - ptadr->set_node_type(PointsToNode::LocalVar); - set_escape_state(resproj->_idx, PointsToNode::UnknownEscape); - _processed.set(resproj->_idx); - + CallNode *call = resproj->in(0)->as_Call(); switch (call->Opcode()) { case Op_Allocate: { @@ -1057,36 +1514,40 @@ void ConnectionGraph::process_call_result(ProjNode *resproj, PhaseTransform *pha ciInstanceKlass* ciik = cik->as_instance_klass(); PointsToNode *ptadr = ptnode_adr(call->_idx); - ptadr->set_node_type(PointsToNode::JavaObject); + PointsToNode::EscapeState es; + uint edge_to; if (cik->is_subclass_of(_compile->env()->Thread_klass()) || ciik->has_finalizer()) { - set_escape_state(call->_idx, PointsToNode::GlobalEscape); - add_pointsto_edge(resproj->_idx, _phantom_object); + es = PointsToNode::GlobalEscape; + edge_to = _phantom_object; // Could not be worse } else { - set_escape_state(call->_idx, PointsToNode::NoEscape); - add_pointsto_edge(resproj->_idx, call->_idx); + es = PointsToNode::NoEscape; + edge_to = call->_idx; } - _processed.set(call->_idx); + set_escape_state(call->_idx, es); + add_pointsto_edge(resproj->_idx, edge_to); + _processed.set(resproj->_idx); break; } case Op_AllocateArray: { PointsToNode *ptadr = ptnode_adr(call->_idx); - ptadr->set_node_type(PointsToNode::JavaObject); + int length = call->in(AllocateNode::ALength)->find_int_con(-1); + if (length < 0 || length > EliminateAllocationArraySizeLimit) { + // Not scalar replaceable if the length is not constant or too big. + ptadr->_scalar_replaceable = false; + } set_escape_state(call->_idx, PointsToNode::NoEscape); - _processed.set(call->_idx); add_pointsto_edge(resproj->_idx, call->_idx); + _processed.set(resproj->_idx); break; } - case Op_Lock: - case Op_Unlock: - break; - case Op_CallStaticJava: // For a static call, we know exactly what method is being called. // Use bytecode estimator to record whether the call's return value escapes { + bool done = true; const TypeTuple *r = call->tf()->range(); const Type* ret_type = NULL; @@ -1095,32 +1556,45 @@ void ConnectionGraph::process_call_result(ProjNode *resproj, PhaseTransform *pha // Note: we use isa_ptr() instead of isa_oopptr() here because the // _multianewarray functions return a TypeRawPtr. - if (ret_type == NULL || ret_type->isa_ptr() == NULL) + if (ret_type == NULL || ret_type->isa_ptr() == NULL) { + _processed.set(resproj->_idx); break; // doesn't return a pointer type - + } ciMethod *meth = call->as_CallJava()->method(); + const TypeTuple * d = call->tf()->domain(); if (meth == NULL) { // not a Java method, assume global escape set_escape_state(call->_idx, PointsToNode::GlobalEscape); if (resproj != NULL) add_pointsto_edge(resproj->_idx, _phantom_object); } else { - BCEscapeAnalyzer call_analyzer(meth); + BCEscapeAnalyzer *call_analyzer = meth->get_bcea(); VectorSet ptset(Thread::current()->resource_area()); + bool copy_dependencies = false; - if (call_analyzer.is_return_local() && resproj != NULL) { + if (call_analyzer->is_return_allocated()) { + // Returns a newly allocated unescaped object, simply + // update dependency information. + // Mark it as NoEscape so that objects referenced by + // it's fields will be marked as NoEscape at least. + set_escape_state(call->_idx, PointsToNode::NoEscape); + if (resproj != NULL) + add_pointsto_edge(resproj->_idx, call->_idx); + copy_dependencies = true; + } else if (call_analyzer->is_return_local() && resproj != NULL) { // determine whether any arguments are returned - const TypeTuple * d = call->tf()->domain(); set_escape_state(call->_idx, PointsToNode::NoEscape); for (uint i = TypeFunc::Parms; i < d->cnt(); i++) { const Type* at = d->field_at(i); if (at->isa_oopptr() != NULL) { - Node *arg = skip_casts(call->in(i)); + Node *arg = call->in(i)->uncast(); - if (call_analyzer.is_arg_returned(i - TypeFunc::Parms)) { + if (call_analyzer->is_arg_returned(i - TypeFunc::Parms)) { PointsToNode *arg_esp = _nodes->adr_at(arg->_idx); - if (arg_esp->node_type() == PointsToNode::JavaObject) + if (arg_esp->node_type() == PointsToNode::UnknownType) + done = false; + else if (arg_esp->node_type() == PointsToNode::JavaObject) add_pointsto_edge(resproj->_idx, arg->_idx); else add_deferred_edge(resproj->_idx, arg->_idx); @@ -1128,13 +1602,25 @@ void ConnectionGraph::process_call_result(ProjNode *resproj, PhaseTransform *pha } } } + copy_dependencies = true; } else { set_escape_state(call->_idx, PointsToNode::GlobalEscape); if (resproj != NULL) add_pointsto_edge(resproj->_idx, _phantom_object); + for (uint i = TypeFunc::Parms; i < d->cnt(); i++) { + const Type* at = d->field_at(i); + if (at->isa_oopptr() != NULL) { + Node *arg = call->in(i)->uncast(); + PointsToNode *arg_esp = _nodes->adr_at(arg->_idx); + arg_esp->_hidden_alias = true; + } + } } - call_analyzer.copy_dependencies(C()->dependencies()); + if (copy_dependencies) + call_analyzer->copy_dependencies(C()->dependencies()); } + if (done) + _processed.set(resproj->_idx); break; } @@ -1143,7 +1629,6 @@ void ConnectionGraph::process_call_result(ProjNode *resproj, PhaseTransform *pha // returned value, if any, globally escapes. { const TypeTuple *r = call->tf()->range(); - if (r->cnt() > TypeFunc::Parms) { const Type* ret_type = r->field_at(TypeFunc::Parms); @@ -1151,188 +1636,414 @@ void ConnectionGraph::process_call_result(ProjNode *resproj, PhaseTransform *pha // _multianewarray functions return a TypeRawPtr. if (ret_type->isa_ptr() != NULL) { PointsToNode *ptadr = ptnode_adr(call->_idx); - ptadr->set_node_type(PointsToNode::JavaObject); set_escape_state(call->_idx, PointsToNode::GlobalEscape); if (resproj != NULL) add_pointsto_edge(resproj->_idx, _phantom_object); } } + _processed.set(resproj->_idx); } } } -void ConnectionGraph::record_for_escape_analysis(Node *n) { - if (_collecting) { - if (n->is_Phi()) { - PhiNode *phi = n->as_Phi(); - const Type *pt = phi->type(); - if ((pt->isa_oopptr() != NULL) || pt == TypePtr::NULL_PTR) { - PointsToNode *ptn = ptnode_adr(phi->_idx); - ptn->set_node_type(PointsToNode::LocalVar); - ptn->_node = n; - _deferred.push(n); - } - } - } -} - -void ConnectionGraph::record_escape_work(Node *n, PhaseTransform *phase) { - - int opc = n->Opcode(); - PointsToNode *ptadr = ptnode_adr(n->_idx); - +// Populate Connection Graph with Ideal nodes and create simple +// connection graph edges (do not need to check the node_type of inputs +// or to call PointsTo() to walk the connection graph). +void ConnectionGraph::record_for_escape_analysis(Node *n, PhaseTransform *phase) { if (_processed.test(n->_idx)) - return; + return; // No need to redefine node's state. - ptadr->_node = n; if (n->is_Call()) { - CallNode *call = n->as_Call(); - process_call_arguments(call, phase); + // Arguments to allocation and locking don't escape. + if (n->is_Allocate()) { + add_node(n, PointsToNode::JavaObject, PointsToNode::UnknownEscape, true); + record_for_optimizer(n); + } else if (n->is_Lock() || n->is_Unlock()) { + // Put Lock and Unlock nodes on IGVN worklist to process them during + // the first IGVN optimization when escape information is still available. + record_for_optimizer(n); + _processed.set(n->_idx); + } else { + // Have to process call's arguments first. + PointsToNode::NodeType nt = PointsToNode::UnknownType; + + // Check if a call returns an object. + const TypeTuple *r = n->as_Call()->tf()->range(); + if (r->cnt() > TypeFunc::Parms && + n->as_Call()->proj_out(TypeFunc::Parms) != NULL) { + // Note: use isa_ptr() instead of isa_oopptr() here because + // the _multianewarray functions return a TypeRawPtr. + if (r->field_at(TypeFunc::Parms)->isa_ptr() != NULL) { + nt = PointsToNode::JavaObject; + } + } + add_node(n, nt, PointsToNode::UnknownEscape, false); + } return; } - switch (opc) { + // Using isa_ptr() instead of isa_oopptr() for LoadP and Phi because + // ThreadLocal has RawPrt type. + switch (n->Opcode()) { case Op_AddP: { - Node *base = skip_casts(n->in(AddPNode::Base)); - ptadr->set_node_type(PointsToNode::Field); - - // create a field edge to this node from everything adr could point to - VectorSet ptset(Thread::current()->resource_area()); - PointsTo(ptset, base, phase); - for( VectorSetI i(&ptset); i.test(); ++i ) { - uint pt = i.elem; - add_field_edge(pt, n->_idx, type_to_offset(phase->type(n))); - } + add_node(n, PointsToNode::Field, PointsToNode::UnknownEscape, false); break; } - case Op_Parm: + case Op_CastX2P: + { // "Unsafe" memory access. + add_node(n, PointsToNode::JavaObject, PointsToNode::GlobalEscape, true); + break; + } + case Op_CastPP: + case Op_CheckCastPP: { - ProjNode *nproj = n->as_Proj(); - uint con = nproj->_con; - if (con < TypeFunc::Parms) - return; - const Type *t = nproj->in(0)->as_Start()->_domain->field_at(con); - if (t->isa_ptr() == NULL) - return; - ptadr->set_node_type(PointsToNode::JavaObject); - if (t->isa_oopptr() != NULL) { - set_escape_state(n->_idx, PointsToNode::ArgEscape); + add_node(n, PointsToNode::LocalVar, PointsToNode::UnknownEscape, false); + int ti = n->in(1)->_idx; + PointsToNode::NodeType nt = _nodes->adr_at(ti)->node_type(); + if (nt == PointsToNode::UnknownType) { + _delayed_worklist.push(n); // Process it later. + break; + } else if (nt == PointsToNode::JavaObject) { + add_pointsto_edge(n->_idx, ti); } else { - // this must be the incoming state of an OSR compile, we have to assume anything - // passed in globally escapes - assert(_compile->is_osr_compilation(), "bad argument type for non-osr compilation"); - set_escape_state(n->_idx, PointsToNode::GlobalEscape); + add_deferred_edge(n->_idx, ti); } _processed.set(n->_idx); break; } - case Op_Phi: - { - PhiNode *phi = n->as_Phi(); - if (phi->type()->isa_oopptr() == NULL) - return; // nothing to do if not an oop - ptadr->set_node_type(PointsToNode::LocalVar); - process_phi_escape(phi, phase); - break; - } - case Op_CreateEx: - { - // assume that all exception objects globally escape - ptadr->set_node_type(PointsToNode::JavaObject); - set_escape_state(n->_idx, PointsToNode::GlobalEscape); - _processed.set(n->_idx); - break; - } case Op_ConP: { - const Type *t = phase->type(n); - ptadr->set_node_type(PointsToNode::JavaObject); // assume all pointer constants globally escape except for null - if (t == TypePtr::NULL_PTR) - set_escape_state(n->_idx, PointsToNode::NoEscape); + PointsToNode::EscapeState es; + if (phase->type(n) == TypePtr::NULL_PTR) + es = PointsToNode::NoEscape; else - set_escape_state(n->_idx, PointsToNode::GlobalEscape); - _processed.set(n->_idx); + es = PointsToNode::GlobalEscape; + + add_node(n, PointsToNode::JavaObject, es, true); + break; + } + case Op_CreateEx: + { + // assume that all exception objects globally escape + add_node(n, PointsToNode::JavaObject, PointsToNode::GlobalEscape, true); break; } case Op_LoadKlass: { - ptadr->set_node_type(PointsToNode::JavaObject); - set_escape_state(n->_idx, PointsToNode::GlobalEscape); - _processed.set(n->_idx); + add_node(n, PointsToNode::JavaObject, PointsToNode::GlobalEscape, true); break; } case Op_LoadP: { const Type *t = phase->type(n); - if (!t->isa_oopptr()) + if (t->isa_ptr() == NULL) { + _processed.set(n->_idx); return; - ptadr->set_node_type(PointsToNode::LocalVar); - set_escape_state(n->_idx, PointsToNode::UnknownEscape); + } + add_node(n, PointsToNode::LocalVar, PointsToNode::UnknownEscape, false); + break; + } + case Op_Parm: + { + _processed.set(n->_idx); // No need to redefine it state. + uint con = n->as_Proj()->_con; + if (con < TypeFunc::Parms) + return; + const Type *t = n->in(0)->as_Start()->_domain->field_at(con); + if (t->isa_ptr() == NULL) + return; + // We have to assume all input parameters globally escape + // (Note: passing 'false' since _processed is already set). + add_node(n, PointsToNode::JavaObject, PointsToNode::GlobalEscape, false); + break; + } + case Op_Phi: + { + if (n->as_Phi()->type()->isa_ptr() == NULL) { + // nothing to do if not an oop + _processed.set(n->_idx); + return; + } + add_node(n, PointsToNode::LocalVar, PointsToNode::UnknownEscape, false); + uint i; + for (i = 1; i < n->req() ; i++) { + Node* in = n->in(i); + if (in == NULL) + continue; // ignore NULL + in = in->uncast(); + if (in->is_top() || in == n) + continue; // ignore top or inputs which go back this node + int ti = in->_idx; + PointsToNode::NodeType nt = _nodes->adr_at(ti)->node_type(); + if (nt == PointsToNode::UnknownType) { + break; + } else if (nt == PointsToNode::JavaObject) { + add_pointsto_edge(n->_idx, ti); + } else { + add_deferred_edge(n->_idx, ti); + } + } + if (i >= n->req()) + _processed.set(n->_idx); + else + _delayed_worklist.push(n); + break; + } + case Op_Proj: + { + // we are only interested in the result projection from a call + if (n->as_Proj()->_con == TypeFunc::Parms && n->in(0)->is_Call() ) { + add_node(n, PointsToNode::LocalVar, PointsToNode::UnknownEscape, false); + process_call_result(n->as_Proj(), phase); + if (!_processed.test(n->_idx)) { + // The call's result may need to be processed later if the call + // returns it's argument and the argument is not processed yet. + _delayed_worklist.push(n); + } + } else { + _processed.set(n->_idx); + } + break; + } + case Op_Return: + { + if( n->req() > TypeFunc::Parms && + phase->type(n->in(TypeFunc::Parms))->isa_oopptr() ) { + // Treat Return value as LocalVar with GlobalEscape escape state. + add_node(n, PointsToNode::LocalVar, PointsToNode::GlobalEscape, false); + int ti = n->in(TypeFunc::Parms)->_idx; + PointsToNode::NodeType nt = _nodes->adr_at(ti)->node_type(); + if (nt == PointsToNode::UnknownType) { + _delayed_worklist.push(n); // Process it later. + break; + } else if (nt == PointsToNode::JavaObject) { + add_pointsto_edge(n->_idx, ti); + } else { + add_deferred_edge(n->_idx, ti); + } + } + _processed.set(n->_idx); + break; + } + case Op_StoreP: + { + const Type *adr_type = phase->type(n->in(MemNode::Address)); + if (adr_type->isa_oopptr()) { + add_node(n, PointsToNode::UnknownType, PointsToNode::UnknownEscape, false); + } else { + Node* adr = n->in(MemNode::Address); + if (adr->is_AddP() && phase->type(adr) == TypeRawPtr::NOTNULL && + adr->in(AddPNode::Address)->is_Proj() && + adr->in(AddPNode::Address)->in(0)->is_Allocate()) { + add_node(n, PointsToNode::UnknownType, PointsToNode::UnknownEscape, false); + // We are computing a raw address for a store captured + // by an Initialize compute an appropriate address type. + int offs = (int)phase->find_intptr_t_con(adr->in(AddPNode::Offset), Type::OffsetBot); + assert(offs != Type::OffsetBot, "offset must be a constant"); + } else { + _processed.set(n->_idx); + return; + } + } + break; + } + case Op_StorePConditional: + case Op_CompareAndSwapP: + { + const Type *adr_type = phase->type(n->in(MemNode::Address)); + if (adr_type->isa_oopptr()) { + add_node(n, PointsToNode::UnknownType, PointsToNode::UnknownEscape, false); + } else { + _processed.set(n->_idx); + return; + } + break; + } + case Op_ThreadLocal: + { + add_node(n, PointsToNode::JavaObject, PointsToNode::ArgEscape, true); + break; + } + default: + ; + // nothing to do + } + return; +} - Node *adr = skip_casts(n->in(MemNode::Address)); - const Type *adr_type = phase->type(adr); - Node *adr_base = skip_casts((adr->Opcode() == Op_AddP) ? adr->in(AddPNode::Base) : adr); +void ConnectionGraph::build_connection_graph(Node *n, PhaseTransform *phase) { + // Don't set processed bit for AddP, LoadP, StoreP since + // they may need more then one pass to process. + if (_processed.test(n->_idx)) + return; // No need to redefine node's state. - // For everything "adr" could point to, create a deferred edge from - // this node to each field with the same offset as "adr_type" + PointsToNode *ptadr = ptnode_adr(n->_idx); + + if (n->is_Call()) { + CallNode *call = n->as_Call(); + process_call_arguments(call, phase); + _processed.set(n->_idx); + return; + } + + switch (n->Opcode()) { + case Op_AddP: + { + Node *base = get_addp_base(n); + // Create a field edge to this node from everything base could point to. VectorSet ptset(Thread::current()->resource_area()); - PointsTo(ptset, adr_base, phase); - // If ptset is empty, then this value must have been set outside - // this method, so we add the phantom node - if (ptset.Size() == 0) - ptset.set(_phantom_object); + PointsTo(ptset, base, phase); for( VectorSetI i(&ptset); i.test(); ++i ) { uint pt = i.elem; - add_deferred_edge_to_fields(n->_idx, pt, type_to_offset(adr_type)); + add_field_edge(pt, n->_idx, address_offset(n, phase)); } break; } + case Op_CastX2P: + { + assert(false, "Op_CastX2P"); + break; + } + case Op_CastPP: + case Op_CheckCastPP: + { + int ti = n->in(1)->_idx; + if (_nodes->adr_at(ti)->node_type() == PointsToNode::JavaObject) { + add_pointsto_edge(n->_idx, ti); + } else { + add_deferred_edge(n->_idx, ti); + } + _processed.set(n->_idx); + break; + } + case Op_ConP: + { + assert(false, "Op_ConP"); + break; + } + case Op_CreateEx: + { + assert(false, "Op_CreateEx"); + break; + } + case Op_LoadKlass: + { + assert(false, "Op_LoadKlass"); + break; + } + case Op_LoadP: + { + const Type *t = phase->type(n); +#ifdef ASSERT + if (t->isa_ptr() == NULL) + assert(false, "Op_LoadP"); +#endif + + Node* adr = n->in(MemNode::Address)->uncast(); + const Type *adr_type = phase->type(adr); + Node* adr_base; + if (adr->is_AddP()) { + adr_base = get_addp_base(adr); + } else { + adr_base = adr; + } + + // For everything "adr_base" could point to, create a deferred edge from + // this node to each field with the same offset. + VectorSet ptset(Thread::current()->resource_area()); + PointsTo(ptset, adr_base, phase); + int offset = address_offset(adr, phase); + for( VectorSetI i(&ptset); i.test(); ++i ) { + uint pt = i.elem; + add_deferred_edge_to_fields(n->_idx, pt, offset); + } + break; + } + case Op_Parm: + { + assert(false, "Op_Parm"); + break; + } + case Op_Phi: + { +#ifdef ASSERT + if (n->as_Phi()->type()->isa_ptr() == NULL) + assert(false, "Op_Phi"); +#endif + for (uint i = 1; i < n->req() ; i++) { + Node* in = n->in(i); + if (in == NULL) + continue; // ignore NULL + in = in->uncast(); + if (in->is_top() || in == n) + continue; // ignore top or inputs which go back this node + int ti = in->_idx; + if (_nodes->adr_at(in->_idx)->node_type() == PointsToNode::JavaObject) { + add_pointsto_edge(n->_idx, ti); + } else { + add_deferred_edge(n->_idx, ti); + } + } + _processed.set(n->_idx); + break; + } + case Op_Proj: + { + // we are only interested in the result projection from a call + if (n->as_Proj()->_con == TypeFunc::Parms && n->in(0)->is_Call() ) { + process_call_result(n->as_Proj(), phase); + assert(_processed.test(n->_idx), "all call results should be processed"); + } else { + assert(false, "Op_Proj"); + } + break; + } + case Op_Return: + { +#ifdef ASSERT + if( n->req() <= TypeFunc::Parms || + !phase->type(n->in(TypeFunc::Parms))->isa_oopptr() ) { + assert(false, "Op_Return"); + } +#endif + int ti = n->in(TypeFunc::Parms)->_idx; + if (_nodes->adr_at(ti)->node_type() == PointsToNode::JavaObject) { + add_pointsto_edge(n->_idx, ti); + } else { + add_deferred_edge(n->_idx, ti); + } + _processed.set(n->_idx); + break; + } case Op_StoreP: case Op_StorePConditional: case Op_CompareAndSwapP: { Node *adr = n->in(MemNode::Address); - Node *val = skip_casts(n->in(MemNode::ValueIn)); const Type *adr_type = phase->type(adr); +#ifdef ASSERT if (!adr_type->isa_oopptr()) - return; + assert(phase->type(adr) == TypeRawPtr::NOTNULL, "Op_StoreP"); +#endif - assert(adr->Opcode() == Op_AddP, "expecting an AddP"); - Node *adr_base = adr->in(AddPNode::Base); - - // For everything "adr_base" could point to, create a deferred edge to "val" from each field - // with the same offset as "adr_type" + assert(adr->is_AddP(), "expecting an AddP"); + Node *adr_base = get_addp_base(adr); + Node *val = n->in(MemNode::ValueIn)->uncast(); + // For everything "adr_base" could point to, create a deferred edge + // to "val" from each field with the same offset. VectorSet ptset(Thread::current()->resource_area()); PointsTo(ptset, adr_base, phase); for( VectorSetI i(&ptset); i.test(); ++i ) { uint pt = i.elem; - add_edge_from_fields(pt, val->_idx, type_to_offset(adr_type)); + add_edge_from_fields(pt, val->_idx, address_offset(adr, phase)); } break; } - case Op_Proj: + case Op_ThreadLocal: { - ProjNode *nproj = n->as_Proj(); - Node *n0 = nproj->in(0); - // we are only interested in the result projection from a call - if (nproj->_con == TypeFunc::Parms && n0->is_Call() ) { - process_call_result(nproj, phase); - } - - break; - } - case Op_CastPP: - case Op_CheckCastPP: - { - ptadr->set_node_type(PointsToNode::LocalVar); - int ti = n->in(1)->_idx; - if (_nodes->at(ti).node_type() == PointsToNode::JavaObject) { - add_pointsto_edge(n->_idx, ti); - } else { - add_deferred_edge(n->_idx, ti); - } + assert(false, "Op_ThreadLocal"); break; } default: @@ -1341,34 +2052,48 @@ void ConnectionGraph::record_escape_work(Node *n, PhaseTransform *phase) { } } -void ConnectionGraph::record_escape(Node *n, PhaseTransform *phase) { - if (_collecting) - record_escape_work(n, phase); -} - #ifndef PRODUCT void ConnectionGraph::dump() { PhaseGVN *igvn = _compile->initial_gvn(); bool first = true; - for (uint ni = 0; ni < (uint)_nodes->length(); ni++) { - PointsToNode *esp = _nodes->adr_at(ni); - if (esp->node_type() == PointsToNode::UnknownType || esp->_node == NULL) + uint size = (uint)_nodes->length(); + for (uint ni = 0; ni < size; ni++) { + PointsToNode *ptn = _nodes->adr_at(ni); + PointsToNode::NodeType ptn_type = ptn->node_type(); + + if (ptn_type != PointsToNode::JavaObject || ptn->_node == NULL) continue; - PointsToNode::EscapeState es = escape_state(esp->_node, igvn); - if (es == PointsToNode::NoEscape || (Verbose && - (es != PointsToNode::UnknownEscape || esp->edge_count() != 0))) { - // don't print null pointer node which almost every method has - if (esp->_node->Opcode() != Op_ConP || igvn->type(esp->_node) != TypePtr::NULL_PTR) { - if (first) { - tty->print("======== Connection graph for "); - C()->method()->print_short_name(); - tty->cr(); - first = false; - } - tty->print("%4d ", ni); - esp->dump(); + PointsToNode::EscapeState es = escape_state(ptn->_node, igvn); + if (ptn->_node->is_Allocate() && (es == PointsToNode::NoEscape || Verbose)) { + if (first) { + tty->cr(); + tty->print("======== Connection graph for "); + C()->method()->print_short_name(); + tty->cr(); + first = false; } + tty->print("%6d ", ni); + ptn->dump(); + // Print all locals which reference this allocation + for (uint li = ni; li < size; li++) { + PointsToNode *ptn_loc = _nodes->adr_at(li); + PointsToNode::NodeType ptn_loc_type = ptn_loc->node_type(); + if ( ptn_loc_type == PointsToNode::LocalVar && ptn_loc->_node != NULL && + ptn_loc->edge_count() == 1 && ptn_loc->edge_target(0) == ni ) { + tty->print("%6d LocalVar [[%d]]", li, ni); + _nodes->adr_at(li)->_node->dump(); + } + } + if (Verbose) { + // Print all fields which reference this allocation + for (uint i = 0; i < ptn->edge_count(); i++) { + uint ei = ptn->edge_target(i); + tty->print("%6d Field [[%d]]", ei, ni); + _nodes->adr_at(ei)->_node->dump(); + } + } + tty->cr(); } } } diff --git a/hotspot/src/share/vm/opto/escape.hpp b/hotspot/src/share/vm/opto/escape.hpp index 3cd879257e7..a7552b2c3ae 100644 --- a/hotspot/src/share/vm/opto/escape.hpp +++ b/hotspot/src/share/vm/opto/escape.hpp @@ -25,14 +25,15 @@ // // Adaptation for C2 of the escape analysis algorithm described in: // -// [Choi99] Jong-Deok Shoi, Manish Gupta, Mauricio Seffano, Vugranam C. Sreedhar, -// Sam Midkiff, "Escape Analysis for Java", Procedings of ACM SIGPLAN -// OOPSLA Conference, November 1, 1999 +// [Choi99] Jong-Deok Shoi, Manish Gupta, Mauricio Seffano, +// Vugranam C. Sreedhar, Sam Midkiff, +// "Escape Analysis for Java", Procedings of ACM SIGPLAN +// OOPSLA Conference, November 1, 1999 // // The flow-insensitive analysis described in the paper has been implemented. // -// The analysis requires construction of a "connection graph" (CG) for the method being -// analyzed. The nodes of the connection graph are: +// The analysis requires construction of a "connection graph" (CG) for +// the method being analyzed. The nodes of the connection graph are: // // - Java objects (JO) // - Local variables (LV) @@ -40,47 +41,51 @@ // // The CG contains 3 types of edges: // -// - PointsTo (-P>) {LV,OF} to JO -// - Deferred (-D>) from {LV, OF} to {LV, OF} +// - PointsTo (-P>) {LV, OF} to JO +// - Deferred (-D>) from {LV, OF} to {LV, OF} // - Field (-F>) from JO to OF // // The following utility functions is used by the algorithm: // -// PointsTo(n) - n is any CG node, it returns the set of JO that n could -// point to. +// PointsTo(n) - n is any CG node, it returns the set of JO that n could +// point to. // -// The algorithm describes how to construct the connection graph in the following 4 cases: +// The algorithm describes how to construct the connection graph +// in the following 4 cases: // // Case Edges Created // -// (1) p = new T() LV -P> JO -// (2) p = q LV -D> LV -// (3) p.f = q JO -F> OF, OF -D> LV -// (4) p = q.f JO -F> OF, LV -D> OF +// (1) p = new T() LV -P> JO +// (2) p = q LV -D> LV +// (3) p.f = q JO -F> OF, OF -D> LV +// (4) p = q.f JO -F> OF, LV -D> OF // -// In all these cases, p and q are local variables. For static field references, we can -// construct a local variable containing a reference to the static memory. +// In all these cases, p and q are local variables. For static field +// references, we can construct a local variable containing a reference +// to the static memory. // // C2 does not have local variables. However for the purposes of constructing // the connection graph, the following IR nodes are treated as local variables: // Phi (pointer values) // LoadP -// Proj (value returned from callnodes including allocations) -// CheckCastPP +// Proj#5 (value returned from callnodes including allocations) +// CheckCastPP, CastPP // -// The LoadP, Proj and CheckCastPP behave like variables assigned to only once. Only -// a Phi can have multiple assignments. Each input to a Phi is treated +// The LoadP, Proj and CheckCastPP behave like variables assigned to only once. +// Only a Phi can have multiple assignments. Each input to a Phi is treated // as an assignment to it. // -// The following note types are JavaObject: +// The following node types are JavaObject: // // top() // Allocate // AllocateArray // Parm (for incoming arguments) +// CastX2P ("unsafe" operations) // CreateEx // ConP // LoadKlass +// ThreadLocal // // AddP nodes are fields. // @@ -89,7 +94,7 @@ // source. This results in a graph with no deferred edges, only: // // LV -P> JO -// OF -P> JO +// OF -P> JO (the object whose oop is stored in the field) // JO -F> OF // // Then, for each node which is GlobalEscape, anything it could point to @@ -110,17 +115,18 @@ class PointsToNode { friend class ConnectionGraph; public: typedef enum { - UnknownType = 0, - JavaObject = 1, - LocalVar = 2, - Field = 3 + UnknownType = 0, + JavaObject = 1, + LocalVar = 2, + Field = 3 } NodeType; typedef enum { UnknownEscape = 0, - NoEscape = 1, - ArgEscape = 2, - GlobalEscape = 3 + NoEscape = 1, // A scalar replaceable object with unique type. + ArgEscape = 2, // An object passed as argument or referenced by + // argument (and not globally escape during call). + GlobalEscape = 3 // An object escapes the method and thread. } EscapeState; typedef enum { @@ -140,18 +146,24 @@ private: NodeType _type; EscapeState _escape; - GrowableArray* _edges; // outgoing edges - int _offset; // for fields + GrowableArray* _edges; // outgoing edges - bool _unique_type; // For allocated objects, this node may be a unique type public: - Node* _node; // Ideal node corresponding to this PointsTo node - int _inputs_processed; // the number of Phi inputs that have been processed so far - bool _hidden_alias; // this node is an argument to a function which may return it - // creating a hidden alias + Node* _node; // Ideal node corresponding to this PointsTo node. + int _offset; // Object fields offsets. + bool _scalar_replaceable;// Not escaped object could be replaced with scalar + bool _hidden_alias; // This node is an argument to a function. + // which may return it creating a hidden alias. + PointsToNode(): + _type(UnknownType), + _escape(UnknownEscape), + _edges(NULL), + _node(NULL), + _offset(-1), + _scalar_replaceable(true), + _hidden_alias(false) {} - PointsToNode(): _offset(-1), _type(UnknownType), _escape(UnknownEscape), _edges(NULL), _node(NULL), _inputs_processed(0), _hidden_alias(false), _unique_type(true) {} EscapeState escape_state() const { return _escape; } NodeType node_type() const { return _type;} @@ -182,22 +194,28 @@ public: class ConnectionGraph: public ResourceObj { private: - enum { - INITIAL_NODE_COUNT = 100 // initial size of _nodes array - }; + GrowableArray* _nodes; // Connection graph nodes indexed + // by ideal node index. + Unique_Node_List _delayed_worklist; // Nodes to be processed before + // the call build_connection_graph(). - GrowableArray* _nodes; // connection graph nodes Indexed by ideal - // node index - Unique_Node_List _deferred; // Phi's to be processed after parsing - VectorSet _processed; // records which nodes have been processed - bool _collecting; // indicates whether escape information is - // still being collected. If false, no new - // nodes will be processed - uint _phantom_object; // index of globally escaping object that - // pointer values loaded from a field which - // has not been set are assumed to point to - Compile * _compile; // Compile object for current compilation + VectorSet _processed; // Records which nodes have been + // processed. + + bool _collecting; // Indicates whether escape information + // is still being collected. If false, + // no new nodes will be processed. + + bool _has_allocations; // Indicates whether method has any + // non-escaping allocations. + + uint _phantom_object; // Index of globally escaping object + // that pointer values loaded from + // a field which has not been set + // are assumed to point to. + + Compile * _compile; // Compile object for current compilation // address of an element in _nodes. Used when the element is to be modified PointsToNode *ptnode_adr(uint idx) { @@ -208,8 +226,11 @@ private: return _nodes->adr_at(idx); } + // Add node to ConnectionGraph. + void add_node(Node *n, PointsToNode::NodeType nt, PointsToNode::EscapeState es, bool done); + // offset of a field reference - int type_to_offset(const Type *t); + int address_offset(Node* adr, PhaseTransform *phase); // compute the escape state for arguments to a call void process_call_arguments(CallNode *call, PhaseTransform *phase); @@ -217,12 +238,11 @@ private: // compute the escape state for the return value of a call void process_call_result(ProjNode *resproj, PhaseTransform *phase); - // compute the escape state of a Phi. This may be called multiple - // times as new inputs are added to the Phi. - void process_phi_escape(PhiNode *phi, PhaseTransform *phase); + // Populate Connection Graph with Ideal nodes. + void record_for_escape_analysis(Node *n, PhaseTransform *phase); - // compute the escape state of an ideal node. - void record_escape_work(Node *n, PhaseTransform *phase); + // Build Connection Graph and set nodes escape state. + void build_connection_graph(Node *n, PhaseTransform *phase); // walk the connection graph starting at the node corresponding to "n" and // add the index of everything it could point to, to "ptset". This may cause @@ -241,8 +261,8 @@ private: // a pointsto edge is added if it is a JavaObject void add_edge_from_fields(uint adr, uint to_i, int offs); - // Add a deferred edge from node given by "from_i" to any field of adr_i whose offset - // matches "offset" + // Add a deferred edge from node given by "from_i" to any field + // of adr_i whose offset matches "offset" void add_deferred_edge_to_fields(uint from_i, uint adr, int offs); @@ -262,6 +282,8 @@ private: PhiNode *create_split_phi(PhiNode *orig_phi, int alias_idx, GrowableArray &orig_phi_worklist, PhaseGVN *igvn, bool &new_created); PhiNode *split_memory_phi(PhiNode *orig_phi, int alias_idx, GrowableArray &orig_phi_worklist, PhaseGVN *igvn); Node *find_mem(Node *mem, int alias_idx, PhaseGVN *igvn); + Node *find_inst_mem(Node *mem, int alias_idx,GrowableArray &orig_phi_worklist, PhaseGVN *igvn); + // Propagate unique types created for unescaped allocated objects // through the graph void split_unique_types(GrowableArray &alloc_worklist); @@ -285,26 +307,24 @@ private: // Set the escape state of a node void set_escape_state(uint ni, PointsToNode::EscapeState es); - // bypass any casts and return the node they refer to - Node * skip_casts(Node *n); - // Get Compile object for current compilation. Compile *C() const { return _compile; } public: ConnectionGraph(Compile *C); - // record a Phi for later processing. - void record_for_escape_analysis(Node *n); - - // process a node and fill in its connection graph node - void record_escape(Node *n, PhaseTransform *phase); - - // All nodes have been recorded, compute the escape information + // Compute the escape information void compute_escape(); // escape state of a node PointsToNode::EscapeState escape_state(Node *n, PhaseTransform *phase); + // other information we have collected + bool is_scalar_replaceable(Node *n) { + if (_collecting) + return false; + PointsToNode ptn = _nodes->at_grow(n->_idx); + return ptn.escape_state() == PointsToNode::NoEscape && ptn._scalar_replaceable; + } bool hidden_alias(Node *n) { if (_collecting) diff --git a/hotspot/src/share/vm/opto/node.cpp b/hotspot/src/share/vm/opto/node.cpp index f361ef8b888..63606340527 100644 --- a/hotspot/src/share/vm/opto/node.cpp +++ b/hotspot/src/share/vm/opto/node.cpp @@ -812,8 +812,7 @@ int Node::disconnect_inputs(Node *n) { Node* Node::uncast() const { // Should be inline: //return is_ConstraintCast() ? uncast_helper(this) : (Node*) this; - if (is_ConstraintCast() || - (is_Type() && req() == 2 && Opcode() == Op_CheckCastPP)) + if (is_ConstraintCast() || is_CheckCastPP()) return uncast_helper(this); else return (Node*) this; @@ -827,7 +826,7 @@ Node* Node::uncast_helper(const Node* p) { break; } else if (p->is_ConstraintCast()) { p = p->in(1); - } else if (p->is_Type() && p->Opcode() == Op_CheckCastPP) { + } else if (p->is_CheckCastPP()) { p = p->in(1); } else { break; diff --git a/hotspot/src/share/vm/opto/node.hpp b/hotspot/src/share/vm/opto/node.hpp index ac35f9b4f1b..6dbd2a4cd30 100644 --- a/hotspot/src/share/vm/opto/node.hpp +++ b/hotspot/src/share/vm/opto/node.hpp @@ -1328,7 +1328,6 @@ public: // Inline definition of Compile::record_for_igvn must be deferred to this point. inline void Compile::record_for_igvn(Node* n) { _for_igvn->push(n); - record_for_escape_analysis(n); } //------------------------------Node_Stack------------------------------------- diff --git a/hotspot/src/share/vm/opto/phaseX.cpp b/hotspot/src/share/vm/opto/phaseX.cpp index 90b34d4afad..f462fe7d230 100644 --- a/hotspot/src/share/vm/opto/phaseX.cpp +++ b/hotspot/src/share/vm/opto/phaseX.cpp @@ -587,11 +587,6 @@ ConNode* PhaseValues::uncached_makecon(const Type *t) { Node_Notes* loc = C->locate_node_notes(nna, x->_idx, true); loc->clear(); // do not put debug info on constants } - // Collect points-to information for escape analysys - ConnectionGraph *cgr = C->congraph(); - if (cgr != NULL) { - cgr->record_escape(x, this); - } } else { x->destruct(); // Hit, destroy duplicate constant x = k; // use existing constant @@ -714,12 +709,6 @@ Node *PhaseGVN::transform_no_reclaim( Node *n ) { return i; } - // Collect points-to information for escape analysys - ConnectionGraph *cgr = C->congraph(); - if (cgr != NULL) { - cgr->record_escape(k, this); - } - // Return Idealized original return k; } @@ -1245,7 +1234,7 @@ void PhaseIterGVN::add_users_to_worklist( Node *n ) { uint use_op = use->Opcode(); // If changed Cast input, check Phi users for simple cycles - if( use->is_ConstraintCast() || use->Opcode() == Op_CheckCastPP ) { + if( use->is_ConstraintCast() || use->is_CheckCastPP() ) { for (DUIterator_Fast i2max, i2 = use->fast_outs(i2max); i2 < i2max; i2++) { Node* u = use->fast_out(i2); if (u->is_Phi()) diff --git a/hotspot/src/share/vm/runtime/arguments.cpp b/hotspot/src/share/vm/runtime/arguments.cpp index ccb60b7cb4b..991ed66233a 100644 --- a/hotspot/src/share/vm/runtime/arguments.cpp +++ b/hotspot/src/share/vm/runtime/arguments.cpp @@ -1276,6 +1276,9 @@ void Arguments::set_aggressive_opts_flags() { sprintf(buffer, "java.lang.Integer.IntegerCache.high=%d", AutoBoxCacheMax); add_property(buffer); } + if (AggressiveOpts && FLAG_IS_DEFAULT(DoEscapeAnalysis)) { + FLAG_SET_DEFAULT(DoEscapeAnalysis, true); + } #endif if (AggressiveOpts) { From 20046c1a187cad1a934bb3df58ea4ef686ec6d58 Mon Sep 17 00:00:00 2001 From: Vladimir Kozlov Date: Fri, 14 Mar 2008 16:40:42 -0700 Subject: [PATCH 056/258] 6672848: (Escape Analysis) improve lock elimination with EA Remove lock/unlock MemBar nodes and specify locks in debug info for deoptimization. Reviewed-by: never --- hotspot/src/share/vm/opto/callnode.cpp | 91 +++++++------------- hotspot/src/share/vm/opto/locknode.cpp | 3 +- hotspot/src/share/vm/opto/locknode.hpp | 5 ++ hotspot/src/share/vm/opto/macro.cpp | 111 +++++++++++++++++++------ hotspot/src/share/vm/opto/macro.hpp | 2 +- hotspot/src/share/vm/opto/output.cpp | 3 +- 6 files changed, 123 insertions(+), 92 deletions(-) diff --git a/hotspot/src/share/vm/opto/callnode.cpp b/hotspot/src/share/vm/opto/callnode.cpp index 60a183def71..ce9d353b41b 100644 --- a/hotspot/src/share/vm/opto/callnode.cpp +++ b/hotspot/src/share/vm/opto/callnode.cpp @@ -1364,7 +1364,7 @@ void AbstractLockNode::set_eliminated() { //============================================================================= Node *LockNode::Ideal(PhaseGVN *phase, bool can_reshape) { - // perform any generic optimizations first + // perform any generic optimizations first (returns 'this' or NULL) Node *result = SafePointNode::Ideal(phase, can_reshape); // Now see if we can optimize away this lock. We don't actually @@ -1372,7 +1372,20 @@ Node *LockNode::Ideal(PhaseGVN *phase, bool can_reshape) { // prevents macro expansion from expanding the lock. Since we don't // modify the graph, the value returned from this function is the // one computed above. - if (EliminateLocks && !is_eliminated()) { + if (result == NULL && can_reshape && EliminateLocks && !is_eliminated()) { + // + // If we are locking an unescaped object, the lock/unlock is unnecessary + // + ConnectionGraph *cgr = Compile::current()->congraph(); + PointsToNode::EscapeState es = PointsToNode::GlobalEscape; + if (cgr != NULL) + es = cgr->escape_state(obj_node(), phase); + if (es != PointsToNode::UnknownEscape && es != PointsToNode::GlobalEscape) { + // Mark it eliminated to update any counters + this->set_eliminated(); + return result; + } + // // Try lock coarsening // @@ -1412,8 +1425,10 @@ Node *LockNode::Ideal(PhaseGVN *phase, bool can_reshape) { int unlocks = 0; for (int i = 0; i < lock_ops.length(); i++) { AbstractLockNode* lock = lock_ops.at(i); - if (lock->Opcode() == Op_Lock) locks++; - else unlocks++; + if (lock->Opcode() == Op_Lock) + locks++; + else + unlocks++; if (Verbose) { lock->dump(1); } @@ -1450,7 +1465,7 @@ uint UnlockNode::size_of() const { return sizeof(*this); } //============================================================================= Node *UnlockNode::Ideal(PhaseGVN *phase, bool can_reshape) { - // perform any generic optimizations first + // perform any generic optimizations first (returns 'this' or NULL) Node * result = SafePointNode::Ideal(phase, can_reshape); // Now see if we can optimize away this unlock. We don't actually @@ -1458,66 +1473,18 @@ Node *UnlockNode::Ideal(PhaseGVN *phase, bool can_reshape) { // prevents macro expansion from expanding the unlock. Since we don't // modify the graph, the value returned from this function is the // one computed above. - if (EliminateLocks && !is_eliminated()) { + // Escape state is defined after Parse phase. + if (result == NULL && can_reshape && EliminateLocks && !is_eliminated()) { // - // If we are unlocking an unescaped object, the lock/unlock is unnecessary - // We can eliminate them if there are no safepoints in the locked region. + // If we are unlocking an unescaped object, the lock/unlock is unnecessary. // ConnectionGraph *cgr = Compile::current()->congraph(); - if (cgr != NULL && cgr->escape_state(obj_node(), phase) == PointsToNode::NoEscape) { - GrowableArray lock_ops; - LockNode *lock = find_matching_lock(this); - if (lock != NULL) { - lock_ops.append(this); - lock_ops.append(lock); - // find other unlocks which pair with the lock we found and add them - // to the list - Node * box = box_node(); - - for (DUIterator_Fast imax, i = box->fast_outs(imax); i < imax; i++) { - Node *use = box->fast_out(i); - if (use->is_Unlock() && use != this) { - UnlockNode *unlock1 = use->as_Unlock(); - if (!unlock1->is_eliminated()) { - LockNode *lock1 = find_matching_lock(unlock1); - if (lock == lock1) - lock_ops.append(unlock1); - else if (lock1 == NULL) { - // we can't find a matching lock, we must assume the worst - lock_ops.trunc_to(0); - break; - } - } - } - } - if (lock_ops.length() > 0) { - - #ifndef PRODUCT - if (PrintEliminateLocks) { - int locks = 0; - int unlocks = 0; - for (int i = 0; i < lock_ops.length(); i++) { - AbstractLockNode* lock = lock_ops.at(i); - if (lock->Opcode() == Op_Lock) locks++; - else unlocks++; - if (Verbose) { - lock->dump(1); - } - } - tty->print_cr("***Eliminated %d unescaped unlocks and %d unescaped locks", unlocks, locks); - } - #endif - - // for each of the identified locks, mark them - // as eliminatable - for (int i = 0; i < lock_ops.length(); i++) { - AbstractLockNode* lock = lock_ops.at(i); - - // Mark it eliminated to update any counters - lock->set_eliminated(); - } - } - } + PointsToNode::EscapeState es = PointsToNode::GlobalEscape; + if (cgr != NULL) + es = cgr->escape_state(obj_node(), phase); + if (es != PointsToNode::UnknownEscape && es != PointsToNode::GlobalEscape) { + // Mark it eliminated to update any counters + this->set_eliminated(); } } return result; diff --git a/hotspot/src/share/vm/opto/locknode.cpp b/hotspot/src/share/vm/opto/locknode.cpp index 90da8efaa36..48bf9ebfefc 100644 --- a/hotspot/src/share/vm/opto/locknode.cpp +++ b/hotspot/src/share/vm/opto/locknode.cpp @@ -36,7 +36,8 @@ const RegMask &BoxLockNode::out_RegMask() const { uint BoxLockNode::size_of() const { return sizeof(*this); } -BoxLockNode::BoxLockNode( int slot ) : Node( Compile::current()->root() ), _slot(slot) { +BoxLockNode::BoxLockNode( int slot ) : Node( Compile::current()->root() ), + _slot(slot), _is_eliminated(false) { init_class_id(Class_BoxLock); init_flags(Flag_rematerialize); OptoReg::Name reg = OptoReg::stack2reg(_slot); diff --git a/hotspot/src/share/vm/opto/locknode.hpp b/hotspot/src/share/vm/opto/locknode.hpp index 6b1a8883ca4..e765a6c5d69 100644 --- a/hotspot/src/share/vm/opto/locknode.hpp +++ b/hotspot/src/share/vm/opto/locknode.hpp @@ -27,6 +27,7 @@ class BoxLockNode : public Node { public: const int _slot; RegMask _inmask; + bool _is_eliminated; // indicates this lock was safely eliminated BoxLockNode( int lock ); virtual int Opcode() const; @@ -42,6 +43,10 @@ public: static OptoReg::Name stack_slot(Node* box_node); + bool is_eliminated() { return _is_eliminated; } + // mark lock as eliminated. + void set_eliminated() { _is_eliminated = true; } + #ifndef PRODUCT virtual void format( PhaseRegAlloc *, outputStream *st ) const; virtual void dump_spec(outputStream *st) const { st->print(" Lock %d",_slot); } diff --git a/hotspot/src/share/vm/opto/macro.cpp b/hotspot/src/share/vm/opto/macro.cpp index 4a8ffd1076f..014280aaa0a 100644 --- a/hotspot/src/share/vm/opto/macro.cpp +++ b/hotspot/src/share/vm/opto/macro.cpp @@ -828,43 +828,102 @@ void PhaseMacroExpand::expand_allocate_array(AllocateArrayNode *alloc) { // Note: The membar's associated with the lock/unlock are currently not // eliminated. This should be investigated as a future enhancement. // -void PhaseMacroExpand::eliminate_locking_node(AbstractLockNode *alock) { - Node* mem = alock->in(TypeFunc::Memory); +bool PhaseMacroExpand::eliminate_locking_node(AbstractLockNode *alock) { + + if (!alock->is_eliminated()) { + return false; + } + // Mark the box lock as eliminated if all correspondent locks are eliminated + // to construct correct debug info. + BoxLockNode* box = alock->box_node()->as_BoxLock(); + if (!box->is_eliminated()) { + bool eliminate = true; + for (DUIterator_Fast imax, i = box->fast_outs(imax); i < imax; i++) { + Node *lck = box->fast_out(i); + if (lck->is_Lock() && !lck->as_AbstractLock()->is_eliminated()) { + eliminate = false; + break; + } + } + if (eliminate) + box->set_eliminated(); + } + + #ifndef PRODUCT + if (PrintEliminateLocks) { + if (alock->is_Lock()) { + tty->print_cr("++++ Eliminating: %d Lock", alock->_idx); + } else { + tty->print_cr("++++ Eliminating: %d Unlock", alock->_idx); + } + } + #endif + + Node* mem = alock->in(TypeFunc::Memory); + Node* ctrl = alock->in(TypeFunc::Control); + + extract_call_projections(alock); + // There are 2 projections from the lock. The lock node will + // be deleted when its last use is subsumed below. + assert(alock->outcnt() == 2 && + _fallthroughproj != NULL && + _memproj_fallthrough != NULL, + "Unexpected projections from Lock/Unlock"); + + Node* fallthroughproj = _fallthroughproj; + Node* memproj_fallthrough = _memproj_fallthrough; // The memory projection from a lock/unlock is RawMem // The input to a Lock is merged memory, so extract its RawMem input // (unless the MergeMem has been optimized away.) if (alock->is_Lock()) { - if (mem->is_MergeMem()) - mem = mem->as_MergeMem()->in(Compile::AliasIdxRaw); + // Seach for MemBarAcquire node and delete it also. + MemBarNode* membar = fallthroughproj->unique_ctrl_out()->as_MemBar(); + assert(membar != NULL && membar->Opcode() == Op_MemBarAcquire, ""); + Node* ctrlproj = membar->proj_out(TypeFunc::Control); + Node* memproj = membar->proj_out(TypeFunc::Memory); + _igvn.hash_delete(ctrlproj); + _igvn.subsume_node(ctrlproj, fallthroughproj); + _igvn.hash_delete(memproj); + _igvn.subsume_node(memproj, memproj_fallthrough); } - extract_call_projections(alock); - // There are 2 projections from the lock. The lock node will - // be deleted when its last use is subsumed below. - assert(alock->outcnt() == 2 && _fallthroughproj != NULL && - _memproj_fallthrough != NULL, "Unexpected projections from Lock/Unlock"); - _igvn.hash_delete(_fallthroughproj); - _igvn.subsume_node(_fallthroughproj, alock->in(TypeFunc::Control)); - _igvn.hash_delete(_memproj_fallthrough); - _igvn.subsume_node(_memproj_fallthrough, mem); - return; + // Seach for MemBarRelease node and delete it also. + if (alock->is_Unlock() && ctrl != NULL && ctrl->is_Proj() && + ctrl->in(0)->is_MemBar()) { + MemBarNode* membar = ctrl->in(0)->as_MemBar(); + assert(membar->Opcode() == Op_MemBarRelease && + mem->is_Proj() && membar == mem->in(0), ""); + _igvn.hash_delete(fallthroughproj); + _igvn.subsume_node(fallthroughproj, ctrl); + _igvn.hash_delete(memproj_fallthrough); + _igvn.subsume_node(memproj_fallthrough, mem); + fallthroughproj = ctrl; + memproj_fallthrough = mem; + ctrl = membar->in(TypeFunc::Control); + mem = membar->in(TypeFunc::Memory); + } + + _igvn.hash_delete(fallthroughproj); + _igvn.subsume_node(fallthroughproj, ctrl); + _igvn.hash_delete(memproj_fallthrough); + _igvn.subsume_node(memproj_fallthrough, mem); + return true; } //------------------------------expand_lock_node---------------------- void PhaseMacroExpand::expand_lock_node(LockNode *lock) { + if (eliminate_locking_node(lock)) { + return; + } + Node* ctrl = lock->in(TypeFunc::Control); Node* mem = lock->in(TypeFunc::Memory); Node* obj = lock->obj_node(); Node* box = lock->box_node(); - Node *flock = lock->fastlock_node(); - - if (lock->is_eliminated()) { - eliminate_locking_node(lock); - return; - } + Node* flock = lock->fastlock_node(); // Make the merge point Node *region = new (C, 3) RegionNode(3); @@ -913,17 +972,15 @@ void PhaseMacroExpand::expand_lock_node(LockNode *lock) { //------------------------------expand_unlock_node---------------------- void PhaseMacroExpand::expand_unlock_node(UnlockNode *unlock) { - Node *ctrl = unlock->in(TypeFunc::Control); + if (eliminate_locking_node(unlock)) { + return; + } + + Node* ctrl = unlock->in(TypeFunc::Control); Node* mem = unlock->in(TypeFunc::Memory); Node* obj = unlock->obj_node(); Node* box = unlock->box_node(); - - if (unlock->is_eliminated()) { - eliminate_locking_node(unlock); - return; - } - // No need for a null check on unlock // Make the merge point diff --git a/hotspot/src/share/vm/opto/macro.hpp b/hotspot/src/share/vm/opto/macro.hpp index 20dd65c40b7..a34094dbf00 100644 --- a/hotspot/src/share/vm/opto/macro.hpp +++ b/hotspot/src/share/vm/opto/macro.hpp @@ -78,7 +78,7 @@ private: Node* length, const TypeFunc* slow_call_type, address slow_call_address); - void eliminate_locking_node(AbstractLockNode *alock); + bool eliminate_locking_node(AbstractLockNode *alock); void expand_lock_node(LockNode *lock); void expand_unlock_node(UnlockNode *unlock); diff --git a/hotspot/src/share/vm/opto/output.cpp b/hotspot/src/share/vm/opto/output.cpp index 3c06b135f9a..b1f2ca12155 100644 --- a/hotspot/src/share/vm/opto/output.cpp +++ b/hotspot/src/share/vm/opto/output.cpp @@ -882,7 +882,8 @@ void Compile::Process_OopMap_Node(MachNode *mach, int current_offset) { } OptoReg::Name box_reg = BoxLockNode::stack_slot(box_node); - monarray->append(new MonitorValue(scval, Location::new_stk_loc(Location::normal,_regalloc->reg2offset(box_reg)))); + Location basic_lock = Location::new_stk_loc(Location::normal,_regalloc->reg2offset(box_reg)); + monarray->append(new MonitorValue(scval, basic_lock, box_node->as_BoxLock()->is_eliminated())); } // We dump the object pool first, since deoptimization reads it in first. From f2b6ac989e1115101809f98ba5b3681b6897b64d Mon Sep 17 00:00:00 2001 From: "Y. Srinivas Ramakrishna" Date: Sun, 16 Mar 2008 21:57:25 -0700 Subject: [PATCH 057/258] 6634032: CMS: Need CMSInitiatingPermOccupancyFraction for perm, divorcing from CMSInitiatingOccupancyFraction The option CMSInitiatingPermOccupancyFraction now controls perm triggering threshold. Even though the actual value of the threshold has not yet been changed, so there is no change in policy, we now have the infrastructure in place for dynamically deciding when to collect the perm gen, an issue that will be addressed in the near future. Reviewed-by: jmasa --- .../concurrentMarkSweepGeneration.cpp | 239 +++++++++++------- .../concurrentMarkSweepGeneration.hpp | 45 ++-- .../concurrentMarkSweepGeneration.inline.hpp | 2 +- hotspot/src/share/vm/runtime/globals.hpp | 21 +- 4 files changed, 198 insertions(+), 109 deletions(-) diff --git a/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/concurrentMarkSweepGeneration.cpp b/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/concurrentMarkSweepGeneration.cpp index eff7a042e95..42593073c32 100644 --- a/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/concurrentMarkSweepGeneration.cpp +++ b/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/concurrentMarkSweepGeneration.cpp @@ -225,6 +225,34 @@ ConcurrentMarkSweepGeneration::ConcurrentMarkSweepGeneration( assert(_dilatation_factor >= 1.0, "from previous assert"); } + +// The field "_initiating_occupancy" represents the occupancy percentage +// at which we trigger a new collection cycle. Unless explicitly specified +// via CMSInitiating[Perm]OccupancyFraction (argument "io" below), it +// is calculated by: +// +// Let "f" be MinHeapFreeRatio in +// +// _intiating_occupancy = 100-f + +// f * (CMSTrigger[Perm]Ratio/100) +// where CMSTrigger[Perm]Ratio is the argument "tr" below. +// +// That is, if we assume the heap is at its desired maximum occupancy at the +// end of a collection, we let CMSTrigger[Perm]Ratio of the (purported) free +// space be allocated before initiating a new collection cycle. +// +void ConcurrentMarkSweepGeneration::init_initiating_occupancy(intx io, intx tr) { + assert(io <= 100 && tr >= 0 && tr <= 100, "Check the arguments"); + if (io >= 0) { + _initiating_occupancy = (double)io / 100.0; + } else { + _initiating_occupancy = ((100 - MinHeapFreeRatio) + + (double)(tr * MinHeapFreeRatio) / 100.0) + / 100.0; + } +} + + void ConcurrentMarkSweepGeneration::ref_processor_init() { assert(collector() != NULL, "no collector"); collector()->ref_processor_init(); @@ -520,8 +548,8 @@ CMSCollector::CMSCollector(ConcurrentMarkSweepGeneration* cmsGen, _verification_mark_bm(0, Mutex::leaf + 1, "CMS_verification_mark_bm_lock"), _completed_initialization(false), _collector_policy(cp), - _unload_classes(false), - _unloaded_classes_last_cycle(false), + _should_unload_classes(false), + _concurrent_cycles_since_last_unload(0), _sweep_estimate(CMS_SweepWeight, CMS_SweepPadding) { if (ExplicitGCInvokesConcurrentAndUnloadsClasses) { @@ -642,26 +670,11 @@ CMSCollector::CMSCollector(ConcurrentMarkSweepGeneration* cmsGen, } } - // "initiatingOccupancy" is the occupancy ratio at which we trigger - // a new collection cycle. Unless explicitly specified via - // CMSTriggerRatio, it is calculated by: - // Let "f" be MinHeapFreeRatio in - // - // intiatingOccupancy = 100-f + - // f * (CMSTriggerRatio/100) - // That is, if we assume the heap is at its desired maximum occupancy at the - // end of a collection, we let CMSTriggerRatio of the (purported) free - // space be allocated before initiating a new collection cycle. - if (CMSInitiatingOccupancyFraction > 0) { - _initiatingOccupancy = (double)CMSInitiatingOccupancyFraction / 100.0; - } else { - _initiatingOccupancy = ((100 - MinHeapFreeRatio) + - (double)(CMSTriggerRatio * - MinHeapFreeRatio) / 100.0) - / 100.0; - } + _cmsGen ->init_initiating_occupancy(CMSInitiatingOccupancyFraction, CMSTriggerRatio); + _permGen->init_initiating_occupancy(CMSInitiatingPermOccupancyFraction, CMSTriggerPermRatio); + // Clip CMSBootstrapOccupancy between 0 and 100. - _bootstrap_occupancy = ((double)MIN2((intx)100, MAX2((intx)0, CMSBootstrapOccupancy))) + _bootstrap_occupancy = ((double)MIN2((uintx)100, MAX2((uintx)0, CMSBootstrapOccupancy))) /(double)100; _full_gcs_since_conc_gc = 0; @@ -1413,7 +1426,8 @@ bool CMSCollector::shouldConcurrentCollect() { gclog_or_tty->print_cr("promotion_rate=%g", stats().promotion_rate()); gclog_or_tty->print_cr("cms_allocation_rate=%g", stats().cms_allocation_rate()); gclog_or_tty->print_cr("occupancy=%3.7f", _cmsGen->occupancy()); - gclog_or_tty->print_cr("initiatingOccupancy=%3.7f", initiatingOccupancy()); + gclog_or_tty->print_cr("initiatingOccupancy=%3.7f", _cmsGen->initiating_occupancy()); + gclog_or_tty->print_cr("initiatingPermOccupancy=%3.7f", _permGen->initiating_occupancy()); } // ------------------------------------------------------------------ @@ -1446,22 +1460,36 @@ bool CMSCollector::shouldConcurrentCollect() { // old gen want a collection cycle started. Each may use // an appropriate criterion for making this decision. // XXX We need to make sure that the gen expansion - // criterion dovetails well with this. - if (_cmsGen->shouldConcurrentCollect(initiatingOccupancy())) { + // criterion dovetails well with this. XXX NEED TO FIX THIS + if (_cmsGen->should_concurrent_collect()) { if (Verbose && PrintGCDetails) { gclog_or_tty->print_cr("CMS old gen initiated"); } return true; } - if (cms_should_unload_classes() && - _permGen->shouldConcurrentCollect(initiatingOccupancy())) { - if (Verbose && PrintGCDetails) { - gclog_or_tty->print_cr("CMS perm gen initiated"); + // We start a collection if we believe an incremental collection may fail; + // this is not likely to be productive in practice because it's probably too + // late anyway. + GenCollectedHeap* gch = GenCollectedHeap::heap(); + assert(gch->collector_policy()->is_two_generation_policy(), + "You may want to check the correctness of the following"); + if (gch->incremental_collection_will_fail()) { + if (PrintGCDetails && Verbose) { + gclog_or_tty->print("CMSCollector: collect because incremental collection will fail "); } return true; } + if (CMSClassUnloadingEnabled && _permGen->should_concurrent_collect()) { + bool res = update_should_unload_classes(); + if (res) { + if (Verbose && PrintGCDetails) { + gclog_or_tty->print_cr("CMS perm gen initiated"); + } + return true; + } + } return false; } @@ -1471,32 +1499,36 @@ void CMSCollector::clear_expansion_cause() { _permGen->clear_expansion_cause(); } -bool ConcurrentMarkSweepGeneration::shouldConcurrentCollect( - double initiatingOccupancy) { - // We should be conservative in starting a collection cycle. To - // start too eagerly runs the risk of collecting too often in the - // extreme. To collect too rarely falls back on full collections, - // which works, even if not optimum in terms of concurrent work. - // As a work around for too eagerly collecting, use the flag - // UseCMSInitiatingOccupancyOnly. This also has the advantage of - // giving the user an easily understandable way of controlling the - // collections. - // We want to start a new collection cycle if any of the following - // conditions hold: - // . our current occupancy exceeds the initiating occupancy, or - // . we recently needed to expand and have not since that expansion, - // collected, or - // . we are not using adaptive free lists and linear allocation is - // going to fail, or - // . (for old gen) incremental collection has already failed or - // may soon fail in the near future as we may not be able to absorb - // promotions. - assert_lock_strong(freelistLock()); +// We should be conservative in starting a collection cycle. To +// start too eagerly runs the risk of collecting too often in the +// extreme. To collect too rarely falls back on full collections, +// which works, even if not optimum in terms of concurrent work. +// As a work around for too eagerly collecting, use the flag +// UseCMSInitiatingOccupancyOnly. This also has the advantage of +// giving the user an easily understandable way of controlling the +// collections. +// We want to start a new collection cycle if any of the following +// conditions hold: +// . our current occupancy exceeds the configured initiating occupancy +// for this generation, or +// . we recently needed to expand this space and have not, since that +// expansion, done a collection of this generation, or +// . the underlying space believes that it may be a good idea to initiate +// a concurrent collection (this may be based on criteria such as the +// following: the space uses linear allocation and linear allocation is +// going to fail, or there is believed to be excessive fragmentation in +// the generation, etc... or ... +// [.(currently done by CMSCollector::shouldConcurrentCollect() only for +// the case of the old generation, not the perm generation; see CR 6543076): +// we may be approaching a point at which allocation requests may fail because +// we will be out of sufficient free space given allocation rate estimates.] +bool ConcurrentMarkSweepGeneration::should_concurrent_collect() const { - if (occupancy() > initiatingOccupancy) { + assert_lock_strong(freelistLock()); + if (occupancy() > initiating_occupancy()) { if (PrintGCDetails && Verbose) { gclog_or_tty->print(" %s: collect because of occupancy %f / %f ", - short_name(), occupancy(), initiatingOccupancy); + short_name(), occupancy(), initiating_occupancy()); } return true; } @@ -1510,20 +1542,9 @@ bool ConcurrentMarkSweepGeneration::shouldConcurrentCollect( } return true; } - GenCollectedHeap* gch = GenCollectedHeap::heap(); - assert(gch->collector_policy()->is_two_generation_policy(), - "You may want to check the correctness of the following"); - if (gch->incremental_collection_will_fail()) { + if (_cmsSpace->should_concurrent_collect()) { if (PrintGCDetails && Verbose) { - gclog_or_tty->print(" %s: collect because incremental collection will fail ", - short_name()); - } - return true; - } - if (!_cmsSpace->adaptive_freelists() && - _cmsSpace->linearAllocationWouldFail()) { - if (PrintGCDetails && Verbose) { - gclog_or_tty->print(" %s: collect because of linAB ", + gclog_or_tty->print(" %s: collect because cmsSpace says so ", short_name()); } return true; @@ -1970,8 +1991,9 @@ void CMSCollector::do_compaction_work(bool clear_all_soft_refs) { "Should have been NULL'd before baton was passed"); reset(false /* == !asynch */); _cmsGen->reset_after_compaction(); + _concurrent_cycles_since_last_unload = 0; - if (verifying() && !cms_should_unload_classes()) { + if (verifying() && !should_unload_classes()) { perm_gen_verify_bit_map()->clear_all(); } @@ -2098,6 +2120,7 @@ void CMSCollector::collect_in_background(bool clear_all_soft_refs) { { bool safepoint_check = Mutex::_no_safepoint_check_flag; MutexLockerEx hl(Heap_lock, safepoint_check); + FreelistLocker fll(this); MutexLockerEx x(CGC_lock, safepoint_check); if (_foregroundGCIsActive || !UseAsyncConcMarkSweepGC) { // The foreground collector is active or we're @@ -2112,13 +2135,9 @@ void CMSCollector::collect_in_background(bool clear_all_soft_refs) { // a new cycle. clear_expansion_cause(); } - _unloaded_classes_last_cycle = cms_should_unload_classes(); // ... from last cycle - // This controls class unloading in response to an explicit gc request. - // If ExplicitGCInvokesConcurrentAndUnloadsClasses is set, then - // we will unload classes even if CMSClassUnloadingEnabled is not set. - // See CR 6541037 and related CRs. - _unload_classes = _full_gc_requested // ... for this cycle - && ExplicitGCInvokesConcurrentAndUnloadsClasses; + // Decide if we want to enable class unloading as part of the + // ensuing concurrent GC cycle. + update_should_unload_classes(); _full_gc_requested = false; // acks all outstanding full gc requests // Signal that we are about to start a collection gch->increment_total_full_collections(); // ... starting a collection cycle @@ -3047,21 +3066,62 @@ void CMSCollector::verify_overflow_empty() const { } #endif // PRODUCT +// Decide if we want to enable class unloading as part of the +// ensuing concurrent GC cycle. We will collect the perm gen and +// unload classes if it's the case that: +// (1) an explicit gc request has been made and the flag +// ExplicitGCInvokesConcurrentAndUnloadsClasses is set, OR +// (2) (a) class unloading is enabled at the command line, and +// (b) (i) perm gen threshold has been crossed, or +// (ii) old gen is getting really full, or +// (iii) the previous N CMS collections did not collect the +// perm gen +// NOTE: Provided there is no change in the state of the heap between +// calls to this method, it should have idempotent results. Moreover, +// its results should be monotonically increasing (i.e. going from 0 to 1, +// but not 1 to 0) between successive calls between which the heap was +// not collected. For the implementation below, it must thus rely on +// the property that concurrent_cycles_since_last_unload() +// will not decrease unless a collection cycle happened and that +// _permGen->should_concurrent_collect() and _cmsGen->is_too_full() are +// themselves also monotonic in that sense. See check_monotonicity() +// below. +bool CMSCollector::update_should_unload_classes() { + _should_unload_classes = false; + // Condition 1 above + if (_full_gc_requested && ExplicitGCInvokesConcurrentAndUnloadsClasses) { + _should_unload_classes = true; + } else if (CMSClassUnloadingEnabled) { // Condition 2.a above + // Disjuncts 2.b.(i,ii,iii) above + _should_unload_classes = (concurrent_cycles_since_last_unload() >= + CMSClassUnloadingMaxInterval) + || _permGen->should_concurrent_collect() + || _cmsGen->is_too_full(); + } + return _should_unload_classes; +} + +bool ConcurrentMarkSweepGeneration::is_too_full() const { + bool res = should_concurrent_collect(); + res = res && (occupancy() > (double)CMSIsTooFullPercentage/100.0); + return res; +} + void CMSCollector::setup_cms_unloading_and_verification_state() { const bool should_verify = VerifyBeforeGC || VerifyAfterGC || VerifyDuringGC || VerifyBeforeExit; const int rso = SharedHeap::SO_Symbols | SharedHeap::SO_Strings | SharedHeap::SO_CodeCache; - if (cms_should_unload_classes()) { // Should unload classes this cycle + if (should_unload_classes()) { // Should unload classes this cycle remove_root_scanning_option(rso); // Shrink the root set appropriately set_verifying(should_verify); // Set verification state for this cycle return; // Nothing else needs to be done at this time } // Not unloading classes this cycle - assert(!cms_should_unload_classes(), "Inconsitency!"); - if ((!verifying() || cms_unloaded_classes_last_cycle()) && should_verify) { + assert(!should_unload_classes(), "Inconsitency!"); + if ((!verifying() || unloaded_classes_last_cycle()) && should_verify) { // We were not verifying, or we _were_ unloading classes in the last cycle, // AND some verification options are enabled this cycle; in this case, // we must make sure that the deadness map is allocated if not already so, @@ -4693,7 +4753,7 @@ void CMSCollector::checkpointRootsFinalWork(bool asynch, GenCollectedHeap* gch = GenCollectedHeap::heap(); - if (cms_should_unload_classes()) { + if (should_unload_classes()) { CodeCache::gc_prologue(); } assert(haveFreelistLocks(), "must have free list locks"); @@ -4753,7 +4813,7 @@ void CMSCollector::checkpointRootsFinalWork(bool asynch, verify_work_stacks_empty(); verify_overflow_empty(); - if (cms_should_unload_classes()) { + if (should_unload_classes()) { CodeCache::gc_epilogue(); } @@ -5623,7 +5683,7 @@ void CMSCollector::refProcessingWork(bool asynch, bool clear_all_soft_refs) { verify_work_stacks_empty(); } - if (cms_should_unload_classes()) { + if (should_unload_classes()) { { TraceTime t("class unloading", PrintGCDetails, false, gclog_or_tty); @@ -5726,7 +5786,7 @@ void CMSCollector::sweep(bool asynch) { // this cycle, we preserve the perm gen object "deadness" information // in the perm_gen_verify_bit_map. In order to do that we traverse // all blocks in perm gen and mark all dead objects. - if (verifying() && !cms_should_unload_classes()) { + if (verifying() && !should_unload_classes()) { assert(perm_gen_verify_bit_map()->sizeInBits() != 0, "Should have already been allocated"); MarkDeadObjectsClosure mdo(this, _permGen->cmsSpace(), @@ -5753,7 +5813,7 @@ void CMSCollector::sweep(bool asynch) { } // Now repeat for perm gen - if (cms_should_unload_classes()) { + if (should_unload_classes()) { CMSTokenSyncWithLocks ts(true, _permGen->freelistLock(), bitMapLock()); sweepWork(_permGen, asynch); @@ -5775,7 +5835,7 @@ void CMSCollector::sweep(bool asynch) { // already have needed locks sweepWork(_cmsGen, asynch); - if (cms_should_unload_classes()) { + if (should_unload_classes()) { sweepWork(_permGen, asynch); } // Update heap occupancy information which is used as @@ -5937,6 +5997,11 @@ void CMSCollector::sweepWork(ConcurrentMarkSweepGeneration* gen, } gen->cmsSpace()->sweep_completed(); gen->cmsSpace()->endSweepFLCensus(sweepCount()); + if (should_unload_classes()) { // unloaded classes this cycle, + _concurrent_cycles_since_last_unload = 0; // ... reset count + } else { // did not unload classes, + _concurrent_cycles_since_last_unload++; // ... increment count + } } // Reset CMS data structures (for now just the marking bit map) @@ -7194,7 +7259,7 @@ PushOrMarkClosure::PushOrMarkClosure(CMSCollector* collector, _revisitStack(revisitStack), _finger(finger), _parent(parent), - _should_remember_klasses(collector->cms_should_unload_classes()) + _should_remember_klasses(collector->should_unload_classes()) { } Par_PushOrMarkClosure::Par_PushOrMarkClosure(CMSCollector* collector, @@ -7217,7 +7282,7 @@ Par_PushOrMarkClosure::Par_PushOrMarkClosure(CMSCollector* collector, _finger(finger), _global_finger_addr(global_finger_addr), _parent(parent), - _should_remember_klasses(collector->cms_should_unload_classes()) + _should_remember_klasses(collector->should_unload_classes()) { } @@ -7360,7 +7425,7 @@ PushAndMarkClosure::PushAndMarkClosure(CMSCollector* collector, _mark_stack(mark_stack), _revisit_stack(revisit_stack), _concurrent_precleaning(concurrent_precleaning), - _should_remember_klasses(collector->cms_should_unload_classes()) + _should_remember_klasses(collector->should_unload_classes()) { assert(_ref_processor != NULL, "_ref_processor shouldn't be NULL"); } @@ -7422,7 +7487,7 @@ Par_PushAndMarkClosure::Par_PushAndMarkClosure(CMSCollector* collector, _bit_map(bit_map), _work_queue(work_queue), _revisit_stack(revisit_stack), - _should_remember_klasses(collector->cms_should_unload_classes()) + _should_remember_klasses(collector->should_unload_classes()) { assert(_ref_processor != NULL, "_ref_processor shouldn't be NULL"); } @@ -7944,7 +8009,7 @@ size_t SweepClosure::doLiveChunk(FreeChunk* fc) { #ifdef DEBUG if (oop(addr)->klass() != NULL && - ( !_collector->cms_should_unload_classes() + ( !_collector->should_unload_classes() || oop(addr)->is_parsable())) { // Ignore mark word because we are running concurrent with mutators assert(oop(addr)->is_oop(true), "live block should be an oop"); @@ -7957,7 +8022,7 @@ size_t SweepClosure::doLiveChunk(FreeChunk* fc) { } else { // This should be an initialized object that's alive. assert(oop(addr)->klass() != NULL && - (!_collector->cms_should_unload_classes() + (!_collector->should_unload_classes() || oop(addr)->is_parsable()), "Should be an initialized object"); // Ignore mark word because we are running concurrent with mutators diff --git a/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/concurrentMarkSweepGeneration.hpp b/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/concurrentMarkSweepGeneration.hpp index f4f790ebab1..9f05caf7214 100644 --- a/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/concurrentMarkSweepGeneration.hpp +++ b/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/concurrentMarkSweepGeneration.hpp @@ -535,13 +535,16 @@ class CMSCollector: public CHeapObj { // In support of ExplicitGCInvokesConcurrent static bool _full_gc_requested; unsigned int _collection_count_start; + // Should we unload classes this concurrent cycle? - // Set in response to a concurrent full gc request. - bool _unload_classes; - bool _unloaded_classes_last_cycle; + bool _should_unload_classes; + unsigned int _concurrent_cycles_since_last_unload; + unsigned int concurrent_cycles_since_last_unload() const { + return _concurrent_cycles_since_last_unload; + } // Did we (allow) unload classes in the previous concurrent cycle? - bool cms_unloaded_classes_last_cycle() const { - return _unloaded_classes_last_cycle || CMSClassUnloadingEnabled; + bool unloaded_classes_last_cycle() const { + return concurrent_cycles_since_last_unload() == 0; } // Verification support @@ -651,8 +654,6 @@ class CMSCollector: public CHeapObj { // number of full gc's since the last concurrent gc. uint _full_gcs_since_conc_gc; - // if occupancy exceeds this, start a new gc cycle - double _initiatingOccupancy; // occupancy used for bootstrapping stats double _bootstrap_occupancy; @@ -825,7 +826,6 @@ class CMSCollector: public CHeapObj { Mutex* bitMapLock() const { return _markBitMap.lock(); } static CollectorState abstract_state() { return _collectorState; } - double initiatingOccupancy() const { return _initiatingOccupancy; } bool should_abort_preclean() const; // Whether preclean should be aborted. size_t get_eden_used() const; @@ -849,11 +849,10 @@ class CMSCollector: public CHeapObj { // In support of ExplicitGCInvokesConcurrent static void request_full_gc(unsigned int full_gc_count); // Should we unload classes in a particular concurrent cycle? - bool cms_should_unload_classes() const { - assert(!_unload_classes || ExplicitGCInvokesConcurrentAndUnloadsClasses, - "Inconsistency; see CR 6541037"); - return _unload_classes || CMSClassUnloadingEnabled; + bool should_unload_classes() const { + return _should_unload_classes; } + bool update_should_unload_classes(); void direct_allocated(HeapWord* start, size_t size); @@ -1022,6 +1021,10 @@ class ConcurrentMarkSweepGeneration: public CardGeneration { _incremental_collection_failed = false; } + // accessors + void set_expansion_cause(CMSExpansionCause::Cause v) { _expansion_cause = v;} + CMSExpansionCause::Cause expansion_cause() const { return _expansion_cause; } + private: // For parallel young-gen GC support. CMSParGCThreadState** _par_gc_thread_states; @@ -1029,10 +1032,6 @@ class ConcurrentMarkSweepGeneration: public CardGeneration { // Reason generation was expanded CMSExpansionCause::Cause _expansion_cause; - // accessors - void set_expansion_cause(CMSExpansionCause::Cause v) { _expansion_cause = v;} - CMSExpansionCause::Cause expansion_cause() { return _expansion_cause; } - // In support of MinChunkSize being larger than min object size const double _dilatation_factor; @@ -1045,6 +1044,10 @@ class ConcurrentMarkSweepGeneration: public CardGeneration { CollectionTypes _debug_collection_type; + // Fraction of current occupancy at which to start a CMS collection which + // will collect this generation (at least). + double _initiating_occupancy; + protected: // Grow generation by specified size (returns false if unable to grow) bool grow_by(size_t bytes); @@ -1060,6 +1063,10 @@ class ConcurrentMarkSweepGeneration: public CardGeneration { // space. size_t max_available() const; + // getter and initializer for _initiating_occupancy field. + double initiating_occupancy() const { return _initiating_occupancy; } + void init_initiating_occupancy(intx io, intx tr); + public: ConcurrentMarkSweepGeneration(ReservedSpace rs, size_t initial_byte_size, int level, CardTableRS* ct, @@ -1103,7 +1110,7 @@ class ConcurrentMarkSweepGeneration: public CardGeneration { size_t capacity() const; size_t used() const; size_t free() const; - double occupancy() { return ((double)used())/((double)capacity()); } + double occupancy() const { return ((double)used())/((double)capacity()); } size_t contiguous_available() const; size_t unsafe_max_alloc_nogc() const; @@ -1158,8 +1165,8 @@ class ConcurrentMarkSweepGeneration: public CardGeneration { bool younger_handles_promotion_failure) const; bool should_collect(bool full, size_t size, bool tlab); - // XXXPERM - bool shouldConcurrentCollect(double initiatingOccupancy); // XXXPERM + virtual bool should_concurrent_collect() const; + virtual bool is_too_full() const; void collect(bool full, bool clear_all_soft_refs, size_t size, diff --git a/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/concurrentMarkSweepGeneration.inline.hpp b/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/concurrentMarkSweepGeneration.inline.hpp index c151fab332a..8dd2ca4abe4 100644 --- a/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/concurrentMarkSweepGeneration.inline.hpp +++ b/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/concurrentMarkSweepGeneration.inline.hpp @@ -267,7 +267,7 @@ inline bool CMSCollector::is_dead_obj(oop obj) const { (_permGen->cmsSpace()->is_in_reserved(addr) && _permGen->cmsSpace()->block_is_obj(addr)), "must be object"); - return cms_should_unload_classes() && + return should_unload_classes() && _collectorState == Sweeping && !_markBitMap.isMarked(addr); } diff --git a/hotspot/src/share/vm/runtime/globals.hpp b/hotspot/src/share/vm/runtime/globals.hpp index 67cb3285da5..3b09dc5e75d 100644 --- a/hotspot/src/share/vm/runtime/globals.hpp +++ b/hotspot/src/share/vm/runtime/globals.hpp @@ -1319,6 +1319,10 @@ class CommandLineFlags { product(bool, CMSClassUnloadingEnabled, false, \ "Whether class unloading enabled when using CMS GC") \ \ + product(uintx, CMSClassUnloadingMaxInterval, 0, \ + "When CMS class unloading is enabled, the maximum CMS cycle count"\ + " for which classes may not be unloaded") \ + \ product(bool, CMSCompactWhenClearAllSoftRefs, true, \ "Compact when asked to collect CMS gen with clear_all_soft_refs") \ \ @@ -1504,17 +1508,30 @@ class CommandLineFlags { "Percentage of MinHeapFreeRatio in CMS generation that is " \ " allocated before a CMS collection cycle commences") \ \ - product(intx, CMSBootstrapOccupancy, 50, \ + product(intx, CMSTriggerPermRatio, 80, \ + "Percentage of MinHeapFreeRatio in the CMS perm generation that" \ + " is allocated before a CMS collection cycle commences, that " \ + " also collects the perm generation") \ + \ + product(uintx, CMSBootstrapOccupancy, 50, \ "Percentage CMS generation occupancy at which to " \ " initiate CMS collection for bootstrapping collection stats") \ \ product(intx, CMSInitiatingOccupancyFraction, -1, \ "Percentage CMS generation occupancy to start a CMS collection " \ - " cycle (A negative value means that CMSTirggerRatio is used)") \ + " cycle (A negative value means that CMSTriggerRatio is used)") \ + \ + product(intx, CMSInitiatingPermOccupancyFraction, -1, \ + "Percentage CMS perm generation occupancy to start a CMScollection"\ + " cycle (A negative value means that CMSTriggerPermRatio is used)")\ \ product(bool, UseCMSInitiatingOccupancyOnly, false, \ "Only use occupancy as a crierion for starting a CMS collection") \ \ + product(intx, CMSIsTooFullPercentage, 98, \ + "An absolute ceiling above which CMS will always consider the" \ + " perm gen ripe for collection") \ + \ develop(bool, CMSTestInFreeList, false, \ "Check if the coalesced range is already in the " \ "free lists as claimed.") \ From 641bce6847edcb34f889deb6e3431c8333dcd098 Mon Sep 17 00:00:00 2001 From: Tom Rodriguez Date: Tue, 18 Mar 2008 11:17:37 -0700 Subject: [PATCH 058/258] 6666343: Compile::has_loops not always set correctly Compile::has_loops() should be set from inlined methods Reviewed-by: kvn, rasbold --- hotspot/src/share/vm/opto/doCall.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/hotspot/src/share/vm/opto/doCall.cpp b/hotspot/src/share/vm/opto/doCall.cpp index ff85fb643e3..edf71c0caf0 100644 --- a/hotspot/src/share/vm/opto/doCall.cpp +++ b/hotspot/src/share/vm/opto/doCall.cpp @@ -390,6 +390,8 @@ void Parse::do_call() { } if (cg->is_inline()) { + // Accumulate has_loops estimate + C->set_has_loops(C->has_loops() || call_method->has_loops()); C->env()->notice_inlined_method(call_method); } From af4bff1a1e358dd8a232c16e5b19f2c002a38051 Mon Sep 17 00:00:00 2001 From: Mandy Chung Date: Tue, 18 Mar 2008 11:53:15 -0700 Subject: [PATCH 059/258] 6658779: Regression: HotspotDiagnosticMXBean.getDiagnosticOptions() throws NullPointerException Add a null check for the VM option string Reviewed-by: alanb, tbell --- .../share/classes/sun/management/Flag.java | 3 +- .../GetDiagnosticOptions.java | 61 +++++++++++++++++++ 2 files changed, 63 insertions(+), 1 deletion(-) create mode 100644 jdk/test/com/sun/management/HotSpotDiagnosticMXBean/GetDiagnosticOptions.java diff --git a/jdk/src/share/classes/sun/management/Flag.java b/jdk/src/share/classes/sun/management/Flag.java index 510edadd668..d89761cb1f7 100644 --- a/jdk/src/share/classes/sun/management/Flag.java +++ b/jdk/src/share/classes/sun/management/Flag.java @@ -64,7 +64,8 @@ class Flag { } VMOption getVMOption() { - return new VMOption(name, value.toString(), writeable, origin); + String val = value == null ? "" : value.toString(); + return new VMOption(name, val, writeable, origin); } static Flag getFlag(String name) { diff --git a/jdk/test/com/sun/management/HotSpotDiagnosticMXBean/GetDiagnosticOptions.java b/jdk/test/com/sun/management/HotSpotDiagnosticMXBean/GetDiagnosticOptions.java new file mode 100644 index 00000000000..78d57b27578 --- /dev/null +++ b/jdk/test/com/sun/management/HotSpotDiagnosticMXBean/GetDiagnosticOptions.java @@ -0,0 +1,61 @@ +/* + * Copyright 2005 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* + * @test + * @bug 6658779 + * @summary Basic Test for HotSpotDiagnosticMXBean.getDiagnosticOptions() + * @author Daniel Fuchs + * + * @run main GetDiagnosticOptions + */ + +import com.sun.management.HotSpotDiagnosticMXBean; +import com.sun.management.VMOption; +import java.lang.management.ManagementFactory; +import java.util.List; +import javax.management.MBeanServer; + +public class GetDiagnosticOptions { + private static String HOTSPOT_DIAGNOSTIC_MXBEAN_NAME = + "com.sun.management:type=HotSpotDiagnostic"; + + public static void main(String[] args) throws Exception { + HotSpotDiagnosticMXBean mbean = + sun.management.ManagementFactory.getDiagnosticMXBean(); + checkDiagnosticOptions(mbean); + + MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); + mbean = ManagementFactory.newPlatformMXBeanProxy(mbs, + HOTSPOT_DIAGNOSTIC_MXBEAN_NAME, + HotSpotDiagnosticMXBean.class); + checkDiagnosticOptions(mbean); + } + + private static void checkDiagnosticOptions(HotSpotDiagnosticMXBean mbean) { + List options = mbean.getDiagnosticOptions(); + for (VMOption opt : options) { + System.out.println("option: "+opt.getName()+"="+opt.getValue()); + } + } +} From 9c8e97d713af1a018bba764c2fb0e5a03bacb3cf Mon Sep 17 00:00:00 2001 From: Mandy Chung Date: Tue, 18 Mar 2008 12:53:47 -0700 Subject: [PATCH 060/258] 6672804: First line in com/sun/management/package.html is broken Fixed the typo in package.html Reviewed-by: jjh --- jdk/src/share/classes/com/sun/management/package.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jdk/src/share/classes/com/sun/management/package.html b/jdk/src/share/classes/com/sun/management/package.html index 8a1a4a5381c..372d9c4cc54 100644 --- a/jdk/src/share/classes/com/sun/management/package.html +++ b/jdk/src/share/classes/com/sun/management/package.html @@ -1,4 +1,4 @@ -CTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"> + " + e); + } + }, FocusEvent.FOCUS_EVENT_MASK | WindowEvent.WINDOW_FOCUS_EVENT_MASK); + + try { + robot = new Robot(); + } catch (AWTException e) { + throw new RuntimeException("Error: unable to create robot", e); + } + owner.add(fButton); + win.add(wButton); + frame.add(aButton); + + owner.setName("OWNER_FRAME"); + win.setName("OWNED_WINDOW"); + frame.setName("AUX_FRAME"); + + tuneAndShowWindows(new Window[] {owner, win, frame}); + } + + public void start() { + if ("sun.awt.motif.MToolkit".equals(Toolkit.getDefaultToolkit().getClass().getName())) { + Sysout.println("No testing on Motif. Test passed."); + return; + } + + Sysout.println("\nTest started:\n"); + + // Test 1. + + clickOnCheckFocus(wButton); + + clickOnCheckFocus(aButton); + + clickOn(fButton); + if (!testFocused(fButton)) { + throw new TestFailedException("The owner's component [" + fButton + "] couldn't be focused by click"); + } + + // Test 2. + + clickOnCheckFocus(wButton); + + clickOnCheckFocus(aButton); + + fButton.requestFocus(); + realSync(); + if (!testFocused(fButton)) { + throw new TestFailedException("The owner's component [" + fButton + "] couldn't be focused by request"); + } + + // Test 3. + + clickOnCheckFocus(wButton); + + clickOnCheckFocus(aButton); + + clickOnCheckFocus(fButton); + + clickOnCheckFocus(aButton); + + clickOn(owner); + if (!testFocused(fButton)) { + throw new TestFailedException("The owner's component [" + fButton + "] couldn't be focused as the most recent focus owner"); + } + + Sysout.println("Test passed."); + } + + void tuneAndShowWindows(Window[] arr) { + int y = 0; + for (Window w: arr) { + w.setLayout(new FlowLayout()); + w.setBounds(100, y, 400, 150); + w.setBackground(Color.blue); + w.setVisible(true); + y += 200; + realSync(); + } + } + + void clickOn(Component c) { + Sysout.println("Test: clicking " + c); + + Point p = c.getLocationOnScreen(); + Dimension d = c.getSize(); + + if (c instanceof Frame) { + robot.mouseMove(p.x + (int)(d.getWidth()/2), p.y + ((Frame)c).getInsets().top/2); + Sysout.println((p.x + (int)(d.getWidth()/2)) + " " + (p.y + ((Frame)c).getInsets().top/2)); + } else { + robot.mouseMove(p.x + (int)(d.getWidth()/2), p.y + (int)(d.getHeight()/2)); + } + robot.mousePress(InputEvent.BUTTON1_MASK); + robot.delay(100); + robot.mouseRelease(InputEvent.BUTTON1_MASK); + + realSync(); + } + + void clickOnCheckFocus(Component c) { + clickOn(c); + if (!testFocused(c)) { + throw new RuntimeException("Error: [" + c + "] couldn't get focus by click."); + } + } + + boolean testFocused(Component c) { + for (int i=0; i<10; i++) { + if (KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner() == c) { + return true; + } + realSync(); + } + return false; + } + + void realSync() { + ((SunToolkit)Toolkit.getDefaultToolkit()).realSync(); + } + + class TestFailedException extends RuntimeException { + public TestFailedException(String cause) { + super("Test failed. " + cause); + Sysout.println(cause); + } + } +} + +/**************************************************** + Standard Test Machinery + DO NOT modify anything below -- it's a standard + chunk of code whose purpose is to make user + interaction uniform, and thereby make it simpler + to read and understand someone else's test. + ****************************************************/ + +/** + This is part of the standard test machinery. + It creates a dialog (with the instructions), and is the interface + for sending text messages to the user. + To print the instructions, send an array of strings to Sysout.createDialog + WithInstructions method. Put one line of instructions per array entry. + To display a message for the tester to see, simply call Sysout.println + with the string to be displayed. + This mimics System.out.println but works within the test harness as well + as standalone. + */ + +class Sysout +{ + static TestDialog dialog; + + public static void createDialogWithInstructions( String[] instructions ) + { + dialog = new TestDialog( new Frame(), "Instructions" ); + dialog.printInstructions( instructions ); + dialog.setLocation(500,0); + dialog.setVisible(true); + println( "Any messages for the tester will display here." ); + } + + public static void createDialog( ) + { + dialog = new TestDialog( new Frame(), "Instructions" ); + String[] defInstr = { "Instructions will appear here. ", "" } ; + dialog.printInstructions( defInstr ); + dialog.setVisible(true); + println( "Any messages for the tester will display here." ); + } + + + public static void printInstructions( String[] instructions ) + { + dialog.printInstructions( instructions ); + } + + + public static void println( String messageIn ) + { + dialog.displayMessage( messageIn ); + } + +}// Sysout class + +/** + This is part of the standard test machinery. It provides a place for the + test instructions to be displayed, and a place for interactive messages + to the user to be displayed. + To have the test instructions displayed, see Sysout. + To have a message to the user be displayed, see Sysout. + Do not call anything in this dialog directly. + */ +class TestDialog extends Dialog +{ + + TextArea instructionsText; + TextArea messageText; + int maxStringLength = 80; + + //DO NOT call this directly, go through Sysout + public TestDialog( Frame frame, String name ) + { + super( frame, name ); + int scrollBoth = TextArea.SCROLLBARS_BOTH; + instructionsText = new TextArea( "", 15, maxStringLength, scrollBoth ); + add( "North", instructionsText ); + + messageText = new TextArea( "", 5, maxStringLength, scrollBoth ); + add("Center", messageText); + + pack(); + + setVisible(true); + }// TestDialog() + + //DO NOT call this directly, go through Sysout + public void printInstructions( String[] instructions ) + { + //Clear out any current instructions + instructionsText.setText( "" ); + + //Go down array of instruction strings + + String printStr, remainingStr; + for( int i=0; i < instructions.length; i++ ) + { + //chop up each into pieces maxSringLength long + remainingStr = instructions[ i ]; + while( remainingStr.length() > 0 ) + { + //if longer than max then chop off first max chars to print + if( remainingStr.length() >= maxStringLength ) + { + //Try to chop on a word boundary + int posOfSpace = remainingStr. + lastIndexOf( ' ', maxStringLength - 1 ); + + if( posOfSpace <= 0 ) posOfSpace = maxStringLength - 1; + + printStr = remainingStr.substring( 0, posOfSpace + 1 ); + remainingStr = remainingStr.substring( posOfSpace + 1 ); + } + //else just print + else + { + printStr = remainingStr; + remainingStr = ""; + } + + instructionsText.append( printStr + "\n" ); + + }// while + + }// for + + }//printInstructions() + + //DO NOT call this directly, go through Sysout + public void displayMessage( String messageIn ) + { + messageText.append( messageIn + "\n" ); + System.out.println(messageIn); + } + +}// TestDialog class diff --git a/jdk/test/java/awt/Focus/ActualFocusedWindowTest/ActualFocusedWindowRetaining.java b/jdk/test/java/awt/Focus/ActualFocusedWindowTest/ActualFocusedWindowRetaining.java new file mode 100644 index 00000000000..e539e39cd70 --- /dev/null +++ b/jdk/test/java/awt/Focus/ActualFocusedWindowTest/ActualFocusedWindowRetaining.java @@ -0,0 +1,430 @@ +/* + * Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* + @test + @bug 4823903 + @summary Tests actual focused window retaining. + @author Anton Tarasov: area=awt.focus + @run applet ActualFocusedWindowRetaining.html +*/ + +import java.awt.*; +import java.awt.event.*; +import java.lang.reflect.*; +import java.applet.*; + +public class ActualFocusedWindowRetaining extends Applet { + public static Frame frame = new Frame("Other Frame"); + public static Frame owner = new Frame("Test Frame"); + public static Button otherButton1 = new Button("Other Button 1"); + public static Button otherButton2 = new Button("Other Button 2"); + public static Button otherButton3 = new Button("Other Button 3"); + public static Button testButton1 = new Button("Test Button 1"); + public static Button testButton2 = new Button("Test Button 2"); + public static Button testButton3 = new Button("Test Button 3"); + public static Window window1 = new TestWindow(owner, otherButton2, testButton2, 800, 200); + public static Window window2 = new TestWindow(owner, otherButton3, testButton3, 800, 300); + public static int step; + public static Robot robot; + + public static void main(String[] args) { + ActualFocusedWindowRetaining a = new ActualFocusedWindowRetaining(); + a.init(); + a.start(); + } + + public void init() + { + //Create instructions for the user here, as well as set up + // the environment -- set the layout manager, add buttons, + // etc. + this.setLayout (new BorderLayout ()); + + String[] instructions = + { + "This is an AUTOMATIC test", + "simply wait until it is done" + }; + Sysout.createDialogWithInstructions( instructions ); + } + + public void start () + { + if (Toolkit.getDefaultToolkit().getClass() + .getName().equals("sun.awt.motif.MToolkit")) { + Sysout.println("No testing on Motif."); + return; + } + + try { + robot = new Robot(); + } catch (AWTException e) { + throw new RuntimeException("Error: unable to create robot", e); + } + + Toolkit.getDefaultToolkit().addAWTEventListener(new AWTEventListener() { + public void eventDispatched(AWTEvent e) { + Object src = e.getSource(); + Class cls = src.getClass(); + + if (cls == TestWindow.class) { + Sysout.println(e.paramString() + " on <" + (src == window1 ? "Window 1" : "Window 2") + ">"); + } else if (cls == Frame.class) { + Sysout.println(e.paramString() + " on <" + ((Frame)src).getTitle() + ">"); + } else if (cls == Button.class) { + Sysout.println(e.paramString() + " on <" + ((Button)src).getLabel() + ">"); + } else { + Sysout.println(e.paramString() + " on "); + } + } + }, AWTEvent.WINDOW_EVENT_MASK | AWTEvent.WINDOW_FOCUS_EVENT_MASK | AWTEvent.FOCUS_EVENT_MASK); + + setSize (200,200); + setVisible(true); + validate(); + + frame.setSize(new Dimension(400, 100)); + frame.setLocation(800, 400); + frame.setVisible(true); + frame.toFront(); + + owner.setLayout(new FlowLayout()); + owner.add(testButton1); + owner.add(otherButton1); + owner.pack(); + owner.setLocation(800, 100); + owner.setSize(new Dimension(400, 100)); + owner.setVisible(true); + owner.toFront(); + waitTillShown(owner); + + window1.setVisible(true); + window2.setVisible(true); + window1.toFront(); + window2.toFront(); + // Wait longer... + waitTillShown(window1); + waitTillShown(window2); + + test(); + + frame.dispose(); + owner.dispose(); + } + + public void test() { + + Button[] butArr = new Button[] {testButton3, testButton2, testButton1}; + Window[] winArr = new Window[] {window2, window1, owner}; + + step = 1; + for (int i = 0; i < 3; i++) { + clickOnCheckFocusOwner(butArr[i]); + clickOnCheckFocusedWindow(frame); + clickOn(owner); + if (!checkFocusedWindow(winArr[i])) { + stopTest("Test failed: actual focused window didn't get a focus"); + } + if (!checkFocusOwner(butArr[i])) { + stopTest("Test failed: actual focus owner didn't get a focus"); + } + step++; + } + + step = 4; + clickOnCheckFocusOwner(testButton3); + clickOnCheckFocusOwner(testButton1); + clickOnCheckFocusedWindow(frame); + clickOn(owner); + if (!checkFocusedWindow(owner)) { + stopTest("Test failed: actual focused window didn't get a focus"); + } + if (!checkFocusOwner(testButton1)) { + stopTest("Test failed: actual focus owner didn't get a focus"); + } + + step = 5; + clickOnCheckFocusOwner(testButton3); + clickOnCheckFocusOwner(testButton2); + clickOnCheckFocusedWindow(frame); + clickOn(owner); + if (!checkFocusedWindow(window1)) { + stopTest("Test failed: actual focused window didn't get a focus"); + } + if (!checkFocusOwner(testButton2)) { + stopTest("Test failed: actual focus owner didn't get a focus"); + } + + step = 6; + clickOnCheckFocusOwner(testButton1); + clickOnCheckFocusOwner(testButton2); + clickOnCheckFocusedWindow(frame); + clickOn(owner); + if (!checkFocusedWindow(window1)) { + stopTest("Test failed: actual focused window didn't get a focus"); + } + if (!checkFocusOwner(testButton2)) { + stopTest("Test failed: actual focus owner didn't get a focus"); + } + + step = 7; + clickOnCheckFocusOwner(testButton1); + clickOnCheckFocusOwner(testButton2); + clickOnCheckFocusedWindow(frame); + window1.setVisible(false); + clickOn(owner); + if (!checkFocusedWindow(owner)) { + stopTest("Test failed: actual focused window didn't get a focus"); + } + if (!checkFocusOwner(testButton1)) { + stopTest("Test failed: actual focus owner didn't get a focus"); + } + + step = 8; + window1.setVisible(true); + waitTillShown(window1); + clickOnCheckFocusOwner(testButton2); + clickOnCheckFocusedWindow(frame); + clickOn(owner); + if (!checkFocusedWindow(window1)) { + stopTest("Test failed: actual focused window didn't get a focus"); + } + if (!checkFocusOwner(testButton2)) { + stopTest("Test failed: actual focus owner didn't get a focus"); + } + } + + boolean checkFocusOwner(Component comp) { + return (comp == KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner()); + } + + boolean checkFocusedWindow(Window win) { + return (win == KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusedWindow()); + } + + void waitTillShown(Component c) { + ((sun.awt.SunToolkit) Toolkit.getDefaultToolkit()).realSync(); + } + + void clickOnCheckFocusOwner(Component c) { + clickOn(c); + if (!checkFocusOwner(c)) { + stopTest("Error: can't bring a focus on Component by clicking on it"); + } + } + + void clickOnCheckFocusedWindow(Frame f) { + clickOn(f); + if (!checkFocusedWindow(f)) { + stopTest("Error: can't bring a focus on Frame by clicking on it"); + } + } + + void clickOn(Component c) + { + Point p = c.getLocationOnScreen(); + Dimension d = c.getSize(); + + if (c instanceof Frame) { + robot.mouseMove(p.x + (int)(d.getWidth()/2), p.y + ((Frame)c).getInsets().top/2); + } else { + robot.mouseMove(p.x + (int)(d.getWidth()/2), p.y + (int)(d.getHeight()/2)); + } + + pause(100); + robot.mousePress(InputEvent.BUTTON1_MASK); + pause(100); + robot.mouseRelease(InputEvent.BUTTON1_MASK); + + waitForIdle(); + } + + void waitForIdle() { + ((sun.awt.SunToolkit) Toolkit.getDefaultToolkit()).realSync(); + } + + void pause(int msec) { + try { + Thread.sleep(msec); + } catch (InterruptedException e) { + Sysout.println("pause: non-fatal exception caught:"); + e.printStackTrace(); + } + } + + void stopTest(String msg) { + throw new RuntimeException(new String("Step " + step + ": " + msg)); + } +} + +class TestWindow extends Window { + TestWindow(Frame owner, Button otherButton, Button testButton, int x, int y) { + super(owner); + + setLayout(new FlowLayout()); + setLocation(x, y); + add(testButton); + add(otherButton); + pack(); + setBackground(Color.green); + } +} + + +/**************************************************** + Standard Test Machinery + DO NOT modify anything below -- it's a standard + chunk of code whose purpose is to make user + interaction uniform, and thereby make it simpler + to read and understand someone else's test. + ****************************************************/ + +/** + This is part of the standard test machinery. + It creates a dialog (with the instructions), and is the interface + for sending text messages to the user. + To print the instructions, send an array of strings to Sysout.createDialog + WithInstructions method. Put one line of instructions per array entry. + To display a message for the tester to see, simply call Sysout.println + with the string to be displayed. + This mimics System.out.println but works within the test harness as well + as standalone. + */ + +class Sysout +{ + private static TestDialog dialog; + + public static void createDialogWithInstructions( String[] instructions ) + { + dialog = new TestDialog( new Frame(), "Instructions" ); + dialog.printInstructions( instructions ); + dialog.setVisible(true); + println( "Any messages for the tester will display here." ); + } + + public static void createDialog( ) + { + dialog = new TestDialog( new Frame(), "Instructions" ); + String[] defInstr = { "Instructions will appear here. ", "" } ; + dialog.printInstructions( defInstr ); + dialog.setVisible(true); + println( "Any messages for the tester will display here." ); + } + + + public static void printInstructions( String[] instructions ) + { + dialog.printInstructions( instructions ); + } + + + public static void println( String messageIn ) + { + dialog.displayMessage( messageIn ); + } + +}// Sysout class + +/** + This is part of the standard test machinery. It provides a place for the + test instructions to be displayed, and a place for interactive messages + to the user to be displayed. + To have the test instructions displayed, see Sysout. + To have a message to the user be displayed, see Sysout. + Do not call anything in this dialog directly. + */ +class TestDialog extends Dialog +{ + + TextArea instructionsText; + TextArea messageText; + int maxStringLength = 80; + + //DO NOT call this directly, go through Sysout + public TestDialog( Frame frame, String name ) + { + super( frame, name ); + int scrollBoth = TextArea.SCROLLBARS_BOTH; + instructionsText = new TextArea( "", 15, maxStringLength, scrollBoth ); + add( "North", instructionsText ); + + messageText = new TextArea( "", 5, maxStringLength, scrollBoth ); + add("Center", messageText); + + pack(); + + setVisible(true); + }// TestDialog() + + //DO NOT call this directly, go through Sysout + public void printInstructions( String[] instructions ) + { + //Clear out any current instructions + instructionsText.setText( "" ); + + //Go down array of instruction strings + + String printStr, remainingStr; + for( int i=0; i < instructions.length; i++ ) + { + //chop up each into pieces maxSringLength long + remainingStr = instructions[ i ]; + while( remainingStr.length() > 0 ) + { + //if longer than max then chop off first max chars to print + if( remainingStr.length() >= maxStringLength ) + { + //Try to chop on a word boundary + int posOfSpace = remainingStr. + lastIndexOf( ' ', maxStringLength - 1 ); + + if( posOfSpace <= 0 ) posOfSpace = maxStringLength - 1; + + printStr = remainingStr.substring( 0, posOfSpace + 1 ); + remainingStr = remainingStr.substring( posOfSpace + 1 ); + } + //else just print + else + { + printStr = remainingStr; + remainingStr = ""; + } + + instructionsText.append( printStr + "\n" ); + + }// while + + }// for + + }//printInstructions() + + //DO NOT call this directly, go through Sysout + public void displayMessage( String messageIn ) + { + messageText.append( messageIn + "\n" ); + System.out.println(messageIn); + } + +}// TestDialog class diff --git a/jdk/test/java/awt/Focus/AppletInitialFocusTest/AppletInitialFocusTest.html b/jdk/test/java/awt/Focus/AppletInitialFocusTest/AppletInitialFocusTest.html new file mode 100644 index 00000000000..3d3d0c81a62 --- /dev/null +++ b/jdk/test/java/awt/Focus/AppletInitialFocusTest/AppletInitialFocusTest.html @@ -0,0 +1,22 @@ + + + + AppletInitialFocusTest + + + +

AppletInitialFocusTest
Bug ID: 4041703

+ +

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

+ + + + + diff --git a/jdk/test/java/awt/Focus/AppletInitialFocusTest/AppletInitialFocusTest.java b/jdk/test/java/awt/Focus/AppletInitialFocusTest/AppletInitialFocusTest.java new file mode 100644 index 00000000000..e34e6e123a5 --- /dev/null +++ b/jdk/test/java/awt/Focus/AppletInitialFocusTest/AppletInitialFocusTest.java @@ -0,0 +1,103 @@ +/* + * Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* + test + @bug 4041703 4096228 4025223 4260929 + @summary Ensures that appletviewer sets a reasonable default focus + for an Applet on start + @author das area=appletviewer + @run shell AppletInitialFocusTest.sh +*/ + +import java.applet.Applet; +import java.awt.*; +import java.awt.event.*; + +class MyKeyboardFocusManager extends DefaultKeyboardFocusManager { + public Window getGlobalFocusedWindow() { + return super.getGlobalFocusedWindow(); + } +} + +public class AppletInitialFocusTest extends Applet { + + Window window; + Button button = new Button("Button"); + MyKeyboardFocusManager manager = new MyKeyboardFocusManager(); + + Object lock = new Object(); + + public void init() { + KeyboardFocusManager.setCurrentKeyboardFocusManager(manager); + + Component parent = this; + while (parent != null && !(parent instanceof Window)) { + parent = parent.getParent(); + } + /* + * This applet is designed to be run only with appletviewer, + * so there always should be a toplevel frame. + */ + if (parent == null) { + synchronized (lock) { + System.err.println("appletviewer not running"); + System.exit(3); + } + } + window = (Window)parent; + + button.addFocusListener(new FocusAdapter() { + public void focusGained(FocusEvent e) { + synchronized (lock) { + System.err.println("passed"); + System.exit(0); + } + } + }); + add(button); + } + + public void start() { + Thread thread = new Thread(new Runnable() { + public void run() { + try { + Thread.sleep(1000); + synchronized (lock) { + Window focused = manager.getGlobalFocusedWindow(); + if (window == focused) { + System.err.println("failed"); + System.exit(2); + } else { + System.err.println("window never activated"); + System.err.println(focused); + System.exit(0); + } + } + } catch(InterruptedException e) { + } + } + }); + thread.start(); + } +} diff --git a/jdk/test/java/awt/Focus/AppletInitialFocusTest/AppletInitialFocusTest1.html b/jdk/test/java/awt/Focus/AppletInitialFocusTest/AppletInitialFocusTest1.html new file mode 100644 index 00000000000..cdbcdb48021 --- /dev/null +++ b/jdk/test/java/awt/Focus/AppletInitialFocusTest/AppletInitialFocusTest1.html @@ -0,0 +1,22 @@ + + + + AppletInitialFocusTest1 + + + +

AppletInitialFocusTest1
Bug ID: 4517274

+ +

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

+ + + + + diff --git a/jdk/test/java/awt/Focus/AppletInitialFocusTest/AppletInitialFocusTest1.java b/jdk/test/java/awt/Focus/AppletInitialFocusTest/AppletInitialFocusTest1.java new file mode 100644 index 00000000000..b72c1c99758 --- /dev/null +++ b/jdk/test/java/awt/Focus/AppletInitialFocusTest/AppletInitialFocusTest1.java @@ -0,0 +1,94 @@ +/* + * Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* + test + @bug 4411534 4517274 + @summary ensures that user's requestFocus() during applet initialization + is not ignored. + @author prs area=appletviewer + @run shell AppletInitialFocusTest1.sh +*/ + +import java.applet.Applet; +import java.awt.*; +import java.awt.event.*; + +public class AppletInitialFocusTest1 extends Applet implements FocusListener { + + Button button1 = new Button("Button1"); + Button button2 = new Button("Button2"); + + Object lock = new Object(); + + public void init() { + + Component parent = this; + while (parent != null && !(parent instanceof Window)) { + parent = parent.getParent(); + } + /* + * This applet is designed to be run only with appletviewer, + * so there always should be a toplevel frame. + */ + if (parent == null) { + synchronized (lock) { + System.err.println("appletviewer not running"); + System.exit(3); + } + } + button1.addFocusListener(this); + button2.addFocusListener(this); + add(button1); + add(button2); + button2.requestFocus(); + } + + public void focusGained(FocusEvent e) { + if (e.getSource() == button1) { + synchronized (lock) { + System.err.println("failed: focus on the wrong button"); + System.exit(2); + } + } + } + + public void focusLost(FocusEvent e) { + } + + public void start() { + Thread thread = new Thread(new Runnable() { + public void run() { + try { + Thread.sleep(10000); + synchronized (lock) { + System.err.println("passed"); + System.exit(0); + } + } catch(InterruptedException e) { + } + } + }); + thread.start(); + } +} diff --git a/jdk/test/java/awt/Focus/FrameJumpingToMouse/FrameJumpingToMouse.java b/jdk/test/java/awt/Focus/FrameJumpingToMouse/FrameJumpingToMouse.java new file mode 100644 index 00000000000..54928d2988b --- /dev/null +++ b/jdk/test/java/awt/Focus/FrameJumpingToMouse/FrameJumpingToMouse.java @@ -0,0 +1,259 @@ +/* + * Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* +test +@bug 4752312 +@summary Tests that after moving non-focusable window it ungrabs mouse pointer +@author dom@sparc.spb.su: area=awt.focus +@run applet FrameJumpingToMouse.html +*/ + +// Note there is no @ in front of test above. This is so that the +// harness will not mistake this file as a test file. It should +// only see the html file as a test file. (the harness runs all +// valid test files, so it would run this test twice if this file +// were valid as well as the html file.) +// Also, note the area= after Your Name in the author tag. Here, you +// should put which functional area the test falls in. See the +// AWT-core home page -> test areas and/or -> AWT team for a list of +// areas. +// Note also the 'FrameJumpingToMouse.html' in the run tag. This should +// be changed to the name of the test. + + +/** + * FrameJumpingToMouse.java + * + * summary: + */ + +import java.applet.Applet; +import java.awt.*; +import java.awt.event.*; +import javax.swing.JFrame; + +//Automated tests should run as applet tests if possible because they +// get their environments cleaned up, including AWT threads, any +// test created threads, and any system resources used by the test +// such as file descriptors. (This is normally not a problem as +// main tests usually run in a separate VM, however on some platforms +// such as the Mac, separate VMs are not possible and non-applet +// tests will cause problems). Also, you don't have to worry about +// synchronisation stuff in Applet tests they way you do in main +// tests... + + +public class FrameJumpingToMouse extends Applet +{ + //Declare things used in the test, like buttons and labels here + JFrame frame = new JFrame("Test jumping frame"); + Robot robot = null; + public void init() + { + //Create instructions for the user here, as well as set up + // the environment -- set the layout manager, add buttons, + // etc. + + this.setLayout (new BorderLayout ()); + + frame.setFocusableWindowState(false); + frame.setBounds(100, 100, 100, 100); + }//End init() + + public void start () + { + //Get things going. Request focus, set size, et cetera + setSize (200,200); + setVisible(true); + validate(); + + try { + robot = new Robot(); + } catch (Exception e) { + throw new RuntimeException("Can't create robot"); + } + + frame.setVisible(true); + + robot.delay(1000); + + Point frameLoc = frame.getLocationOnScreen(); + robot.mouseMove(frameLoc.x+frame.getWidth()/4, frameLoc.y+frame.getInsets().top/2); + robot.mousePress(InputEvent.BUTTON1_MASK); + robot.mouseMove(frameLoc.x+100, frameLoc.y+50); + robot.mouseRelease(InputEvent.BUTTON1_MASK); + + Toolkit.getDefaultToolkit().sync(); + robot.waitForIdle(); + frameLoc = frame.getLocation(); + + robot.mouseMove(frameLoc.x+frame.getWidth()/2, frameLoc.y+frame.getHeight()/2); + + Toolkit.getDefaultToolkit().sync(); + robot.waitForIdle(); + + if (!(frame.getLocation().equals(frameLoc))) { + throw new RuntimeException("Frame is moving to mouse with grab"); + } + }// start() + +}// class FrameJumpingToMouse + + +/**************************************************** + Standard Test Machinery + DO NOT modify anything below -- it's a standard + chunk of code whose purpose is to make user + interaction uniform, and thereby make it simpler + to read and understand someone else's test. + ****************************************************/ + +/** + This is part of the standard test machinery. + It creates a dialog (with the instructions), and is the interface + for sending text messages to the user. + To print the instructions, send an array of strings to Sysout.createDialog + WithInstructions method. Put one line of instructions per array entry. + To display a message for the tester to see, simply call Sysout.println + with the string to be displayed. + This mimics System.out.println but works within the test harness as well + as standalone. + */ + +class Sysout +{ + private static TestDialog dialog; + + public static void createDialogWithInstructions( String[] instructions ) + { + dialog = new TestDialog( new Frame(), "Instructions" ); + dialog.printInstructions( instructions ); + dialog.setVisible(true); + println( "Any messages for the tester will display here." ); + } + + public static void createDialog( ) + { + dialog = new TestDialog( new Frame(), "Instructions" ); + String[] defInstr = { "Instructions will appear here. ", "" } ; + dialog.printInstructions( defInstr ); + dialog.setVisible(true); + println( "Any messages for the tester will display here." ); + } + + + public static void printInstructions( String[] instructions ) + { + dialog.printInstructions( instructions ); + } + + + public static void println( String messageIn ) + { + dialog.displayMessage( messageIn ); + } + +}// Sysout class + +/** + This is part of the standard test machinery. It provides a place for the + test instructions to be displayed, and a place for interactive messages + to the user to be displayed. + To have the test instructions displayed, see Sysout. + To have a message to the user be displayed, see Sysout. + Do not call anything in this dialog directly. + */ +class TestDialog extends Dialog +{ + + TextArea instructionsText; + TextArea messageText; + int maxStringLength = 80; + + //DO NOT call this directly, go through Sysout + public TestDialog( Frame frame, String name ) + { + super( frame, name ); + int scrollBoth = TextArea.SCROLLBARS_BOTH; + instructionsText = new TextArea( "", 15, maxStringLength, scrollBoth ); + add( "North", instructionsText ); + + messageText = new TextArea( "", 5, maxStringLength, scrollBoth ); + add("Center", messageText); + + pack(); + + show(); + }// TestDialog() + + //DO NOT call this directly, go through Sysout + public void printInstructions( String[] instructions ) + { + //Clear out any current instructions + instructionsText.setText( "" ); + + //Go down array of instruction strings + + String printStr, remainingStr; + for( int i=0; i < instructions.length; i++ ) + { + //chop up each into pieces maxSringLength long + remainingStr = instructions[ i ]; + while( remainingStr.length() > 0 ) + { + //if longer than max then chop off first max chars to print + if( remainingStr.length() >= maxStringLength ) + { + //Try to chop on a word boundary + int posOfSpace = remainingStr. + lastIndexOf( ' ', maxStringLength - 1 ); + + if( posOfSpace <= 0 ) posOfSpace = maxStringLength - 1; + + printStr = remainingStr.substring( 0, posOfSpace + 1 ); + remainingStr = remainingStr.substring( posOfSpace + 1 ); + } + //else just print + else + { + printStr = remainingStr; + remainingStr = ""; + } + + instructionsText.append( printStr + "\n" ); + + }// while + + }// for + + }//printInstructions() + + //DO NOT call this directly, go through Sysout + public void displayMessage( String messageIn ) + { + messageText.append( messageIn + "\n" ); + System.out.println(messageIn); + } + +}// TestDialog class diff --git a/jdk/test/java/awt/Focus/NonFocusableWindowTest/NonfocusableOwnerTest.java b/jdk/test/java/awt/Focus/NonFocusableWindowTest/NonfocusableOwnerTest.java new file mode 100644 index 00000000000..087eba9dea5 --- /dev/null +++ b/jdk/test/java/awt/Focus/NonFocusableWindowTest/NonfocusableOwnerTest.java @@ -0,0 +1,352 @@ +/* + * Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* + @test + @bug 6182359 + @summary Tests that Window having non-focusable owner can't be a focus owner. + @author Anton Tarasov: area=awt.focus + @run applet NonfocusableOwnerTest.html +*/ + +import java.awt.*; +import java.awt.event.*; +import java.applet.Applet; +import java.lang.reflect.*; +import java.io.*; + +public class NonfocusableOwnerTest extends Applet { + Robot robot; + Frame frame; + Dialog dialog; + Window window1; + Window window2; + Button button = new Button("button"); +// PrintStream Sysout = System.out; + + public static void main(String[] args) { + NonfocusableOwnerTest test = new NonfocusableOwnerTest(); + test.init(); + test.start(); + } + + public void init() { + try { + robot = new Robot(); + } catch (AWTException e) { + throw new RuntimeException("Error: unable to create robot", e); + } + // Create instructions for the user here, as well as set up + // the environment -- set the layout manager, add buttons, + // etc. + this.setLayout (new BorderLayout ()); + } + + public void start() { + Toolkit.getDefaultToolkit().addAWTEventListener(new AWTEventListener() { + public void eventDispatched(AWTEvent e) { + Sysout.println(e.toString()); + } + }, FocusEvent.FOCUS_EVENT_MASK | WindowEvent.WINDOW_FOCUS_EVENT_MASK | WindowEvent.WINDOW_EVENT_MASK); + + frame = new Frame("Frame"); + frame.setName("Frame-owner"); + dialog = new Dialog(frame, "Dialog"); + dialog.setName("Dialog-owner"); + + window1 = new Window(frame); + window1.setName("1st child"); + window2 = new Window(window1); + window2.setName("2nd child"); + + test1(frame, window1); + test2(frame, window1, window2); + test3(frame, window1, window2); + + window1 = new Window(dialog); + window1.setName("1st child"); + window2 = new Window(window1); + window2.setName("2nd child"); + + test1(dialog, window1); + test2(dialog, window1, window2); + test3(dialog, window1, window2); + + Sysout.println("Test passed."); + } + + void test1(Window owner, Window child) { + Sysout.println("* * * STAGE 1 * * *\nowner=" + owner); + + owner.setFocusableWindowState(false); + owner.setSize(100, 100); + owner.setVisible(true); + + child.add(button); + child.setBounds(0, 300, 100, 100); + child.setVisible(true); + + waitTillShown(child); + + clickOn(button); + if (button == KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner()) { + throw new RuntimeException("Test Failed."); + } + owner.dispose(); + child.dispose(); + } + + void test2(Window owner, Window child1, Window child2) { + Sysout.println("* * * STAGE 2 * * *\nowner=" + owner); + + owner.setFocusableWindowState(false); + owner.setSize(100, 100); + owner.setVisible(true); + + child1.setFocusableWindowState(true); + child1.setBounds(0, 300, 100, 100); + child1.setVisible(true); + + child2.add(button); + child2.setBounds(0, 500, 100, 100); + child2.setVisible(true); + + clickOn(button); + if (button == KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner()) { + throw new RuntimeException("Test failed."); + } + owner.dispose(); + child1.dispose(); + child2.dispose(); + } + + void test3(Window owner, Window child1, Window child2) { + Sysout.println("* * * STAGE 3 * * *\nowner=" + owner); + + owner.setFocusableWindowState(true); + owner.setSize(100, 100); + owner.setVisible(true); + + child1.setFocusableWindowState(false); + child1.setBounds(0, 300, 100, 100); + child1.setVisible(true); + + child2.setFocusableWindowState(true); + child2.add(button); + child2.setBounds(0, 500, 100, 100); + child2.setVisible(true); + + clickOn(button); + + System.err.println("focus owner: " + KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner()); + if (button != KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner()) { + throw new RuntimeException("Test failed."); + } + owner.dispose(); + child1.dispose(); + child2.dispose(); + } + + void clickOn(Component c) { + Point p = c.getLocationOnScreen(); + Dimension d = c.getSize(); + + Sysout.println("Clicking " + c); + + if (c instanceof Frame) { + robot.mouseMove(p.x + (int)(d.getWidth()/2), p.y + ((Frame)c).getInsets().top/2); + } else { + robot.mouseMove(p.x + (int)(d.getWidth()/2), p.y + (int)(d.getHeight()/2)); + } + robot.mousePress(InputEvent.BUTTON1_MASK); + robot.mouseRelease(InputEvent.BUTTON1_MASK); + waitForIdle(); + } + + void waitTillShown(Component c) { + while (true) { + try { + Thread.sleep(100); + c.getLocationOnScreen(); + break; + } catch (InterruptedException e) { + throw new RuntimeException(e); + } catch (IllegalComponentStateException e) {} + } + } + void waitForIdle() { + try { + Toolkit.getDefaultToolkit().sync(); + sun.awt.SunToolkit.flushPendingEvents(); + EventQueue.invokeAndWait( new Runnable() { + public void run() {} // Dummy implementation + }); + } catch(InterruptedException ie) { + Sysout.println("waitForIdle, non-fatal exception caught:"); + ie.printStackTrace(); + } catch(InvocationTargetException ite) { + Sysout.println("waitForIdle, non-fatal exception caught:"); + ite.printStackTrace(); + } + + // wait longer... + robot.delay(200); + } +} + +/**************************************************** + Standard Test Machinery + DO NOT modify anything below -- it's a standard + chunk of code whose purpose is to make user + interaction uniform, and thereby make it simpler + to read and understand someone else's test. + ****************************************************/ + +/** + This is part of the standard test machinery. + It creates a dialog (with the instructions), and is the interface + for sending text messages to the user. + To print the instructions, send an array of strings to Sysout.createDialog + WithInstructions method. Put one line of instructions per array entry. + To display a message for the tester to see, simply call Sysout.println + with the string to be displayed. + This mimics System.out.println but works within the test harness as well + as standalone. + */ + +class Sysout +{ + static TestDialog dialog; + + public static void createDialogWithInstructions( String[] instructions ) + { + dialog = new TestDialog( new Frame(), "Instructions" ); + dialog.printInstructions( instructions ); + dialog.setVisible(true); + println( "Any messages for the tester will display here." ); + } + + public static void createDialog( ) + { + dialog = new TestDialog( new Frame(), "Instructions" ); + String[] defInstr = { "Instructions will appear here. ", "" } ; + dialog.printInstructions( defInstr ); + dialog.setVisible(true); + println( "Any messages for the tester will display here." ); + } + + + public static void printInstructions( String[] instructions ) + { + dialog.printInstructions( instructions ); + } + + + public static void println( String messageIn ) + { + System.err.println(messageIn); + } + +}// Sysout class + +/** + This is part of the standard test machinery. It provides a place for the + test instructions to be displayed, and a place for interactive messages + to the user to be displayed. + To have the test instructions displayed, see Sysout. + To have a message to the user be displayed, see Sysout. + Do not call anything in this dialog directly. + */ +class TestDialog extends Dialog +{ + + TextArea instructionsText; + TextArea messageText; + int maxStringLength = 80; + + //DO NOT call this directly, go through Sysout + public TestDialog( Frame frame, String name ) + { + super( frame, name ); + int scrollBoth = TextArea.SCROLLBARS_BOTH; + instructionsText = new TextArea( "", 15, maxStringLength, scrollBoth ); + add( "North", instructionsText ); + + messageText = new TextArea( "", 5, maxStringLength, scrollBoth ); + add("Center", messageText); + + pack(); + + setVisible(true); + }// TestDialog() + + //DO NOT call this directly, go through Sysout + public void printInstructions( String[] instructions ) + { + //Clear out any current instructions + instructionsText.setText( "" ); + + //Go down array of instruction strings + + String printStr, remainingStr; + for( int i=0; i < instructions.length; i++ ) + { + //chop up each into pieces maxSringLength long + remainingStr = instructions[ i ]; + while( remainingStr.length() > 0 ) + { + //if longer than max then chop off first max chars to print + if( remainingStr.length() >= maxStringLength ) + { + //Try to chop on a word boundary + int posOfSpace = remainingStr. + lastIndexOf( ' ', maxStringLength - 1 ); + + if( posOfSpace <= 0 ) posOfSpace = maxStringLength - 1; + + printStr = remainingStr.substring( 0, posOfSpace + 1 ); + remainingStr = remainingStr.substring( posOfSpace + 1 ); + } + //else just print + else + { + printStr = remainingStr; + remainingStr = ""; + } + + instructionsText.append( printStr + "\n" ); + + }// while + + }// for + + }//printInstructions() + + //DO NOT call this directly, go through Sysout + public void displayMessage( String messageIn ) + { + messageText.append( messageIn + "\n" ); + System.out.println(messageIn); + } + +}// TestDialog class diff --git a/jdk/test/java/awt/Focus/NonFocusableWindowTest/Test.java b/jdk/test/java/awt/Focus/NonFocusableWindowTest/Test.java new file mode 100644 index 00000000000..e3e7d0645a8 --- /dev/null +++ b/jdk/test/java/awt/Focus/NonFocusableWindowTest/Test.java @@ -0,0 +1,417 @@ +/* + * Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ +/* + @test + @bug 4452384 + @summary Tests that non-focusable windows doesn't generate any focus events when accessed. + @author dom: area=awt.focus + @run main Test +*/ + +import java.awt.*; +import java.awt.event.*; +import java.util.*; + +public class Test extends Frame { + public static final int DEF_WIDTH = 400, + DEF_HEIGHT = 300, + DEF_TOP = 1, + DEF_LEFT = 100, + DEF_ROW = 0, + DEF_COL = 0; + static boolean automatic = true; + static Window[] windows; + static Frame main_frame, jumpingFrame; + static Button focus_button; + static Robot robot; + static void pause(int timeout) { + Toolkit.getDefaultToolkit().sync(); + robot.waitForIdle(); + robot.delay(100); + } + static GlobalListener listener; + public static void main(String[] args) { + + listener = new GlobalListener(); + Toolkit.getDefaultToolkit().addAWTEventListener(listener, + AWTEvent.FOCUS_EVENT_MASK | + AWTEvent.WINDOW_EVENT_MASK); + try{ + robot = new Robot(); + } catch(Exception e) {} + // Create several pairs - focusable Frame with focusable component(button) and non-focusable: + // window, resizable frame, non-resizable frame, dialog, non-resiable dialog + main_frame = new Frame("focusable frame"); + focus_button = new Button("button to focus"); + main_frame.add(focus_button); + main_frame.pack(); + main_frame.setVisible(true); + main_frame.setLocation(10, 600); + main_frame.addWindowListener(new WindowAdapter() { + public void windowClosing(WindowEvent e) { + listener.report(); + System.exit(0); + } + }); + + jumpingFrame = new Frame("Jumping frame"); + jumpingFrame.setBounds(DEF_LEFT, DEF_TOP, DEF_WIDTH, DEF_HEIGHT); + + windows = new Window[7]; + windows[0] = new TestWindow(0, 0, false, main_frame); + //windows[1] = new TestWindow(2, 1, true, main_frame); + windows[2] = new Test(1, 0, false, true); + windows[3] = new Test(2, 0, false, false); + //windows[4] = new Test(3, 0, true, true); + windows[5] = new TestDialog(0, 1, false, true, main_frame); + windows[6] = new TestDialog(1, 1, false, false, main_frame); + if (!automatic) { + int windowInd; + for (windowInd = 0; windowInd < windows.length; windowInd++) { + if (windows[windowInd] != null) { + windows[windowInd].setVisible(true); + } + } + } + // Run the test + // 1. Click on all controls, check for no focus events for non-focusable, right focus events for focusable + // 2. Perform some action with control, check if it works + if (automatic) { + int windowInd; + for (windowInd = 0; windowInd < windows.length; windowInd++) { + if (windows[windowInd] != null) { + windows[windowInd].setVisible(true); + focus_button.requestFocus(); + pause(1000); + + // Verify that click on non-focusable window causes no focus lost on active window + performFocusClick(windows[windowInd]); + focus_button.requestFocus(); + pause(500); + performActionClick(windows[windowInd]); + + // Verify that toFront, toBack doesn't cause non-focusable window to become active + jumpingFrame.setVisible(true); + pause(1000); + jumpingFrame.toBack(); + pause(500); + jumpingFrame.toFront(); + pause(500); + windows[windowInd].toBack(); + pause(500); + windows[windowInd].toFront(); + pause(500); + + // Verify that iconifiyng/deiconfiying and + // zooming/unzooming doesn't cause non-focusable + // window to become active + if (windows[windowInd] instanceof Frame) { + Frame toTest = (Frame)windows[windowInd]; + // Deiconification currently doesn't work! +// toTest.setExtendedState(Frame.ICONIFIED); +// pause(500); +// toTest.setExtendedState(Frame.NORMAL); + pause(500); + toTest.setExtendedState(Frame.MAXIMIZED_BOTH); + pause(500); + toTest.setExtendedState(Frame.NORMAL); + } + + windows[windowInd].dispose(); + jumpingFrame.dispose(); + } + } + pause(1000); + System.err.println("Test finished."); + if (!listener.report()) { + throw new RuntimeException("Test Failed. See error stream output for details"); + } + } + } + static void performFocusClick(Window parent) { + if (parent == null) { + return; + } + for (int compInd = 0; compInd < parent.getComponentCount(); compInd++) { + Component child = parent.getComponent(compInd); + if (child instanceof TestPanel) { + TestPanel pan = (TestPanel)child; + pan.performFocusClicks(robot); + pause(100); + } + } + } + static void performActionClick(Window parent) { + if (parent == null) { + return; + } + for (int compInd = 0; compInd < parent.getComponentCount(); compInd++) { + Component child = parent.getComponent(compInd); + if (child instanceof TestPanel) { + TestPanel pan = (TestPanel)child; + pan.performActionClicks(robot); + pause(100); + } + } + } + public Test(int row, int col, boolean focusable, boolean resizable) { + super("Frame" + row + "" + col); + TestPanel panel = new TestPanel(row, col); + if (Test.automatic) { + row = Test.DEF_ROW; + col = Test.DEF_COL; + } + setName(getTitle()); + add("Center", panel); + Label l = new Label(getClass().getSuperclass().getName() + ", " + (focusable?"focusable":"non-focusable") + + ", " + (resizable?"resizable":"non-resizable")); + l.setBackground(Color.green); + add("North", l); + setBounds(Test.DEF_LEFT + DEF_WIDTH*col, DEF_TOP + DEF_HEIGHT*row, DEF_WIDTH, DEF_HEIGHT); + if (!focusable) { + setFocusableWindowState(false); + } + if (!resizable) { + setResizable(false); + } +// setVisible(true); + } +} +class TestWindow extends Window { + public TestWindow(int row, int col, boolean focusable, Frame owner) { + super(owner); + setName("Window" + row + "" + col); + TestPanel panel = new TestPanel(row, col); + if (Test.automatic) { + row = Test.DEF_ROW; + col = Test.DEF_COL; + } + + add("Center", panel); + Label l = new Label(getClass().getSuperclass().getName() + ", " + (focusable?"focusable":"non-focusable") + + ", " + (false?"resizable":"non-resizable")); + l.setBackground(Color.green); + add("North", l); + + setBounds(Test.DEF_LEFT + Test.DEF_WIDTH*col, Test.DEF_TOP + Test.DEF_HEIGHT*row, Test.DEF_WIDTH, Test.DEF_HEIGHT); + if (!focusable) { + setFocusableWindowState(false); + } +// setVisible(true); + } +} +class TestDialog extends Dialog { + public TestDialog(int row, int col, boolean focusable, boolean resizable, Frame owner) { + super(owner); + setName("Dialog" + row + "" + col); + TestPanel panel = new TestPanel(row, col); + if (Test.automatic) { + row = Test.DEF_ROW; + col = Test.DEF_COL; + } + + add("Center", panel); + Label l = new Label(getClass().getSuperclass().getName() + ", " + (focusable?"focusable":"non-focusable") + + ", " + (resizable?"resizable":"non-resizable")); + l.setBackground(Color.green); + add("North", l); + + setBounds(Test.DEF_LEFT + Test.DEF_WIDTH*col, Test.DEF_TOP + Test.DEF_HEIGHT*row, Test.DEF_WIDTH, Test.DEF_HEIGHT); + if (!focusable) { + setFocusableWindowState(false); + } + if (!resizable) { + setResizable(false); + } +// setVisible(true); + } +} + +class TestPanel extends Panel { + + void clickComponent(Component comp, Robot robot) { + if (comp instanceof Choice) { + return; + } + Point compLoc = comp.getLocationOnScreen(); + Dimension size = comp.getSize(); + robot.mouseMove(compLoc.x + size.width/2, compLoc.y + size.height/2); + robot.mousePress(InputEvent.BUTTON1_MASK); + robot.mouseRelease(InputEvent.BUTTON1_MASK); + } + void performFocusClicks(Robot robot) { + for (int childInd = 0; childInd < getComponentCount(); childInd++) { + performFocusClick(getComponent(childInd), robot); + } + } + void performFocusClick(Component comp, Robot robot) { + clickComponent(comp, robot); + } + + void performActionClicks(Robot robot) { + for (int childInd = 0; childInd < getComponentCount(); childInd++) { + performActionClick(getComponent(childInd), robot); + } + } + void performActionClick(Component comp, Robot robot) { + } + + public TestPanel(int row, int col) { + setLayout(new FlowLayout()); + Button b; + add(b = new Button("press"+ row + "" + col)); + b.setName(b.getLabel()); +// b.addMouseListener(new MouseAdapter() { +// public void mousePressed(MouseEvent e) { +// System.err.println(e); +// } +// }); + TextField t; + add(t = new TextField("text" + row + "" + col)); + t.setName(t.getText()); + + java.awt.List list = new java.awt.List(); + add(list); + list.setName("list"); + list.add("one"); + list.add("two"); + list.add("three"); + list.setMultipleMode(true); + list.setName("list" + row + "" + col); + + Checkbox check = new Checkbox("checker"); + add(check); + check.setName("check" + row + "" + col); + + Choice choice = new Choice(); + choice.add("one"); + choice.add("two"); + choice.add("three"); + add(choice); + choice.setName("choice" + row + "" + col); + + Canvas can = new Canvas() { + public Dimension getPreferredSize() { + return new Dimension(10, 10); + } + }; + can.setBackground(Color.blue); + add(can); + can.setName("canvas" + row + "" + col); + + TextArea ta = new TextArea("text\ntttt\naaaa\nwwwww\nqqqqqq\neeeeee\nrrrrrr\nyyyyyy\nuuuuu", 3, 5); + add(ta); + ta.setName("textarea" + row + "" + col); + + Scrollbar bar = new Scrollbar(Scrollbar.HORIZONTAL); + add(bar); + bar.setName("scrollbar" + row + "" + col); + + CheckboxGroup group = new CheckboxGroup(); + Checkbox ch1 = new Checkbox("one", group, true); + Checkbox ch2 = new Checkbox("two", group, false); + add(ch1); + add(ch2); + ch1.setName("checkbox1 " + row + "" + col); + ch2.setName("checkbox2 " + row + "" + col); + + + ScrollPane pane = new ScrollPane(ScrollPane.SCROLLBARS_ALWAYS); + add(pane); + Button bigButton = new Button("abc") { + public Dimension getPreferredSize() { + return new Dimension(100, 100); + } + }; + pane.add(bigButton); + bigButton.setName("bigbutton" + row + "" + col); + } +} + +class GlobalListener implements AWTEventListener { + java.util.List errors = new java.util.LinkedList(); + public boolean report() { + if (errors.size() != 0) { + System.err.println("Test FAILED"); + } else { + System.err.println("Test PASSED"); + return true; + } + ListIterator iter = errors.listIterator(); + while (iter.hasNext()) { + System.err.println(iter.next()); + } + return false; + } + public GlobalListener() { + } + Window getWindowParent(Component comp) { + while (comp != null && !(comp instanceof Window)) { + comp = comp.getParent(); + } + return (Window)comp; + } + void reportError(AWTEvent e, String message) { + String error = "ERROR: " + message + " : " + e; + errors.add(error); + System.err.println(error); + } + public void eventDispatched(AWTEvent e) { + Component comp = (Component)e.getSource(); + Window parent = getWindowParent(comp); + if (!(e instanceof WindowEvent || e instanceof FocusEvent)) { + System.err.println("Strange event " + e); + } + + // Skip WINDOW_OPENED + if (e.getID() == WindowEvent.WINDOW_CLOSING) { + System.err.println(e); + } + switch (e.getID()) { + case WindowEvent.WINDOW_OPENED: + case WindowEvent.WINDOW_CLOSING: + case WindowEvent.WINDOW_CLOSED: + case WindowEvent.WINDOW_ICONIFIED: + case WindowEvent.WINDOW_DEICONIFIED: + case WindowEvent.WINDOW_STATE_CHANGED: + return; + case WindowEvent.WINDOW_LOST_FOCUS: { + WindowEvent we = (WindowEvent)e; + if (we.getOppositeWindow() != null && !we.getOppositeWindow().getFocusableWindowState()) { + reportError(e, "frame lost focus because of non-focusable window"); + } + break; + } + } + // Check that Window owner is focusable + if (!parent.getFocusableWindowState()) { + reportError(e, "focus event for component in non-focusable window " + parent.getName()); + } + if (!comp.isFocusable()) { + reportError(e, "focus event for non-focusable component"); + } +// if (e instanceof WindowEvent || e instanceof FocusEvent) { +// // System.err.println(e); +// } + } +} diff --git a/jdk/test/java/awt/Focus/TypeAhead/TestFocusFreeze.java b/jdk/test/java/awt/Focus/TypeAhead/TestFocusFreeze.java new file mode 100644 index 00000000000..129cdc2811e --- /dev/null +++ b/jdk/test/java/awt/Focus/TypeAhead/TestFocusFreeze.java @@ -0,0 +1,488 @@ +/* + * Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* +@test +@bug 6183877 6216005 6225560 +@summary Tests that keyboard input doesn't freeze due to type-ahead problems +@author Denis Mikhalkin: area=awt.focus +@run main/timeout=300 TestFocusFreeze +*/ + +// Note the area= after Your Name in the author tag. Here, you +// should put which functional area the test falls in. See the +// AWT-core home page -> test areas and/or -> AWT team for a list of +// areas. + + +/** + * TestFocusFreeze.java + * + * summary: XXX A brief summary of what this tests + */ + +import java.awt.*; +import java.awt.event.*; +import javax.swing.*; +import java.util.concurrent.atomic.*; +import sun.awt.SunToolkit; + +public class TestFocusFreeze +{ + + //*** test-writer defined static variables go here *** + + + private static void init() + { + //*** Create instructions for the user here *** + + FocusTest.test(); + + }//End init() + + + + /***************************************************** + * Standard Test Machinery Section + * DO NOT modify anything in this section -- it's a + * standard chunk of code which has all of the + * synchronisation necessary for the test harness. + * By keeping it the same in all tests, it is easier + * to read and understand someone else's test, as + * well as insuring that all tests behave correctly + * with the test harness. + * There is a section following this for test- + * classes + ******************************************************/ + private static boolean theTestPassed = false; + private static boolean testGeneratedInterrupt = false; + private static String failureMessage = ""; + + private static Thread mainThread = null; + + private static int sleepTime = 300000; + + // Not sure about what happens if multiple of this test are + // instantiated in the same VM. Being static (and using + // static vars), it aint gonna work. Not worrying about + // it for now. + public static void main( String args[] ) throws InterruptedException + { + mainThread = Thread.currentThread(); + try + { + init(); + } + catch( TestPassedException e ) + { + //The test passed, so just return from main and harness will + // interepret this return as a pass + return; + } + //At this point, neither test pass nor test fail has been + // called -- either would have thrown an exception and ended the + // test, so we know we have multiple threads. + + //Test involves other threads, so sleep and wait for them to + // called pass() or fail() + try + { + Thread.sleep( sleepTime ); + //Timed out, so fail the test + throw new RuntimeException( "Timed out after " + sleepTime/1000 + " seconds" ); + } + catch (InterruptedException e) + { + //The test harness may have interrupted the test. If so, rethrow the exception + // so that the harness gets it and deals with it. + if( ! testGeneratedInterrupt ) throw e; + + //reset flag in case hit this code more than once for some reason (just safety) + testGeneratedInterrupt = false; + + if ( theTestPassed == false ) + { + throw new RuntimeException( failureMessage ); + } + } + + }//main + + public static synchronized void setTimeoutTo( int seconds ) + { + sleepTime = seconds * 1000; + } + + public static synchronized void pass() + { + Sysout.println( "The test passed." ); + Sysout.println( "The test is over, hit Ctl-C to stop Java VM" ); + //first check if this is executing in main thread + if ( mainThread == Thread.currentThread() ) + { + //Still in the main thread, so set the flag just for kicks, + // and throw a test passed exception which will be caught + // and end the test. + theTestPassed = true; + throw new TestPassedException(); + } + theTestPassed = true; + testGeneratedInterrupt = true; + mainThread.interrupt(); + }//pass() + + public static synchronized void fail() + { + //test writer didn't specify why test failed, so give generic + fail( "it just plain failed! :-)" ); + } + + public static synchronized void fail( String whyFailed ) + { + Sysout.println( "The test failed: " + whyFailed ); + Sysout.println( "The test is over, hit Ctl-C to stop Java VM" ); + //check if this called from main thread + if ( mainThread == Thread.currentThread() ) + { + //If main thread, fail now 'cause not sleeping + throw new RuntimeException( whyFailed ); + } + theTestPassed = false; + testGeneratedInterrupt = true; + failureMessage = whyFailed; + mainThread.interrupt(); + }//fail() + +}// class TestFocusFreeze + +//This exception is used to exit from any level of call nesting +// when it's determined that the test has passed, and immediately +// end the test. +class TestPassedException extends RuntimeException +{ +} + +//*********** End Standard Test Machinery Section ********** + + +//************ Begin classes defined for the test **************** + +// if want to make listeners, here is the recommended place for them, then instantiate +// them in init() + +/* Example of a class which may be written as part of a test +class NewClass implements anInterface + { + static int newVar = 0; + + public void eventDispatched(AWTEvent e) + { + //Counting events to see if we get enough + eventCount++; + + if( eventCount == 20 ) + { + //got enough events, so pass + + TestFocusFreeze.pass(); + } + else if( tries == 20 ) + { + //tried too many times without getting enough events so fail + + TestFocusFreeze.fail(); + } + + }// eventDispatched() + + }// NewClass class + +*/ + + +//************** End classes defined for the test ******************* + + + + +/**************************************************** + Standard Test Machinery + DO NOT modify anything below -- it's a standard + chunk of code whose purpose is to make user + interaction uniform, and thereby make it simpler + to read and understand someone else's test. + ****************************************************/ + +/** + This is part of the standard test machinery. + It creates a dialog (with the instructions), and is the interface + for sending text messages to the user. + To print the instructions, send an array of strings to Sysout.createDialog + WithInstructions method. Put one line of instructions per array entry. + To display a message for the tester to see, simply call Sysout.println + with the string to be displayed. + This mimics System.out.println but works within the test harness as well + as standalone. + */ + +class Sysout +{ + private static TestDialog dialog; + + public static void createDialogWithInstructions( String[] instructions ) + { + dialog = new TestDialog( new Frame(), "Instructions" ); + dialog.printInstructions( instructions ); + dialog.setVisible(true); + println( "Any messages for the tester will display here." ); + } + + public static void createDialog( ) + { + dialog = new TestDialog( new Frame(), "Instructions" ); + String[] defInstr = { "Instructions will appear here. ", "" } ; + dialog.printInstructions( defInstr ); + dialog.setVisible(true); + println( "Any messages for the tester will display here." ); + } + + + public static void printInstructions( String[] instructions ) + { + dialog.printInstructions( instructions ); + } + + + public static void println( String messageIn ) + { + System.out.println(messageIn); + } + +}// Sysout class + +/** + This is part of the standard test machinery. It provides a place for the + test instructions to be displayed, and a place for interactive messages + to the user to be displayed. + To have the test instructions displayed, see Sysout. + To have a message to the user be displayed, see Sysout. + Do not call anything in this dialog directly. + */ +class TestDialog extends Dialog +{ + + TextArea instructionsText; + TextArea messageText; + int maxStringLength = 80; + + //DO NOT call this directly, go through Sysout + public TestDialog( Frame frame, String name ) + { + super( frame, name ); + int scrollBoth = TextArea.SCROLLBARS_BOTH; + instructionsText = new TextArea( "", 15, maxStringLength, scrollBoth ); + add( "North", instructionsText ); + + messageText = new TextArea( "", 5, maxStringLength, scrollBoth ); + add("Center", messageText); + + pack(); + + setVisible(true); + }// TestDialog() + + //DO NOT call this directly, go through Sysout + public void printInstructions( String[] instructions ) + { + //Clear out any current instructions + instructionsText.setText( "" ); + + //Go down array of instruction strings + + String printStr, remainingStr; + for( int i=0; i < instructions.length; i++ ) + { + //chop up each into pieces maxSringLength long + remainingStr = instructions[ i ]; + while( remainingStr.length() > 0 ) + { + //if longer than max then chop off first max chars to print + if( remainingStr.length() >= maxStringLength ) + { + //Try to chop on a word boundary + int posOfSpace = remainingStr. + lastIndexOf( ' ', maxStringLength - 1 ); + + if( posOfSpace <= 0 ) posOfSpace = maxStringLength - 1; + + printStr = remainingStr.substring( 0, posOfSpace + 1 ); + remainingStr = remainingStr.substring( posOfSpace + 1 ); + } + //else just print + else + { + printStr = remainingStr; + remainingStr = ""; + } + + instructionsText.append( printStr + "\n" ); + + }// while + + }// for + + }//printInstructions() + + //DO NOT call this directly, go through Sysout + public void displayMessage( String messageIn ) + { + messageText.append( messageIn + "\n" ); + System.out.println(messageIn); + } + +}// TestDialog class + + +class FocusTest extends JFrame implements ActionListener { + + private JDialog pageDialog = null; + + private AtomicBoolean passed = new AtomicBoolean(); + private static volatile boolean all_passed = true; + private static volatile long pressTime; + private static Object testLock = new Object(); + private static Object resultLock = new Object(); + + public FocusTest() { + final GraphicsConfiguration gc = + GraphicsEnvironment.getLocalGraphicsEnvironment(). + getDefaultScreenDevice().getDefaultConfiguration(); + + pageDialog = new JDialog(this, "JDialog", true, gc); + Container c = pageDialog.getContentPane(); + c.setLayout(new BorderLayout()); + JButton btnApprove =new JButton("Exit Button"); + btnApprove.addActionListener(this); + c.add("South", btnApprove); + pageDialog.pack(); + + JButton bb = new JButton("Action"); + bb.addActionListener(new ActionListener() { + final JDialog pageDialog = FocusTest.this.pageDialog; + public void actionPerformed(ActionEvent e) { + synchronized(testLock) { + testLock.notify(); + } + pageDialog.setVisible(true); + } + }); + + add(bb); + pack(); + setVisible(true); + + ((SunToolkit)Toolkit.getDefaultToolkit()).realSync(); + + bb.requestFocus(); + + ((SunToolkit)Toolkit.getDefaultToolkit()).realSync(); + + if (!bb.isFocusOwner()) { + System.err.println("Couldn't make bb focused"); + all_passed = false; + return; + } + + new Thread() { + public void run() { + try { + Robot r = new Robot(); + synchronized (testLock) { + testLock.wait(); + } + r.keyPress(KeyEvent.VK_SPACE); + r.delay(50); + r.keyRelease(KeyEvent.VK_SPACE); + synchronized(passed) { + passed.wait(1000); + } + pageDialog.dispose(); + FocusTest.this.dispose(); + if (!passed.get()) { + all_passed = false; + } + } catch (Exception e) { + e.printStackTrace(); + } + synchronized (resultLock) { + resultLock.notifyAll(); + } + } + }.start(); + + try { + Robot r = new Robot(); + r.keyPress(KeyEvent.VK_SPACE); + r.delay(50); + r.keyRelease(KeyEvent.VK_SPACE); + } catch (Exception e) { + e.printStackTrace(); + all_passed = false; + return; + } + + try { + synchronized (resultLock) { + resultLock.wait(); + } + } catch (InterruptedException ie) { + ie.printStackTrace(); + } + } + + public void actionPerformed(ActionEvent ae) { + System.err.println("Action performed"); + passed.set(true); + synchronized(passed) { + passed.notify(); + } + } + + public static void test() { + FocusTest test = null; + for (int i = 0; i < 10; i++) { + test = new FocusTest(); + try { + Thread.sleep(500); + } catch (InterruptedException e) { + break; + } + } + if (!all_passed) { + TestFocusFreeze.fail("Not all passed"); + } else { + TestFocusFreeze.pass(); + } + } +} diff --git a/jdk/test/java/awt/Focus/WrongKeyTypedConsumedTest/WrongKeyTypedConsumedTest.java b/jdk/test/java/awt/Focus/WrongKeyTypedConsumedTest/WrongKeyTypedConsumedTest.java new file mode 100644 index 00000000000..fd6b56d8609 --- /dev/null +++ b/jdk/test/java/awt/Focus/WrongKeyTypedConsumedTest/WrongKeyTypedConsumedTest.java @@ -0,0 +1,293 @@ +/* + * Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* + test + @bug 4782886 + @summary FocusManager consumes wrong KEYTYPED-Events + @author son: area=awt.focus + @run applet WrongKeyTypedConsumedTest.html +*/ + +/** + * WrongKeyTypedConsumedTest.java + * + * summary: FocusManager consumes wrong KEYTYPED-Events + */ + +import java.applet.Applet; + +import java.awt.AWTException; +import java.awt.AWTKeyStroke; +import java.awt.BorderLayout; +import java.awt.Dialog; +import java.awt.Dimension; +import java.awt.FlowLayout; +import java.awt.Frame; +import java.awt.KeyboardFocusManager; +import java.awt.Point; +import java.awt.Robot; +import java.awt.TextArea; + +import java.awt.event.KeyEvent; + +import java.util.HashSet; +import java.util.Set; + +import javax.swing.JCheckBox; +import javax.swing.JFrame; +import javax.swing.JTextArea; + +public class WrongKeyTypedConsumedTest extends Applet +{ + //Declare things used in the test, like buttons and labels here + + public void init() + { + //Create instructions for the user here, as well as set up + // the environment -- set the layout manager, add buttons, + // etc. + + String[] instructions = + { + "This is an AUTOMATIC test", + "simply wait until it is done" + }; + Sysout.createDialog( ); + Sysout.printInstructions( instructions ); + + }//End init() + + public void start () + { + //Get things going. Request focus, set size, et cetera + setSize (200,200); + setVisible(true); + validate(); + + JFrame frame = new JFrame("The Frame"); + Set ftk = new HashSet(); + ftk.add(AWTKeyStroke.getAWTKeyStroke(KeyEvent.VK_DOWN, 0)); + frame.getContentPane(). + setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, + ftk); + + JCheckBox checkbox = new JCheckBox("test"); + frame.getContentPane().add(checkbox, BorderLayout.NORTH); + + JTextArea textarea = new JTextArea(40, 10); + frame.getContentPane().add(textarea); + + frame.pack(); + frame.setVisible(true); + + try { + Robot robot = new Robot(); + + // wait for activation + robot.delay(2000); + if (!frame.isActive()) { + Point loc = frame.getLocationOnScreen(); + Dimension size = frame.getSize(); + robot.mouseMove(loc.x + size.width/2, + loc.y + size.height/2); + frame.toFront(); + robot.delay(1000); + if (!frame.isActive()) { + throw new RuntimeException("Test Fialed: frame isn't active"); + } + } + + // verify if checkbox has focus + if (!checkbox.isFocusOwner()) { + checkbox.requestFocusInWindow(); + robot.delay(1000); + if (!checkbox.isFocusOwner()) { + throw new RuntimeException("Test Failed: checkbox doesn't have focus"); + } + } + // press VK_DOWN + robot.keyPress(KeyEvent.VK_DOWN); + robot.delay(250); + robot.keyRelease(KeyEvent.VK_DOWN); + robot.delay(1000); + + // verify if text area has focus + if (!textarea.isFocusOwner()) { + throw new RuntimeException("Test Failed: focus wasn't transfered to text area"); + } + // press '1' + robot.keyPress(KeyEvent.VK_1); + robot.delay(250); + robot.keyRelease(KeyEvent.VK_1); + robot.delay(1000); + + // verify if KEY_TYPED arraived + if (!"1".equals(textarea.getText())) { + throw new RuntimeException("Test Failed: text area text is \"" + textarea.getText() + "\", not \"1\""); + } + } catch(AWTException e) { + e.printStackTrace(); + throw new RuntimeException("Test failed because of some internal exception"); + } + Sysout.println("Test Passed"); + }// start() + +}// class WrongKeyTypedConsumedTest + +/**************************************************** + Standard Test Machinery + DO NOT modify anything below -- it's a standard + chunk of code whose purpose is to make user + interaction uniform, and thereby make it simpler + to read and understand someone else's test. + ****************************************************/ + +/** + This is part of the standard test machinery. + It creates a dialog (with the instructions), and is the interface + for sending text messages to the user. + To print the instructions, send an array of strings to Sysout.createDialog + WithInstructions method. Put one line of instructions per array entry. + To display a message for the tester to see, simply call Sysout.println + with the string to be displayed. + This mimics System.out.println but works within the test harness as well + as standalone. + */ + +class Sysout +{ + private static TestDialog dialog; + + public static void createDialogWithInstructions( String[] instructions ) + { + dialog = new TestDialog( new Frame(), "Instructions" ); + dialog.printInstructions( instructions ); + dialog.setVisible(true); + println( "Any messages for the tester will display here." ); + } + + public static void createDialog( ) + { + dialog = new TestDialog( new Frame(), "Instructions" ); + String[] defInstr = { "Instructions will appear here. ", "" } ; + dialog.printInstructions( defInstr ); + dialog.setVisible(true); + println( "Any messages for the tester will display here." ); + } + + + public static void printInstructions( String[] instructions ) + { + dialog.printInstructions( instructions ); + } + + + public static void println( String messageIn ) + { + dialog.displayMessage( messageIn ); + } + +}// Sysout class + +/** + This is part of the standard test machinery. It provides a place for the + test instructions to be displayed, and a place for interactive messages + to the user to be displayed. + To have the test instructions displayed, see Sysout. + To have a message to the user be displayed, see Sysout. + Do not call anything in this dialog directly. + */ +class TestDialog extends Dialog +{ + + TextArea instructionsText; + TextArea messageText; + int maxStringLength = 80; + + //DO NOT call this directly, go through Sysout + public TestDialog( Frame frame, String name ) + { + super( frame, name ); + int scrollBoth = TextArea.SCROLLBARS_BOTH; + instructionsText = new TextArea( "", 15, maxStringLength, scrollBoth ); + add( "North", instructionsText ); + + messageText = new TextArea( "", 5, maxStringLength, scrollBoth ); + add("Center", messageText); + + pack(); + + setVisible(true); + }// TestDialog() + + //DO NOT call this directly, go through Sysout + public void printInstructions( String[] instructions ) + { + //Clear out any current instructions + instructionsText.setText( "" ); + + //Go down array of instruction strings + + String printStr, remainingStr; + for( int i=0; i < instructions.length; i++ ) + { + //chop up each into pieces maxSringLength long + remainingStr = instructions[ i ]; + while( remainingStr.length() > 0 ) + { + //if longer than max then chop off first max chars to print + if( remainingStr.length() >= maxStringLength ) + { + //Try to chop on a word boundary + int posOfSpace = remainingStr. + lastIndexOf( ' ', maxStringLength - 1 ); + + if( posOfSpace <= 0 ) posOfSpace = maxStringLength - 1; + + printStr = remainingStr.substring( 0, posOfSpace + 1 ); + remainingStr = remainingStr.substring( posOfSpace + 1 ); + } + //else just print + else + { + printStr = remainingStr; + remainingStr = ""; + } + + instructionsText.append( printStr + "\n" ); + + }// while + + }// for + + }//printInstructions() + + //DO NOT call this directly, go through Sysout + public void displayMessage( String messageIn ) + { + messageText.append( messageIn + "\n" ); + System.out.println(messageIn); + } + +}// TestDialog class From 75f6b17d66a720ec267404e76d181a0ff6079a1a Mon Sep 17 00:00:00 2001 From: Anton Tarasov Date: Wed, 26 Mar 2008 16:56:40 +0300 Subject: [PATCH 099/258] 6609607: test/closed/java/awt/Focus/AppletInitialFocusTest should be rewritten Using test.java.awt.regtesthelpers.Util. Refactoring. Reviewed-by: volk --- .../AppletInitialFocusTest.html | 11 +-- .../AppletInitialFocusTest.java | 78 ++++--------------- .../AppletInitialFocusTest1.html | 8 +- .../AppletInitialFocusTest1.java | 27 +------ 4 files changed, 30 insertions(+), 94 deletions(-) diff --git a/jdk/test/java/awt/Focus/AppletInitialFocusTest/AppletInitialFocusTest.html b/jdk/test/java/awt/Focus/AppletInitialFocusTest/AppletInitialFocusTest.html index 3d3d0c81a62..bb07d59a736 100644 --- a/jdk/test/java/awt/Focus/AppletInitialFocusTest/AppletInitialFocusTest.html +++ b/jdk/test/java/awt/Focus/AppletInitialFocusTest/AppletInitialFocusTest.html @@ -1,11 +1,12 @@ - AppletInitialFocusTest diff --git a/jdk/test/java/awt/Focus/AppletInitialFocusTest/AppletInitialFocusTest.java b/jdk/test/java/awt/Focus/AppletInitialFocusTest/AppletInitialFocusTest.java index e34e6e123a5..c3de576386e 100644 --- a/jdk/test/java/awt/Focus/AppletInitialFocusTest/AppletInitialFocusTest.java +++ b/jdk/test/java/awt/Focus/AppletInitialFocusTest/AppletInitialFocusTest.java @@ -23,81 +23,37 @@ /* test - @bug 4041703 4096228 4025223 4260929 - @summary Ensures that appletviewer sets a reasonable default focus - for an Applet on start + @bug 4041703 4096228 4025223 4260929 + @summary Ensures that appletviewer sets a reasonable default focus for an Applet on start @author das area=appletviewer - @run shell AppletInitialFocusTest.sh + @run applet AppletInitialFocusTest.html */ import java.applet.Applet; -import java.awt.*; -import java.awt.event.*; - -class MyKeyboardFocusManager extends DefaultKeyboardFocusManager { - public Window getGlobalFocusedWindow() { - return super.getGlobalFocusedWindow(); - } -} +import java.awt.Button; +import java.awt.Component; +import java.awt.Robot; +import java.awt.Window; +import test.java.awt.regtesthelpers.Util; public class AppletInitialFocusTest extends Applet { - - Window window; + Robot robot = Util.createRobot(); Button button = new Button("Button"); - MyKeyboardFocusManager manager = new MyKeyboardFocusManager(); - - Object lock = new Object(); public void init() { - KeyboardFocusManager.setCurrentKeyboardFocusManager(manager); - - Component parent = this; - while (parent != null && !(parent instanceof Window)) { - parent = parent.getParent(); - } - /* - * This applet is designed to be run only with appletviewer, - * so there always should be a toplevel frame. - */ - if (parent == null) { - synchronized (lock) { - System.err.println("appletviewer not running"); - System.exit(3); - } - } - window = (Window)parent; - - button.addFocusListener(new FocusAdapter() { - public void focusGained(FocusEvent e) { - synchronized (lock) { - System.err.println("passed"); - System.exit(0); - } - } - }); add(button); } public void start() { - Thread thread = new Thread(new Runnable() { - public void run() { - try { - Thread.sleep(1000); - synchronized (lock) { - Window focused = manager.getGlobalFocusedWindow(); - if (window == focused) { - System.err.println("failed"); - System.exit(2); - } else { - System.err.println("window never activated"); - System.err.println(focused); - System.exit(0); - } + new Thread(new Runnable() { + public void run() { + Util.waitTillShown(button); + robot.delay(1000); // delay the thread to let EDT to start dispatching focus events + Util.waitForIdle(robot); + if (!button.hasFocus()) { + throw new RuntimeException("Appletviewer doesn't set default focus correctly."); } - } catch(InterruptedException e) { } - } - }); - thread.start(); + }).start(); } } diff --git a/jdk/test/java/awt/Focus/AppletInitialFocusTest/AppletInitialFocusTest1.html b/jdk/test/java/awt/Focus/AppletInitialFocusTest/AppletInitialFocusTest1.html index cdbcdb48021..dc094e1a556 100644 --- a/jdk/test/java/awt/Focus/AppletInitialFocusTest/AppletInitialFocusTest1.html +++ b/jdk/test/java/awt/Focus/AppletInitialFocusTest/AppletInitialFocusTest1.html @@ -1,11 +1,13 @@ - AppletInitialFocusTest1 diff --git a/jdk/test/java/awt/Focus/AppletInitialFocusTest/AppletInitialFocusTest1.java b/jdk/test/java/awt/Focus/AppletInitialFocusTest/AppletInitialFocusTest1.java index b72c1c99758..2f7e8f92304 100644 --- a/jdk/test/java/awt/Focus/AppletInitialFocusTest/AppletInitialFocusTest1.java +++ b/jdk/test/java/awt/Focus/AppletInitialFocusTest/AppletInitialFocusTest1.java @@ -1,32 +1,9 @@ /* - * Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ - -/* - test + test %W% %E% @bug 4411534 4517274 @summary ensures that user's requestFocus() during applet initialization is not ignored. - @author prs area=appletviewer + @author prs@sparc.spb.su area=appletviewer @run shell AppletInitialFocusTest1.sh */ From 911da0a7964f43ad30be8cf022affa132bf35bc6 Mon Sep 17 00:00:00 2001 From: Anton Tarasov Date: Wed, 26 Mar 2008 17:38:26 +0300 Subject: [PATCH 100/258] 6616792: five AWT focus regression tests should be fixed Fixed/refactored the tests. Reviewed-by: volk --- .../ActualFocusedWindowBlockingTest.java | 228 +------ .../ActualFocusedWindowRetaining.java | 333 ++--------- .../FrameJumpingToMouse.java | 253 ++------ .../{Test.java => NoEventsTest.java} | 39 +- .../NonfocusableOwnerTest.java | 249 +------- .../awt/Focus/TypeAhead/TestFocusFreeze.java | 559 ++++-------------- .../WrongKeyTypedConsumedTest.java | 260 ++------ 7 files changed, 329 insertions(+), 1592 deletions(-) rename jdk/test/java/awt/Focus/NonFocusableWindowTest/{Test.java => NoEventsTest.java} (92%) diff --git a/jdk/test/java/awt/Focus/ActualFocusedWindowTest/ActualFocusedWindowBlockingTest.java b/jdk/test/java/awt/Focus/ActualFocusedWindowTest/ActualFocusedWindowBlockingTest.java index 823c2d0310b..888fae37f51 100644 --- a/jdk/test/java/awt/Focus/ActualFocusedWindowTest/ActualFocusedWindowBlockingTest.java +++ b/jdk/test/java/awt/Focus/ActualFocusedWindowTest/ActualFocusedWindowBlockingTest.java @@ -25,8 +25,10 @@ @test @bug 6314575 @summary Tests that previosly focused owned window doesn't steal focus when an owner's component requests focus. - @author Anton Tarasov: area=awt-focus - @run applet ActualFocusedWindowBlockingTest.html + @author Anton.Tarasov: area=awt.focus + @library ../../regtesthelpers + @build Util + @run main ActualFocusedWindowBlockingTest */ import java.awt.*; @@ -35,9 +37,10 @@ import java.applet.Applet; import java.util.concurrent.atomic.AtomicBoolean; import java.lang.reflect.InvocationTargetException; import sun.awt.SunToolkit; +import test.java.awt.regtesthelpers.Util; public class ActualFocusedWindowBlockingTest extends Applet { - Robot robot; + Robot robot = Util.createRobot(); Frame owner = new Frame("Owner Frame"); Window win = new Window(owner); Frame frame = new Frame("Auxiliary Frame"); @@ -52,28 +55,12 @@ public class ActualFocusedWindowBlockingTest extends Applet { } public void init() { - // Create instructions for the user here, as well as set up - // the environment -- set the layout manager, add buttons, - // etc. - this.setLayout (new BorderLayout ()); - Sysout.createDialogWithInstructions(new String[] - {"Automatic test. Simply wait until it's done."}); - - if ("sun.awt.motif.MToolkit".equals(Toolkit.getDefaultToolkit().getClass().getName())) { - return; - } - Toolkit.getDefaultToolkit().addAWTEventListener(new AWTEventListener() { public void eventDispatched(AWTEvent e) { - Sysout.println("--> " + e); + System.out.println("--> " + e); } }, FocusEvent.FOCUS_EVENT_MASK | WindowEvent.WINDOW_FOCUS_EVENT_MASK); - try { - robot = new Robot(); - } catch (AWTException e) { - throw new RuntimeException("Error: unable to create robot", e); - } owner.add(fButton); win.add(wButton); frame.add(aButton); @@ -87,19 +74,18 @@ public class ActualFocusedWindowBlockingTest extends Applet { public void start() { if ("sun.awt.motif.MToolkit".equals(Toolkit.getDefaultToolkit().getClass().getName())) { - Sysout.println("No testing on Motif. Test passed."); + System.out.println("No testing on Motif. Test passed."); return; } - Sysout.println("\nTest started:\n"); + System.out.println("\nTest started:\n"); // Test 1. clickOnCheckFocus(wButton); - clickOnCheckFocus(aButton); - clickOn(fButton); + Util.clickOnComp(fButton, robot); if (!testFocused(fButton)) { throw new TestFailedException("The owner's component [" + fButton + "] couldn't be focused by click"); } @@ -107,11 +93,10 @@ public class ActualFocusedWindowBlockingTest extends Applet { // Test 2. clickOnCheckFocus(wButton); - clickOnCheckFocus(aButton); fButton.requestFocus(); - realSync(); + Util.waitForIdle(robot); if (!testFocused(fButton)) { throw new TestFailedException("The owner's component [" + fButton + "] couldn't be focused by request"); } @@ -119,19 +104,16 @@ public class ActualFocusedWindowBlockingTest extends Applet { // Test 3. clickOnCheckFocus(wButton); - clickOnCheckFocus(aButton); - clickOnCheckFocus(fButton); - clickOnCheckFocus(aButton); - clickOn(owner); + Util.clickOnTitle(owner, robot); if (!testFocused(fButton)) { throw new TestFailedException("The owner's component [" + fButton + "] couldn't be focused as the most recent focus owner"); } - Sysout.println("Test passed."); + System.out.println("Test passed."); } void tuneAndShowWindows(Window[] arr) { @@ -142,33 +124,18 @@ public class ActualFocusedWindowBlockingTest extends Applet { w.setBackground(Color.blue); w.setVisible(true); y += 200; - realSync(); + Util.waitForIdle(robot); } } - void clickOn(Component c) { - Sysout.println("Test: clicking " + c); - - Point p = c.getLocationOnScreen(); - Dimension d = c.getSize(); - - if (c instanceof Frame) { - robot.mouseMove(p.x + (int)(d.getWidth()/2), p.y + ((Frame)c).getInsets().top/2); - Sysout.println((p.x + (int)(d.getWidth()/2)) + " " + (p.y + ((Frame)c).getInsets().top/2)); - } else { - robot.mouseMove(p.x + (int)(d.getWidth()/2), p.y + (int)(d.getHeight()/2)); - } - robot.mousePress(InputEvent.BUTTON1_MASK); - robot.delay(100); - robot.mouseRelease(InputEvent.BUTTON1_MASK); - - realSync(); - } - void clickOnCheckFocus(Component c) { - clickOn(c); + if (c instanceof Frame) { + Util.clickOnTitle((Frame)c, robot); + } else { + Util.clickOnComp(c, robot); + } if (!testFocused(c)) { - throw new RuntimeException("Error: [" + c + "] couldn't get focus by click."); + throw new TestErrorException(c + "couldn't get focus by click."); } } @@ -177,157 +144,22 @@ public class ActualFocusedWindowBlockingTest extends Applet { if (KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner() == c) { return true; } - realSync(); + Util.waitForIdle(robot); } return false; } - void realSync() { - ((SunToolkit)Toolkit.getDefaultToolkit()).realSync(); + // Thrown when the behavior being verified is found wrong. + class TestFailedException extends RuntimeException { + TestFailedException(String msg) { + super("Test failed: " + msg); + } } - class TestFailedException extends RuntimeException { - public TestFailedException(String cause) { - super("Test failed. " + cause); - Sysout.println(cause); + // Thrown when an error not related to the behavior being verified is encountered. + class TestErrorException extends RuntimeException { + TestErrorException(String msg) { + super("Unexpected error: " + msg); } } } - -/**************************************************** - Standard Test Machinery - DO NOT modify anything below -- it's a standard - chunk of code whose purpose is to make user - interaction uniform, and thereby make it simpler - to read and understand someone else's test. - ****************************************************/ - -/** - This is part of the standard test machinery. - It creates a dialog (with the instructions), and is the interface - for sending text messages to the user. - To print the instructions, send an array of strings to Sysout.createDialog - WithInstructions method. Put one line of instructions per array entry. - To display a message for the tester to see, simply call Sysout.println - with the string to be displayed. - This mimics System.out.println but works within the test harness as well - as standalone. - */ - -class Sysout -{ - static TestDialog dialog; - - public static void createDialogWithInstructions( String[] instructions ) - { - dialog = new TestDialog( new Frame(), "Instructions" ); - dialog.printInstructions( instructions ); - dialog.setLocation(500,0); - dialog.setVisible(true); - println( "Any messages for the tester will display here." ); - } - - public static void createDialog( ) - { - dialog = new TestDialog( new Frame(), "Instructions" ); - String[] defInstr = { "Instructions will appear here. ", "" } ; - dialog.printInstructions( defInstr ); - dialog.setVisible(true); - println( "Any messages for the tester will display here." ); - } - - - public static void printInstructions( String[] instructions ) - { - dialog.printInstructions( instructions ); - } - - - public static void println( String messageIn ) - { - dialog.displayMessage( messageIn ); - } - -}// Sysout class - -/** - This is part of the standard test machinery. It provides a place for the - test instructions to be displayed, and a place for interactive messages - to the user to be displayed. - To have the test instructions displayed, see Sysout. - To have a message to the user be displayed, see Sysout. - Do not call anything in this dialog directly. - */ -class TestDialog extends Dialog -{ - - TextArea instructionsText; - TextArea messageText; - int maxStringLength = 80; - - //DO NOT call this directly, go through Sysout - public TestDialog( Frame frame, String name ) - { - super( frame, name ); - int scrollBoth = TextArea.SCROLLBARS_BOTH; - instructionsText = new TextArea( "", 15, maxStringLength, scrollBoth ); - add( "North", instructionsText ); - - messageText = new TextArea( "", 5, maxStringLength, scrollBoth ); - add("Center", messageText); - - pack(); - - setVisible(true); - }// TestDialog() - - //DO NOT call this directly, go through Sysout - public void printInstructions( String[] instructions ) - { - //Clear out any current instructions - instructionsText.setText( "" ); - - //Go down array of instruction strings - - String printStr, remainingStr; - for( int i=0; i < instructions.length; i++ ) - { - //chop up each into pieces maxSringLength long - remainingStr = instructions[ i ]; - while( remainingStr.length() > 0 ) - { - //if longer than max then chop off first max chars to print - if( remainingStr.length() >= maxStringLength ) - { - //Try to chop on a word boundary - int posOfSpace = remainingStr. - lastIndexOf( ' ', maxStringLength - 1 ); - - if( posOfSpace <= 0 ) posOfSpace = maxStringLength - 1; - - printStr = remainingStr.substring( 0, posOfSpace + 1 ); - remainingStr = remainingStr.substring( posOfSpace + 1 ); - } - //else just print - else - { - printStr = remainingStr; - remainingStr = ""; - } - - instructionsText.append( printStr + "\n" ); - - }// while - - }// for - - }//printInstructions() - - //DO NOT call this directly, go through Sysout - public void displayMessage( String messageIn ) - { - messageText.append( messageIn + "\n" ); - System.out.println(messageIn); - } - -}// TestDialog class diff --git a/jdk/test/java/awt/Focus/ActualFocusedWindowTest/ActualFocusedWindowRetaining.java b/jdk/test/java/awt/Focus/ActualFocusedWindowTest/ActualFocusedWindowRetaining.java index e539e39cd70..f657d431eac 100644 --- a/jdk/test/java/awt/Focus/ActualFocusedWindowTest/ActualFocusedWindowRetaining.java +++ b/jdk/test/java/awt/Focus/ActualFocusedWindowTest/ActualFocusedWindowRetaining.java @@ -23,16 +23,19 @@ /* @test - @bug 4823903 - @summary Tests actual focused window retaining. - @author Anton Tarasov: area=awt.focus - @run applet ActualFocusedWindowRetaining.html + @bug 4823903 + @summary Tests actual focused window retaining. + @author Anton.Tarasov: area=awt.focus + @library ../../regtesthelpers + @build Util + @run main ActualFocusedWindowRetaining */ import java.awt.*; import java.awt.event.*; import java.lang.reflect.*; import java.applet.*; +import test.java.awt.regtesthelpers.Util; public class ActualFocusedWindowRetaining extends Applet { public static Frame frame = new Frame("Other Frame"); @@ -46,7 +49,7 @@ public class ActualFocusedWindowRetaining extends Applet { public static Window window1 = new TestWindow(owner, otherButton2, testButton2, 800, 200); public static Window window2 = new TestWindow(owner, otherButton3, testButton3, 800, 300); public static int step; - public static Robot robot; + public static Robot robot = Util.createRobot(); public static void main(String[] args) { ActualFocusedWindowRetaining a = new ActualFocusedWindowRetaining(); @@ -54,53 +57,25 @@ public class ActualFocusedWindowRetaining extends Applet { a.start(); } - public void init() - { - //Create instructions for the user here, as well as set up - // the environment -- set the layout manager, add buttons, - // etc. - this.setLayout (new BorderLayout ()); - - String[] instructions = - { - "This is an AUTOMATIC test", - "simply wait until it is done" - }; - Sysout.createDialogWithInstructions( instructions ); - } - - public void start () - { - if (Toolkit.getDefaultToolkit().getClass() - .getName().equals("sun.awt.motif.MToolkit")) { - Sysout.println("No testing on Motif."); - return; - } - - try { - robot = new Robot(); - } catch (AWTException e) { - throw new RuntimeException("Error: unable to create robot", e); - } - + public void start () { Toolkit.getDefaultToolkit().addAWTEventListener(new AWTEventListener() { public void eventDispatched(AWTEvent e) { Object src = e.getSource(); Class cls = src.getClass(); if (cls == TestWindow.class) { - Sysout.println(e.paramString() + " on <" + (src == window1 ? "Window 1" : "Window 2") + ">"); + System.out.println(e.paramString() + " on <" + (src == window1 ? "Window 1" : "Window 2") + ">"); } else if (cls == Frame.class) { - Sysout.println(e.paramString() + " on <" + ((Frame)src).getTitle() + ">"); + System.out.println(e.paramString() + " on <" + ((Frame)src).getTitle() + ">"); } else if (cls == Button.class) { - Sysout.println(e.paramString() + " on <" + ((Button)src).getLabel() + ">"); + System.out.println(e.paramString() + " on <" + ((Button)src).getLabel() + ">"); } else { - Sysout.println(e.paramString() + " on "); + System.out.println(e.paramString() + " on "); } } }, AWTEvent.WINDOW_EVENT_MASK | AWTEvent.WINDOW_FOCUS_EVENT_MASK | AWTEvent.FOCUS_EVENT_MASK); - setSize (200,200); + setSize (500, 200); setVisible(true); validate(); @@ -117,15 +92,15 @@ public class ActualFocusedWindowRetaining extends Applet { owner.setSize(new Dimension(400, 100)); owner.setVisible(true); owner.toFront(); - waitTillShown(owner); + Util.waitTillShown(owner); window1.setVisible(true); window2.setVisible(true); window1.toFront(); window2.toFront(); // Wait longer... - waitTillShown(window1); - waitTillShown(window2); + Util.waitTillShown(window1); + Util.waitTillShown(window2); test(); @@ -134,85 +109,39 @@ public class ActualFocusedWindowRetaining extends Applet { } public void test() { - Button[] butArr = new Button[] {testButton3, testButton2, testButton1}; Window[] winArr = new Window[] {window2, window1, owner}; step = 1; for (int i = 0; i < 3; i++) { - clickOnCheckFocusOwner(butArr[i]); - clickOnCheckFocusedWindow(frame); - clickOn(owner); - if (!checkFocusedWindow(winArr[i])) { - stopTest("Test failed: actual focused window didn't get a focus"); - } - if (!checkFocusOwner(butArr[i])) { - stopTest("Test failed: actual focus owner didn't get a focus"); - } + clickInSeriesCheckFocus(null, butArr[i], frame); + clickOwnerCheckFocus(winArr[i], butArr[i]); step++; } step = 4; - clickOnCheckFocusOwner(testButton3); - clickOnCheckFocusOwner(testButton1); - clickOnCheckFocusedWindow(frame); - clickOn(owner); - if (!checkFocusedWindow(owner)) { - stopTest("Test failed: actual focused window didn't get a focus"); - } - if (!checkFocusOwner(testButton1)) { - stopTest("Test failed: actual focus owner didn't get a focus"); - } + clickInSeriesCheckFocus(testButton3, testButton1, frame); + clickOwnerCheckFocus(owner, testButton1); step = 5; - clickOnCheckFocusOwner(testButton3); - clickOnCheckFocusOwner(testButton2); - clickOnCheckFocusedWindow(frame); - clickOn(owner); - if (!checkFocusedWindow(window1)) { - stopTest("Test failed: actual focused window didn't get a focus"); - } - if (!checkFocusOwner(testButton2)) { - stopTest("Test failed: actual focus owner didn't get a focus"); - } + clickInSeriesCheckFocus(testButton3, testButton2, frame); + clickOwnerCheckFocus(window1, testButton2); step = 6; - clickOnCheckFocusOwner(testButton1); - clickOnCheckFocusOwner(testButton2); - clickOnCheckFocusedWindow(frame); - clickOn(owner); - if (!checkFocusedWindow(window1)) { - stopTest("Test failed: actual focused window didn't get a focus"); - } - if (!checkFocusOwner(testButton2)) { - stopTest("Test failed: actual focus owner didn't get a focus"); - } + clickInSeriesCheckFocus(testButton1, testButton2, frame); + clickOwnerCheckFocus(window1, testButton2); step = 7; - clickOnCheckFocusOwner(testButton1); - clickOnCheckFocusOwner(testButton2); - clickOnCheckFocusedWindow(frame); + clickInSeriesCheckFocus(testButton1, testButton2, frame); window1.setVisible(false); - clickOn(owner); - if (!checkFocusedWindow(owner)) { - stopTest("Test failed: actual focused window didn't get a focus"); - } - if (!checkFocusOwner(testButton1)) { - stopTest("Test failed: actual focus owner didn't get a focus"); - } + Util.waitForIdle(robot); + clickOwnerCheckFocus(owner, testButton1); step = 8; window1.setVisible(true); - waitTillShown(window1); - clickOnCheckFocusOwner(testButton2); - clickOnCheckFocusedWindow(frame); - clickOn(owner); - if (!checkFocusedWindow(window1)) { - stopTest("Test failed: actual focused window didn't get a focus"); - } - if (!checkFocusOwner(testButton2)) { - stopTest("Test failed: actual focus owner didn't get a focus"); - } + Util.waitTillShown(window1); + clickInSeriesCheckFocus(null, testButton2, frame); + clickOwnerCheckFocus(window1, testButton2); } boolean checkFocusOwner(Component comp) { @@ -223,56 +152,46 @@ public class ActualFocusedWindowRetaining extends Applet { return (win == KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusedWindow()); } - void waitTillShown(Component c) { - ((sun.awt.SunToolkit) Toolkit.getDefaultToolkit()).realSync(); + void clickOwnerCheckFocus(Window focusedWindow, Component focusedComp) { + Util.clickOnTitle(owner, robot); + robot.delay(500); + + if (!checkFocusedWindow(focusedWindow)) { + stopTest("Test failed: actual focused window didn't get a focus"); + } + if (!checkFocusOwner(focusedComp)) { + stopTest("Test failed: actual focus owner didn't get a focus"); + } + } + + void clickInSeriesCheckFocus(Component comp1, Component comp2, Frame frame) { + if (comp1 != null) { + clickOnCheckFocusOwner(comp1); + } + if (comp2 != null) { + clickOnCheckFocusOwner(comp2); + } + clickOnCheckFocusedWindow(frame); } void clickOnCheckFocusOwner(Component c) { - clickOn(c); + Util.clickOnComp(c, robot); + robot.delay(500); + if (!checkFocusOwner(c)) { stopTest("Error: can't bring a focus on Component by clicking on it"); } } void clickOnCheckFocusedWindow(Frame f) { - clickOn(f); + Util.clickOnTitle(f, robot); + robot.delay(500); + if (!checkFocusedWindow(f)) { stopTest("Error: can't bring a focus on Frame by clicking on it"); } } - void clickOn(Component c) - { - Point p = c.getLocationOnScreen(); - Dimension d = c.getSize(); - - if (c instanceof Frame) { - robot.mouseMove(p.x + (int)(d.getWidth()/2), p.y + ((Frame)c).getInsets().top/2); - } else { - robot.mouseMove(p.x + (int)(d.getWidth()/2), p.y + (int)(d.getHeight()/2)); - } - - pause(100); - robot.mousePress(InputEvent.BUTTON1_MASK); - pause(100); - robot.mouseRelease(InputEvent.BUTTON1_MASK); - - waitForIdle(); - } - - void waitForIdle() { - ((sun.awt.SunToolkit) Toolkit.getDefaultToolkit()).realSync(); - } - - void pause(int msec) { - try { - Thread.sleep(msec); - } catch (InterruptedException e) { - Sysout.println("pause: non-fatal exception caught:"); - e.printStackTrace(); - } - } - void stopTest(String msg) { throw new RuntimeException(new String("Step " + step + ": " + msg)); } @@ -290,141 +209,3 @@ class TestWindow extends Window { setBackground(Color.green); } } - - -/**************************************************** - Standard Test Machinery - DO NOT modify anything below -- it's a standard - chunk of code whose purpose is to make user - interaction uniform, and thereby make it simpler - to read and understand someone else's test. - ****************************************************/ - -/** - This is part of the standard test machinery. - It creates a dialog (with the instructions), and is the interface - for sending text messages to the user. - To print the instructions, send an array of strings to Sysout.createDialog - WithInstructions method. Put one line of instructions per array entry. - To display a message for the tester to see, simply call Sysout.println - with the string to be displayed. - This mimics System.out.println but works within the test harness as well - as standalone. - */ - -class Sysout -{ - private static TestDialog dialog; - - public static void createDialogWithInstructions( String[] instructions ) - { - dialog = new TestDialog( new Frame(), "Instructions" ); - dialog.printInstructions( instructions ); - dialog.setVisible(true); - println( "Any messages for the tester will display here." ); - } - - public static void createDialog( ) - { - dialog = new TestDialog( new Frame(), "Instructions" ); - String[] defInstr = { "Instructions will appear here. ", "" } ; - dialog.printInstructions( defInstr ); - dialog.setVisible(true); - println( "Any messages for the tester will display here." ); - } - - - public static void printInstructions( String[] instructions ) - { - dialog.printInstructions( instructions ); - } - - - public static void println( String messageIn ) - { - dialog.displayMessage( messageIn ); - } - -}// Sysout class - -/** - This is part of the standard test machinery. It provides a place for the - test instructions to be displayed, and a place for interactive messages - to the user to be displayed. - To have the test instructions displayed, see Sysout. - To have a message to the user be displayed, see Sysout. - Do not call anything in this dialog directly. - */ -class TestDialog extends Dialog -{ - - TextArea instructionsText; - TextArea messageText; - int maxStringLength = 80; - - //DO NOT call this directly, go through Sysout - public TestDialog( Frame frame, String name ) - { - super( frame, name ); - int scrollBoth = TextArea.SCROLLBARS_BOTH; - instructionsText = new TextArea( "", 15, maxStringLength, scrollBoth ); - add( "North", instructionsText ); - - messageText = new TextArea( "", 5, maxStringLength, scrollBoth ); - add("Center", messageText); - - pack(); - - setVisible(true); - }// TestDialog() - - //DO NOT call this directly, go through Sysout - public void printInstructions( String[] instructions ) - { - //Clear out any current instructions - instructionsText.setText( "" ); - - //Go down array of instruction strings - - String printStr, remainingStr; - for( int i=0; i < instructions.length; i++ ) - { - //chop up each into pieces maxSringLength long - remainingStr = instructions[ i ]; - while( remainingStr.length() > 0 ) - { - //if longer than max then chop off first max chars to print - if( remainingStr.length() >= maxStringLength ) - { - //Try to chop on a word boundary - int posOfSpace = remainingStr. - lastIndexOf( ' ', maxStringLength - 1 ); - - if( posOfSpace <= 0 ) posOfSpace = maxStringLength - 1; - - printStr = remainingStr.substring( 0, posOfSpace + 1 ); - remainingStr = remainingStr.substring( posOfSpace + 1 ); - } - //else just print - else - { - printStr = remainingStr; - remainingStr = ""; - } - - instructionsText.append( printStr + "\n" ); - - }// while - - }// for - - }//printInstructions() - - //DO NOT call this directly, go through Sysout - public void displayMessage( String messageIn ) - { - messageText.append( messageIn + "\n" ); - System.out.println(messageIn); - } - -}// TestDialog class diff --git a/jdk/test/java/awt/Focus/FrameJumpingToMouse/FrameJumpingToMouse.java b/jdk/test/java/awt/Focus/FrameJumpingToMouse/FrameJumpingToMouse.java index 54928d2988b..510a65cfa7e 100644 --- a/jdk/test/java/awt/Focus/FrameJumpingToMouse/FrameJumpingToMouse.java +++ b/jdk/test/java/awt/Focus/FrameJumpingToMouse/FrameJumpingToMouse.java @@ -22,238 +22,65 @@ */ /* -test -@bug 4752312 -@summary Tests that after moving non-focusable window it ungrabs mouse pointer -@author dom@sparc.spb.su: area=awt.focus -@run applet FrameJumpingToMouse.html + @test + @bug 4752312 + @summary Tests that after moving non-focusable window it ungrabs mouse pointer + @author Denis Mikhalkin: area=awt.focus + @library ../../regtesthelpers + @build Util + @run main FrameJumpingToMouse */ -// Note there is no @ in front of test above. This is so that the -// harness will not mistake this file as a test file. It should -// only see the html file as a test file. (the harness runs all -// valid test files, so it would run this test twice if this file -// were valid as well as the html file.) -// Also, note the area= after Your Name in the author tag. Here, you -// should put which functional area the test falls in. See the -// AWT-core home page -> test areas and/or -> AWT team for a list of -// areas. -// Note also the 'FrameJumpingToMouse.html' in the run tag. This should -// be changed to the name of the test. - - -/** - * FrameJumpingToMouse.java - * - * summary: - */ - import java.applet.Applet; -import java.awt.*; -import java.awt.event.*; +import java.awt.BorderLayout; +import java.awt.Dialog; +import java.awt.Frame; +import java.awt.Point; +import java.awt.Robot; +import java.awt.TextArea; +import java.awt.Toolkit; +import java.awt.event.InputEvent; import javax.swing.JFrame; - -//Automated tests should run as applet tests if possible because they -// get their environments cleaned up, including AWT threads, any -// test created threads, and any system resources used by the test -// such as file descriptors. (This is normally not a problem as -// main tests usually run in a separate VM, however on some platforms -// such as the Mac, separate VMs are not possible and non-applet -// tests will cause problems). Also, you don't have to worry about -// synchronisation stuff in Applet tests they way you do in main -// tests... - +import test.java.awt.regtesthelpers.Util; public class FrameJumpingToMouse extends Applet { - //Declare things used in the test, like buttons and labels here JFrame frame = new JFrame("Test jumping frame"); - Robot robot = null; - public void init() - { - //Create instructions for the user here, as well as set up - // the environment -- set the layout manager, add buttons, - // etc. + Robot robot = Util.createRobot(); - this.setLayout (new BorderLayout ()); + public static void main(String[] args) { + FrameJumpingToMouse test = new FrameJumpingToMouse(); + test.init(); + test.start(); + } + public void init() { frame.setFocusableWindowState(false); frame.setBounds(100, 100, 100, 100); - }//End init() - - public void start () - { - //Get things going. Request focus, set size, et cetera - setSize (200,200); - setVisible(true); - validate(); - - try { - robot = new Robot(); - } catch (Exception e) { - throw new RuntimeException("Can't create robot"); - } + } + public void start() { frame.setVisible(true); + Util.waitTillShown(frame); - robot.delay(1000); - - Point frameLoc = frame.getLocationOnScreen(); - robot.mouseMove(frameLoc.x+frame.getWidth()/4, frameLoc.y+frame.getInsets().top/2); + Point loc = frame.getLocationOnScreen(); + robot.mouseMove(loc.x + frame.getWidth() / 4, loc.y + frame.getInsets().top / 2); + robot.delay(50); robot.mousePress(InputEvent.BUTTON1_MASK); - robot.mouseMove(frameLoc.x+100, frameLoc.y+50); + robot.delay(50); + robot.mouseMove(loc.x + 100, loc.y + 50); + robot.delay(50); robot.mouseRelease(InputEvent.BUTTON1_MASK); - Toolkit.getDefaultToolkit().sync(); - robot.waitForIdle(); - frameLoc = frame.getLocation(); + Util.waitForIdle(robot); - robot.mouseMove(frameLoc.x+frame.getWidth()/2, frameLoc.y+frame.getHeight()/2); + loc = frame.getLocation(); + robot.mouseMove(loc.x + frame.getWidth() / 2, loc.y + frame.getHeight() / 2); + Util.waitForIdle(robot); - Toolkit.getDefaultToolkit().sync(); - robot.waitForIdle(); - - if (!(frame.getLocation().equals(frameLoc))) { - throw new RuntimeException("Frame is moving to mouse with grab"); + if (!(frame.getLocation().equals(loc))) { + throw new RuntimeException("Test failed: frame is moving to mouse with grab!"); } - }// start() - -}// class FrameJumpingToMouse - - -/**************************************************** - Standard Test Machinery - DO NOT modify anything below -- it's a standard - chunk of code whose purpose is to make user - interaction uniform, and thereby make it simpler - to read and understand someone else's test. - ****************************************************/ - -/** - This is part of the standard test machinery. - It creates a dialog (with the instructions), and is the interface - for sending text messages to the user. - To print the instructions, send an array of strings to Sysout.createDialog - WithInstructions method. Put one line of instructions per array entry. - To display a message for the tester to see, simply call Sysout.println - with the string to be displayed. - This mimics System.out.println but works within the test harness as well - as standalone. - */ - -class Sysout -{ - private static TestDialog dialog; - - public static void createDialogWithInstructions( String[] instructions ) - { - dialog = new TestDialog( new Frame(), "Instructions" ); - dialog.printInstructions( instructions ); - dialog.setVisible(true); - println( "Any messages for the tester will display here." ); + System.out.println("Test passed."); } - - public static void createDialog( ) - { - dialog = new TestDialog( new Frame(), "Instructions" ); - String[] defInstr = { "Instructions will appear here. ", "" } ; - dialog.printInstructions( defInstr ); - dialog.setVisible(true); - println( "Any messages for the tester will display here." ); - } - - - public static void printInstructions( String[] instructions ) - { - dialog.printInstructions( instructions ); - } - - - public static void println( String messageIn ) - { - dialog.displayMessage( messageIn ); - } - -}// Sysout class - -/** - This is part of the standard test machinery. It provides a place for the - test instructions to be displayed, and a place for interactive messages - to the user to be displayed. - To have the test instructions displayed, see Sysout. - To have a message to the user be displayed, see Sysout. - Do not call anything in this dialog directly. - */ -class TestDialog extends Dialog -{ - - TextArea instructionsText; - TextArea messageText; - int maxStringLength = 80; - - //DO NOT call this directly, go through Sysout - public TestDialog( Frame frame, String name ) - { - super( frame, name ); - int scrollBoth = TextArea.SCROLLBARS_BOTH; - instructionsText = new TextArea( "", 15, maxStringLength, scrollBoth ); - add( "North", instructionsText ); - - messageText = new TextArea( "", 5, maxStringLength, scrollBoth ); - add("Center", messageText); - - pack(); - - show(); - }// TestDialog() - - //DO NOT call this directly, go through Sysout - public void printInstructions( String[] instructions ) - { - //Clear out any current instructions - instructionsText.setText( "" ); - - //Go down array of instruction strings - - String printStr, remainingStr; - for( int i=0; i < instructions.length; i++ ) - { - //chop up each into pieces maxSringLength long - remainingStr = instructions[ i ]; - while( remainingStr.length() > 0 ) - { - //if longer than max then chop off first max chars to print - if( remainingStr.length() >= maxStringLength ) - { - //Try to chop on a word boundary - int posOfSpace = remainingStr. - lastIndexOf( ' ', maxStringLength - 1 ); - - if( posOfSpace <= 0 ) posOfSpace = maxStringLength - 1; - - printStr = remainingStr.substring( 0, posOfSpace + 1 ); - remainingStr = remainingStr.substring( posOfSpace + 1 ); - } - //else just print - else - { - printStr = remainingStr; - remainingStr = ""; - } - - instructionsText.append( printStr + "\n" ); - - }// while - - }// for - - }//printInstructions() - - //DO NOT call this directly, go through Sysout - public void displayMessage( String messageIn ) - { - messageText.append( messageIn + "\n" ); - System.out.println(messageIn); - } - -}// TestDialog class +} diff --git a/jdk/test/java/awt/Focus/NonFocusableWindowTest/Test.java b/jdk/test/java/awt/Focus/NonFocusableWindowTest/NoEventsTest.java similarity index 92% rename from jdk/test/java/awt/Focus/NonFocusableWindowTest/Test.java rename to jdk/test/java/awt/Focus/NonFocusableWindowTest/NoEventsTest.java index e3e7d0645a8..4375385e5b6 100644 --- a/jdk/test/java/awt/Focus/NonFocusableWindowTest/Test.java +++ b/jdk/test/java/awt/Focus/NonFocusableWindowTest/NoEventsTest.java @@ -20,19 +20,20 @@ * CA 95054 USA or visit www.sun.com if you need additional information or * have any questions. */ + /* @test @bug 4452384 @summary Tests that non-focusable windows doesn't generate any focus events when accessed. - @author dom: area=awt.focus - @run main Test + @author Denis.Mikhalkin: area=awt.focus + @run main NoEventsTest */ import java.awt.*; import java.awt.event.*; import java.util.*; -public class Test extends Frame { +public class NoEventsTest extends Frame { public static final int DEF_WIDTH = 400, DEF_HEIGHT = 300, DEF_TOP = 1, @@ -80,8 +81,8 @@ public class Test extends Frame { windows = new Window[7]; windows[0] = new TestWindow(0, 0, false, main_frame); //windows[1] = new TestWindow(2, 1, true, main_frame); - windows[2] = new Test(1, 0, false, true); - windows[3] = new Test(2, 0, false, false); + windows[2] = new NoEventsTest(1, 0, false, true); + windows[3] = new NoEventsTest(2, 0, false, false); //windows[4] = new Test(3, 0, true, true); windows[5] = new TestDialog(0, 1, false, true, main_frame); windows[6] = new TestDialog(1, 1, false, false, main_frame); @@ -174,12 +175,12 @@ public class Test extends Frame { } } } - public Test(int row, int col, boolean focusable, boolean resizable) { + public NoEventsTest(int row, int col, boolean focusable, boolean resizable) { super("Frame" + row + "" + col); TestPanel panel = new TestPanel(row, col); - if (Test.automatic) { - row = Test.DEF_ROW; - col = Test.DEF_COL; + if (NoEventsTest.automatic) { + row = NoEventsTest.DEF_ROW; + col = NoEventsTest.DEF_COL; } setName(getTitle()); add("Center", panel); @@ -187,7 +188,7 @@ public class Test extends Frame { ", " + (resizable?"resizable":"non-resizable")); l.setBackground(Color.green); add("North", l); - setBounds(Test.DEF_LEFT + DEF_WIDTH*col, DEF_TOP + DEF_HEIGHT*row, DEF_WIDTH, DEF_HEIGHT); + setBounds(NoEventsTest.DEF_LEFT + DEF_WIDTH*col, DEF_TOP + DEF_HEIGHT*row, DEF_WIDTH, DEF_HEIGHT); if (!focusable) { setFocusableWindowState(false); } @@ -202,9 +203,9 @@ class TestWindow extends Window { super(owner); setName("Window" + row + "" + col); TestPanel panel = new TestPanel(row, col); - if (Test.automatic) { - row = Test.DEF_ROW; - col = Test.DEF_COL; + if (NoEventsTest.automatic) { + row = NoEventsTest.DEF_ROW; + col = NoEventsTest.DEF_COL; } add("Center", panel); @@ -213,7 +214,7 @@ class TestWindow extends Window { l.setBackground(Color.green); add("North", l); - setBounds(Test.DEF_LEFT + Test.DEF_WIDTH*col, Test.DEF_TOP + Test.DEF_HEIGHT*row, Test.DEF_WIDTH, Test.DEF_HEIGHT); + setBounds(NoEventsTest.DEF_LEFT + NoEventsTest.DEF_WIDTH*col, NoEventsTest.DEF_TOP + NoEventsTest.DEF_HEIGHT*row, NoEventsTest.DEF_WIDTH, NoEventsTest.DEF_HEIGHT); if (!focusable) { setFocusableWindowState(false); } @@ -225,9 +226,9 @@ class TestDialog extends Dialog { super(owner); setName("Dialog" + row + "" + col); TestPanel panel = new TestPanel(row, col); - if (Test.automatic) { - row = Test.DEF_ROW; - col = Test.DEF_COL; + if (NoEventsTest.automatic) { + row = NoEventsTest.DEF_ROW; + col = NoEventsTest.DEF_COL; } add("Center", panel); @@ -236,7 +237,7 @@ class TestDialog extends Dialog { l.setBackground(Color.green); add("North", l); - setBounds(Test.DEF_LEFT + Test.DEF_WIDTH*col, Test.DEF_TOP + Test.DEF_HEIGHT*row, Test.DEF_WIDTH, Test.DEF_HEIGHT); + setBounds(NoEventsTest.DEF_LEFT + NoEventsTest.DEF_WIDTH*col, NoEventsTest.DEF_TOP + NoEventsTest.DEF_HEIGHT*row, NoEventsTest.DEF_WIDTH, NoEventsTest.DEF_HEIGHT); if (!focusable) { setFocusableWindowState(false); } @@ -415,3 +416,5 @@ class GlobalListener implements AWTEventListener { // } } } + + diff --git a/jdk/test/java/awt/Focus/NonFocusableWindowTest/NonfocusableOwnerTest.java b/jdk/test/java/awt/Focus/NonFocusableWindowTest/NonfocusableOwnerTest.java index 087eba9dea5..74c124b294b 100644 --- a/jdk/test/java/awt/Focus/NonFocusableWindowTest/NonfocusableOwnerTest.java +++ b/jdk/test/java/awt/Focus/NonFocusableWindowTest/NonfocusableOwnerTest.java @@ -25,8 +25,10 @@ @test @bug 6182359 @summary Tests that Window having non-focusable owner can't be a focus owner. - @author Anton Tarasov: area=awt.focus - @run applet NonfocusableOwnerTest.html + @author Anton.Tarasov: area=awt.focus + @library ../../regtesthelpers + @build Util + @run main NonfocusableOwnerTest */ import java.awt.*; @@ -34,319 +36,124 @@ import java.awt.event.*; import java.applet.Applet; import java.lang.reflect.*; import java.io.*; +import test.java.awt.regtesthelpers.Util; public class NonfocusableOwnerTest extends Applet { - Robot robot; + Robot robot = Util.createRobot(); Frame frame; Dialog dialog; Window window1; Window window2; Button button = new Button("button"); -// PrintStream Sysout = System.out; public static void main(String[] args) { NonfocusableOwnerTest test = new NonfocusableOwnerTest(); - test.init(); test.start(); } - public void init() { - try { - robot = new Robot(); - } catch (AWTException e) { - throw new RuntimeException("Error: unable to create robot", e); - } - // Create instructions for the user here, as well as set up - // the environment -- set the layout manager, add buttons, - // etc. - this.setLayout (new BorderLayout ()); - } - public void start() { Toolkit.getDefaultToolkit().addAWTEventListener(new AWTEventListener() { public void eventDispatched(AWTEvent e) { - Sysout.println(e.toString()); + System.out.println(e.toString()); } }, FocusEvent.FOCUS_EVENT_MASK | WindowEvent.WINDOW_FOCUS_EVENT_MASK | WindowEvent.WINDOW_EVENT_MASK); frame = new Frame("Frame"); frame.setName("Frame-owner"); + frame.setBounds(100, 0, 100, 100); dialog = new Dialog(frame, "Dialog"); dialog.setName("Dialog-owner"); + dialog.setBounds(100, 0, 100, 100); window1 = new Window(frame); window1.setName("1st child"); + window1.setBounds(100, 300, 100, 100); window2 = new Window(window1); window2.setName("2nd child"); + window2.setBounds(100, 500, 100, 100); test1(frame, window1); test2(frame, window1, window2); test3(frame, window1, window2); window1 = new Window(dialog); + window1.setBounds(100, 300, 100, 100); window1.setName("1st child"); window2 = new Window(window1); window2.setName("2nd child"); + window2.setBounds(100, 500, 100, 100); test1(dialog, window1); test2(dialog, window1, window2); test3(dialog, window1, window2); - Sysout.println("Test passed."); + System.out.println("Test passed."); } void test1(Window owner, Window child) { - Sysout.println("* * * STAGE 1 * * *\nowner=" + owner); + System.out.println("* * * STAGE 1 * * *\nWindow owner: " + owner); owner.setFocusableWindowState(false); - owner.setSize(100, 100); owner.setVisible(true); child.add(button); - child.setBounds(0, 300, 100, 100); child.setVisible(true); - waitTillShown(child); + Util.waitTillShown(child); - clickOn(button); + Util.clickOnComp(button, robot); if (button == KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner()) { throw new RuntimeException("Test Failed."); } - owner.dispose(); child.dispose(); + owner.dispose(); } void test2(Window owner, Window child1, Window child2) { - Sysout.println("* * * STAGE 2 * * *\nowner=" + owner); + System.out.println("* * * STAGE 2 * * *\nWindow nowner: " + owner); owner.setFocusableWindowState(false); - owner.setSize(100, 100); owner.setVisible(true); child1.setFocusableWindowState(true); - child1.setBounds(0, 300, 100, 100); child1.setVisible(true); child2.add(button); - child2.setBounds(0, 500, 100, 100); child2.setVisible(true); - clickOn(button); + Util.waitTillShown(child2); + + Util.clickOnComp(button, robot); if (button == KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner()) { throw new RuntimeException("Test failed."); } - owner.dispose(); - child1.dispose(); child2.dispose(); + child1.dispose(); + owner.dispose(); } void test3(Window owner, Window child1, Window child2) { - Sysout.println("* * * STAGE 3 * * *\nowner=" + owner); + System.out.println("* * * STAGE 3 * * *\nWidow owner: " + owner); owner.setFocusableWindowState(true); - owner.setSize(100, 100); owner.setVisible(true); child1.setFocusableWindowState(false); - child1.setBounds(0, 300, 100, 100); child1.setVisible(true); child2.setFocusableWindowState(true); child2.add(button); - child2.setBounds(0, 500, 100, 100); child2.setVisible(true); - clickOn(button); + Util.waitTillShown(child2); + Util.clickOnComp(button, robot); System.err.println("focus owner: " + KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner()); if (button != KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner()) { throw new RuntimeException("Test failed."); } - owner.dispose(); child1.dispose(); child2.dispose(); - } - - void clickOn(Component c) { - Point p = c.getLocationOnScreen(); - Dimension d = c.getSize(); - - Sysout.println("Clicking " + c); - - if (c instanceof Frame) { - robot.mouseMove(p.x + (int)(d.getWidth()/2), p.y + ((Frame)c).getInsets().top/2); - } else { - robot.mouseMove(p.x + (int)(d.getWidth()/2), p.y + (int)(d.getHeight()/2)); - } - robot.mousePress(InputEvent.BUTTON1_MASK); - robot.mouseRelease(InputEvent.BUTTON1_MASK); - waitForIdle(); - } - - void waitTillShown(Component c) { - while (true) { - try { - Thread.sleep(100); - c.getLocationOnScreen(); - break; - } catch (InterruptedException e) { - throw new RuntimeException(e); - } catch (IllegalComponentStateException e) {} - } - } - void waitForIdle() { - try { - Toolkit.getDefaultToolkit().sync(); - sun.awt.SunToolkit.flushPendingEvents(); - EventQueue.invokeAndWait( new Runnable() { - public void run() {} // Dummy implementation - }); - } catch(InterruptedException ie) { - Sysout.println("waitForIdle, non-fatal exception caught:"); - ie.printStackTrace(); - } catch(InvocationTargetException ite) { - Sysout.println("waitForIdle, non-fatal exception caught:"); - ite.printStackTrace(); - } - - // wait longer... - robot.delay(200); + owner.dispose(); } } - -/**************************************************** - Standard Test Machinery - DO NOT modify anything below -- it's a standard - chunk of code whose purpose is to make user - interaction uniform, and thereby make it simpler - to read and understand someone else's test. - ****************************************************/ - -/** - This is part of the standard test machinery. - It creates a dialog (with the instructions), and is the interface - for sending text messages to the user. - To print the instructions, send an array of strings to Sysout.createDialog - WithInstructions method. Put one line of instructions per array entry. - To display a message for the tester to see, simply call Sysout.println - with the string to be displayed. - This mimics System.out.println but works within the test harness as well - as standalone. - */ - -class Sysout -{ - static TestDialog dialog; - - public static void createDialogWithInstructions( String[] instructions ) - { - dialog = new TestDialog( new Frame(), "Instructions" ); - dialog.printInstructions( instructions ); - dialog.setVisible(true); - println( "Any messages for the tester will display here." ); - } - - public static void createDialog( ) - { - dialog = new TestDialog( new Frame(), "Instructions" ); - String[] defInstr = { "Instructions will appear here. ", "" } ; - dialog.printInstructions( defInstr ); - dialog.setVisible(true); - println( "Any messages for the tester will display here." ); - } - - - public static void printInstructions( String[] instructions ) - { - dialog.printInstructions( instructions ); - } - - - public static void println( String messageIn ) - { - System.err.println(messageIn); - } - -}// Sysout class - -/** - This is part of the standard test machinery. It provides a place for the - test instructions to be displayed, and a place for interactive messages - to the user to be displayed. - To have the test instructions displayed, see Sysout. - To have a message to the user be displayed, see Sysout. - Do not call anything in this dialog directly. - */ -class TestDialog extends Dialog -{ - - TextArea instructionsText; - TextArea messageText; - int maxStringLength = 80; - - //DO NOT call this directly, go through Sysout - public TestDialog( Frame frame, String name ) - { - super( frame, name ); - int scrollBoth = TextArea.SCROLLBARS_BOTH; - instructionsText = new TextArea( "", 15, maxStringLength, scrollBoth ); - add( "North", instructionsText ); - - messageText = new TextArea( "", 5, maxStringLength, scrollBoth ); - add("Center", messageText); - - pack(); - - setVisible(true); - }// TestDialog() - - //DO NOT call this directly, go through Sysout - public void printInstructions( String[] instructions ) - { - //Clear out any current instructions - instructionsText.setText( "" ); - - //Go down array of instruction strings - - String printStr, remainingStr; - for( int i=0; i < instructions.length; i++ ) - { - //chop up each into pieces maxSringLength long - remainingStr = instructions[ i ]; - while( remainingStr.length() > 0 ) - { - //if longer than max then chop off first max chars to print - if( remainingStr.length() >= maxStringLength ) - { - //Try to chop on a word boundary - int posOfSpace = remainingStr. - lastIndexOf( ' ', maxStringLength - 1 ); - - if( posOfSpace <= 0 ) posOfSpace = maxStringLength - 1; - - printStr = remainingStr.substring( 0, posOfSpace + 1 ); - remainingStr = remainingStr.substring( posOfSpace + 1 ); - } - //else just print - else - { - printStr = remainingStr; - remainingStr = ""; - } - - instructionsText.append( printStr + "\n" ); - - }// while - - }// for - - }//printInstructions() - - //DO NOT call this directly, go through Sysout - public void displayMessage( String messageIn ) - { - messageText.append( messageIn + "\n" ); - System.out.println(messageIn); - } - -}// TestDialog class diff --git a/jdk/test/java/awt/Focus/TypeAhead/TestFocusFreeze.java b/jdk/test/java/awt/Focus/TypeAhead/TestFocusFreeze.java index 129cdc2811e..69f78e3640d 100644 --- a/jdk/test/java/awt/Focus/TypeAhead/TestFocusFreeze.java +++ b/jdk/test/java/awt/Focus/TypeAhead/TestFocusFreeze.java @@ -22,467 +22,118 @@ */ /* -@test -@bug 6183877 6216005 6225560 -@summary Tests that keyboard input doesn't freeze due to type-ahead problems -@author Denis Mikhalkin: area=awt.focus -@run main/timeout=300 TestFocusFreeze + @test + @bug 6183877 6216005 6225560 + @library ../../regtesthelpers + @build Util + @summary Tests that keyboard input doesn't freeze due to type-ahead problems + @author Denis.Mikhalkin, Anton.Tarasov: area=awt.focus + @run main TestFocusFreeze */ -// Note the area= after Your Name in the author tag. Here, you -// should put which functional area the test falls in. See the -// AWT-core home page -> test areas and/or -> AWT team for a list of -// areas. +import java.awt.Component; +import java.awt.DefaultKeyboardFocusManager; +import java.awt.KeyboardFocusManager; +import java.awt.Robot; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.KeyEvent; +import java.util.concurrent.atomic.AtomicBoolean; +import javax.swing.JButton; +import javax.swing.JDialog; +import javax.swing.JFrame; +import test.java.awt.regtesthelpers.Util; + +public class TestFocusFreeze { + private static JFrame frame; + private static JDialog dialog; + private static JButton dlgButton; + private static JButton frameButton; + private static AtomicBoolean lock = new AtomicBoolean(false); + private static Robot robot = Util.createRobot(); + + public static void main(String[] args) { + boolean all_passed = true; + KeyboardFocusManager testKFM = new TestKFM(robot); + KeyboardFocusManager defKFM = KeyboardFocusManager.getCurrentKeyboardFocusManager(); - -/** - * TestFocusFreeze.java - * - * summary: XXX A brief summary of what this tests - */ - -import java.awt.*; -import java.awt.event.*; -import javax.swing.*; -import java.util.concurrent.atomic.*; -import sun.awt.SunToolkit; - -public class TestFocusFreeze -{ - - //*** test-writer defined static variables go here *** - - - private static void init() - { - //*** Create instructions for the user here *** - - FocusTest.test(); - - }//End init() - - - - /***************************************************** - * Standard Test Machinery Section - * DO NOT modify anything in this section -- it's a - * standard chunk of code which has all of the - * synchronisation necessary for the test harness. - * By keeping it the same in all tests, it is easier - * to read and understand someone else's test, as - * well as insuring that all tests behave correctly - * with the test harness. - * There is a section following this for test- - * classes - ******************************************************/ - private static boolean theTestPassed = false; - private static boolean testGeneratedInterrupt = false; - private static String failureMessage = ""; - - private static Thread mainThread = null; - - private static int sleepTime = 300000; - - // Not sure about what happens if multiple of this test are - // instantiated in the same VM. Being static (and using - // static vars), it aint gonna work. Not worrying about - // it for now. - public static void main( String args[] ) throws InterruptedException - { - mainThread = Thread.currentThread(); - try - { - init(); - } - catch( TestPassedException e ) - { - //The test passed, so just return from main and harness will - // interepret this return as a pass - return; - } - //At this point, neither test pass nor test fail has been - // called -- either would have thrown an exception and ended the - // test, so we know we have multiple threads. - - //Test involves other threads, so sleep and wait for them to - // called pass() or fail() - try - { - Thread.sleep( sleepTime ); - //Timed out, so fail the test - throw new RuntimeException( "Timed out after " + sleepTime/1000 + " seconds" ); - } - catch (InterruptedException e) - { - //The test harness may have interrupted the test. If so, rethrow the exception - // so that the harness gets it and deals with it. - if( ! testGeneratedInterrupt ) throw e; - - //reset flag in case hit this code more than once for some reason (just safety) - testGeneratedInterrupt = false; - - if ( theTestPassed == false ) - { - throw new RuntimeException( failureMessage ); - } - } - - }//main - - public static synchronized void setTimeoutTo( int seconds ) - { - sleepTime = seconds * 1000; - } - - public static synchronized void pass() - { - Sysout.println( "The test passed." ); - Sysout.println( "The test is over, hit Ctl-C to stop Java VM" ); - //first check if this is executing in main thread - if ( mainThread == Thread.currentThread() ) - { - //Still in the main thread, so set the flag just for kicks, - // and throw a test passed exception which will be caught - // and end the test. - theTestPassed = true; - throw new TestPassedException(); - } - theTestPassed = true; - testGeneratedInterrupt = true; - mainThread.interrupt(); - }//pass() - - public static synchronized void fail() - { - //test writer didn't specify why test failed, so give generic - fail( "it just plain failed! :-)" ); - } - - public static synchronized void fail( String whyFailed ) - { - Sysout.println( "The test failed: " + whyFailed ); - Sysout.println( "The test is over, hit Ctl-C to stop Java VM" ); - //check if this called from main thread - if ( mainThread == Thread.currentThread() ) - { - //If main thread, fail now 'cause not sleeping - throw new RuntimeException( whyFailed ); - } - theTestPassed = false; - testGeneratedInterrupt = true; - failureMessage = whyFailed; - mainThread.interrupt(); - }//fail() - -}// class TestFocusFreeze - -//This exception is used to exit from any level of call nesting -// when it's determined that the test has passed, and immediately -// end the test. -class TestPassedException extends RuntimeException -{ -} - -//*********** End Standard Test Machinery Section ********** - - -//************ Begin classes defined for the test **************** - -// if want to make listeners, here is the recommended place for them, then instantiate -// them in init() - -/* Example of a class which may be written as part of a test -class NewClass implements anInterface - { - static int newVar = 0; - - public void eventDispatched(AWTEvent e) - { - //Counting events to see if we get enough - eventCount++; - - if( eventCount == 20 ) - { - //got enough events, so pass - - TestFocusFreeze.pass(); - } - else if( tries == 20 ) - { - //tried too many times without getting enough events so fail - - TestFocusFreeze.fail(); - } - - }// eventDispatched() - - }// NewClass class - -*/ - - -//************** End classes defined for the test ******************* - - - - -/**************************************************** - Standard Test Machinery - DO NOT modify anything below -- it's a standard - chunk of code whose purpose is to make user - interaction uniform, and thereby make it simpler - to read and understand someone else's test. - ****************************************************/ - -/** - This is part of the standard test machinery. - It creates a dialog (with the instructions), and is the interface - for sending text messages to the user. - To print the instructions, send an array of strings to Sysout.createDialog - WithInstructions method. Put one line of instructions per array entry. - To display a message for the tester to see, simply call Sysout.println - with the string to be displayed. - This mimics System.out.println but works within the test harness as well - as standalone. - */ - -class Sysout -{ - private static TestDialog dialog; - - public static void createDialogWithInstructions( String[] instructions ) - { - dialog = new TestDialog( new Frame(), "Instructions" ); - dialog.printInstructions( instructions ); - dialog.setVisible(true); - println( "Any messages for the tester will display here." ); - } - - public static void createDialog( ) - { - dialog = new TestDialog( new Frame(), "Instructions" ); - String[] defInstr = { "Instructions will appear here. ", "" } ; - dialog.printInstructions( defInstr ); - dialog.setVisible(true); - println( "Any messages for the tester will display here." ); - } - - - public static void printInstructions( String[] instructions ) - { - dialog.printInstructions( instructions ); - } - - - public static void println( String messageIn ) - { - System.out.println(messageIn); - } - -}// Sysout class - -/** - This is part of the standard test machinery. It provides a place for the - test instructions to be displayed, and a place for interactive messages - to the user to be displayed. - To have the test instructions displayed, see Sysout. - To have a message to the user be displayed, see Sysout. - Do not call anything in this dialog directly. - */ -class TestDialog extends Dialog -{ - - TextArea instructionsText; - TextArea messageText; - int maxStringLength = 80; - - //DO NOT call this directly, go through Sysout - public TestDialog( Frame frame, String name ) - { - super( frame, name ); - int scrollBoth = TextArea.SCROLLBARS_BOTH; - instructionsText = new TextArea( "", 15, maxStringLength, scrollBoth ); - add( "North", instructionsText ); - - messageText = new TextArea( "", 5, maxStringLength, scrollBoth ); - add("Center", messageText); - - pack(); - - setVisible(true); - }// TestDialog() - - //DO NOT call this directly, go through Sysout - public void printInstructions( String[] instructions ) - { - //Clear out any current instructions - instructionsText.setText( "" ); - - //Go down array of instruction strings - - String printStr, remainingStr; - for( int i=0; i < instructions.length; i++ ) - { - //chop up each into pieces maxSringLength long - remainingStr = instructions[ i ]; - while( remainingStr.length() > 0 ) - { - //if longer than max then chop off first max chars to print - if( remainingStr.length() >= maxStringLength ) - { - //Try to chop on a word boundary - int posOfSpace = remainingStr. - lastIndexOf( ' ', maxStringLength - 1 ); - - if( posOfSpace <= 0 ) posOfSpace = maxStringLength - 1; - - printStr = remainingStr.substring( 0, posOfSpace + 1 ); - remainingStr = remainingStr.substring( posOfSpace + 1 ); - } - //else just print - else - { - printStr = remainingStr; - remainingStr = ""; - } - - instructionsText.append( printStr + "\n" ); - - }// while - - }// for - - }//printInstructions() - - //DO NOT call this directly, go through Sysout - public void displayMessage( String messageIn ) - { - messageText.append( messageIn + "\n" ); - System.out.println(messageIn); - } - -}// TestDialog class - - -class FocusTest extends JFrame implements ActionListener { - - private JDialog pageDialog = null; - - private AtomicBoolean passed = new AtomicBoolean(); - private static volatile boolean all_passed = true; - private static volatile long pressTime; - private static Object testLock = new Object(); - private static Object resultLock = new Object(); - - public FocusTest() { - final GraphicsConfiguration gc = - GraphicsEnvironment.getLocalGraphicsEnvironment(). - getDefaultScreenDevice().getDefaultConfiguration(); - - pageDialog = new JDialog(this, "JDialog", true, gc); - Container c = pageDialog.getContentPane(); - c.setLayout(new BorderLayout()); - JButton btnApprove =new JButton("Exit Button"); - btnApprove.addActionListener(this); - c.add("South", btnApprove); - pageDialog.pack(); - - JButton bb = new JButton("Action"); - bb.addActionListener(new ActionListener() { - final JDialog pageDialog = FocusTest.this.pageDialog; - public void actionPerformed(ActionEvent e) { - synchronized(testLock) { - testLock.notify(); - } - pageDialog.setVisible(true); - } - }); - - add(bb); - pack(); - setVisible(true); - - ((SunToolkit)Toolkit.getDefaultToolkit()).realSync(); - - bb.requestFocus(); - - ((SunToolkit)Toolkit.getDefaultToolkit()).realSync(); - - if (!bb.isFocusOwner()) { - System.err.println("Couldn't make bb focused"); - all_passed = false; - return; - } - - new Thread() { - public void run() { - try { - Robot r = new Robot(); - synchronized (testLock) { - testLock.wait(); - } - r.keyPress(KeyEvent.VK_SPACE); - r.delay(50); - r.keyRelease(KeyEvent.VK_SPACE); - synchronized(passed) { - passed.wait(1000); - } - pageDialog.dispose(); - FocusTest.this.dispose(); - if (!passed.get()) { - all_passed = false; - } - } catch (Exception e) { - e.printStackTrace(); - } - synchronized (resultLock) { - resultLock.notifyAll(); - } - } - }.start(); - - try { - Robot r = new Robot(); - r.keyPress(KeyEvent.VK_SPACE); - r.delay(50); - r.keyRelease(KeyEvent.VK_SPACE); - } catch (Exception e) { - e.printStackTrace(); - all_passed = false; - return; - } - - try { - synchronized (resultLock) { - resultLock.wait(); - } - } catch (InterruptedException ie) { - ie.printStackTrace(); - } - } - - public void actionPerformed(ActionEvent ae) { - System.err.println("Action performed"); - passed.set(true); - synchronized(passed) { - passed.notify(); - } - } - - public static void test() { - FocusTest test = null; for (int i = 0; i < 10; i++) { - test = new FocusTest(); - try { - Thread.sleep(500); - } catch (InterruptedException e) { - break; + test(testKFM, defKFM); + Util.waitForIdle(robot); + System.out.println("Iter " + i + ": " + (lock.get() ? "passed." : "failed!")); + if (!lock.get()) { + all_passed = false; } } if (!all_passed) { - TestFocusFreeze.fail("Not all passed"); - } else { - TestFocusFreeze.pass(); + throw new RuntimeException("Test failed: not all iterations passed!"); } + System.out.println("Test passed."); + } + + public static void test(final KeyboardFocusManager testKFM, final KeyboardFocusManager defKFM) { + frame = new JFrame("Frame"); + dialog = new JDialog(frame, "Dialog", true); + dlgButton = new JButton("Dialog_Button"); + frameButton = new JButton("Frame_Button"); + + lock.set(false); + + dialog.add(dlgButton); + dialog.setLocation(200, 0); + dialog.pack(); + frame.add(frameButton); + frame.pack(); + + dlgButton.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + dialog.dispose(); + frame.dispose(); + synchronized (lock) { + lock.set(true); + lock.notifyAll(); + } + } + }); + + frameButton.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + // Right before the dialog will be shown, there will be called + // enqueuKeyEvents() method. We are to catch it. + KeyboardFocusManager.setCurrentKeyboardFocusManager(testKFM); + dialog.setVisible(true); + KeyboardFocusManager.setCurrentKeyboardFocusManager(defKFM); + } + }); + + Runnable showAction = new Runnable() { + public void run() { + frame.setVisible(true); + } + }; + if (!Util.trackFocusGained(frameButton, showAction, 2000, false)) { + System.out.println("Test error: wrong initial focus!"); + return; + } + + robot.keyPress(KeyEvent.VK_SPACE); + robot.delay(50); + robot.keyRelease(KeyEvent.VK_SPACE); + + Util.waitForCondition(lock, 2000); + Util.waitForIdle(robot); + } +} + +class TestKFM extends DefaultKeyboardFocusManager { + Robot robot; + public TestKFM(Robot robot) { + this.robot = robot; + } + protected synchronized void enqueueKeyEvents(long after, Component untilFocused) { + super.enqueueKeyEvents(after, untilFocused); + robot.keyPress(KeyEvent.VK_SPACE); + robot.delay(50); + robot.keyRelease(KeyEvent.VK_SPACE); } } diff --git a/jdk/test/java/awt/Focus/WrongKeyTypedConsumedTest/WrongKeyTypedConsumedTest.java b/jdk/test/java/awt/Focus/WrongKeyTypedConsumedTest/WrongKeyTypedConsumedTest.java index fd6b56d8609..14fd0807b82 100644 --- a/jdk/test/java/awt/Focus/WrongKeyTypedConsumedTest/WrongKeyTypedConsumedTest.java +++ b/jdk/test/java/awt/Focus/WrongKeyTypedConsumedTest/WrongKeyTypedConsumedTest.java @@ -22,21 +22,16 @@ */ /* - test - @bug 4782886 - @summary FocusManager consumes wrong KEYTYPED-Events - @author son: area=awt.focus - @run applet WrongKeyTypedConsumedTest.html + @test + @bug 4782886 + @summary FocusManager consumes wrong KEY_TYPED events + @author Oleg.Sukhodolsky: area=awt.focus + @library ../../regtesthelpers + @build Util + @run main WrongKeyTypedConsumedTest */ -/** - * WrongKeyTypedConsumedTest.java - * - * summary: FocusManager consumes wrong KEYTYPED-Events - */ - import java.applet.Applet; - import java.awt.AWTException; import java.awt.AWTKeyStroke; import java.awt.BorderLayout; @@ -58,29 +53,19 @@ import javax.swing.JCheckBox; import javax.swing.JFrame; import javax.swing.JTextArea; +import test.java.awt.regtesthelpers.Util; + public class WrongKeyTypedConsumedTest extends Applet { - //Declare things used in the test, like buttons and labels here + Robot robot = Util.createRobot(); - public void init() - { - //Create instructions for the user here, as well as set up - // the environment -- set the layout manager, add buttons, - // etc. - - String[] instructions = - { - "This is an AUTOMATIC test", - "simply wait until it is done" - }; - Sysout.createDialog( ); - Sysout.printInstructions( instructions ); - - }//End init() + public static void main(String[] args) { + WrongKeyTypedConsumedTest test = new WrongKeyTypedConsumedTest(); + test.start(); + } public void start () { - //Get things going. Request focus, set size, et cetera setSize (200,200); setVisible(true); validate(); @@ -100,194 +85,45 @@ public class WrongKeyTypedConsumedTest extends Applet frame.pack(); frame.setVisible(true); + Util.waitForIdle(robot); - try { - Robot robot = new Robot(); - - // wait for activation - robot.delay(2000); - if (!frame.isActive()) { - Point loc = frame.getLocationOnScreen(); - Dimension size = frame.getSize(); - robot.mouseMove(loc.x + size.width/2, - loc.y + size.height/2); - frame.toFront(); - robot.delay(1000); - if (!frame.isActive()) { - throw new RuntimeException("Test Fialed: frame isn't active"); - } - } - - // verify if checkbox has focus - if (!checkbox.isFocusOwner()) { - checkbox.requestFocusInWindow(); - robot.delay(1000); - if (!checkbox.isFocusOwner()) { - throw new RuntimeException("Test Failed: checkbox doesn't have focus"); - } - } - // press VK_DOWN - robot.keyPress(KeyEvent.VK_DOWN); - robot.delay(250); - robot.keyRelease(KeyEvent.VK_DOWN); - robot.delay(1000); - - // verify if text area has focus - if (!textarea.isFocusOwner()) { - throw new RuntimeException("Test Failed: focus wasn't transfered to text area"); - } - // press '1' - robot.keyPress(KeyEvent.VK_1); - robot.delay(250); - robot.keyRelease(KeyEvent.VK_1); - robot.delay(1000); - - // verify if KEY_TYPED arraived - if (!"1".equals(textarea.getText())) { - throw new RuntimeException("Test Failed: text area text is \"" + textarea.getText() + "\", not \"1\""); - } - } catch(AWTException e) { - e.printStackTrace(); - throw new RuntimeException("Test failed because of some internal exception"); + if (!frame.isActive()) { + throw new RuntimeException("Test Fialed: frame isn't active"); } - Sysout.println("Test Passed"); - }// start() -}// class WrongKeyTypedConsumedTest + // verify if checkbox has focus + if (!checkbox.isFocusOwner()) { + checkbox.requestFocusInWindow(); + Util.waitForIdle(robot); + if (!checkbox.isFocusOwner()) { + throw new RuntimeException("Test Failed: checkbox doesn't have focus"); + } + } -/**************************************************** - Standard Test Machinery - DO NOT modify anything below -- it's a standard - chunk of code whose purpose is to make user - interaction uniform, and thereby make it simpler - to read and understand someone else's test. - ****************************************************/ + // press VK_DOWN + robot.keyPress(KeyEvent.VK_DOWN); + robot.delay(50); + robot.keyRelease(KeyEvent.VK_DOWN); + robot.delay(50); -/** - This is part of the standard test machinery. - It creates a dialog (with the instructions), and is the interface - for sending text messages to the user. - To print the instructions, send an array of strings to Sysout.createDialog - WithInstructions method. Put one line of instructions per array entry. - To display a message for the tester to see, simply call Sysout.println - with the string to be displayed. - This mimics System.out.println but works within the test harness as well - as standalone. - */ + Util.waitForIdle(robot); -class Sysout -{ - private static TestDialog dialog; + // verify if text area has focus + if (!textarea.isFocusOwner()) { + throw new RuntimeException("Test Failed: focus wasn't transfered to text area"); + } + // press '1' + robot.keyPress(KeyEvent.VK_1); + robot.delay(50); + robot.keyRelease(KeyEvent.VK_1); + robot.delay(50); - public static void createDialogWithInstructions( String[] instructions ) - { - dialog = new TestDialog( new Frame(), "Instructions" ); - dialog.printInstructions( instructions ); - dialog.setVisible(true); - println( "Any messages for the tester will display here." ); + Util.waitForIdle(robot); + + // verify if KEY_TYPED arrived + if (!"1".equals(textarea.getText())) { + throw new RuntimeException("Test Failed: text area text is \"" + textarea.getText() + "\", not \"1\""); + } + System.out.println("Test Passed"); } - - public static void createDialog( ) - { - dialog = new TestDialog( new Frame(), "Instructions" ); - String[] defInstr = { "Instructions will appear here. ", "" } ; - dialog.printInstructions( defInstr ); - dialog.setVisible(true); - println( "Any messages for the tester will display here." ); - } - - - public static void printInstructions( String[] instructions ) - { - dialog.printInstructions( instructions ); - } - - - public static void println( String messageIn ) - { - dialog.displayMessage( messageIn ); - } - -}// Sysout class - -/** - This is part of the standard test machinery. It provides a place for the - test instructions to be displayed, and a place for interactive messages - to the user to be displayed. - To have the test instructions displayed, see Sysout. - To have a message to the user be displayed, see Sysout. - Do not call anything in this dialog directly. - */ -class TestDialog extends Dialog -{ - - TextArea instructionsText; - TextArea messageText; - int maxStringLength = 80; - - //DO NOT call this directly, go through Sysout - public TestDialog( Frame frame, String name ) - { - super( frame, name ); - int scrollBoth = TextArea.SCROLLBARS_BOTH; - instructionsText = new TextArea( "", 15, maxStringLength, scrollBoth ); - add( "North", instructionsText ); - - messageText = new TextArea( "", 5, maxStringLength, scrollBoth ); - add("Center", messageText); - - pack(); - - setVisible(true); - }// TestDialog() - - //DO NOT call this directly, go through Sysout - public void printInstructions( String[] instructions ) - { - //Clear out any current instructions - instructionsText.setText( "" ); - - //Go down array of instruction strings - - String printStr, remainingStr; - for( int i=0; i < instructions.length; i++ ) - { - //chop up each into pieces maxSringLength long - remainingStr = instructions[ i ]; - while( remainingStr.length() > 0 ) - { - //if longer than max then chop off first max chars to print - if( remainingStr.length() >= maxStringLength ) - { - //Try to chop on a word boundary - int posOfSpace = remainingStr. - lastIndexOf( ' ', maxStringLength - 1 ); - - if( posOfSpace <= 0 ) posOfSpace = maxStringLength - 1; - - printStr = remainingStr.substring( 0, posOfSpace + 1 ); - remainingStr = remainingStr.substring( posOfSpace + 1 ); - } - //else just print - else - { - printStr = remainingStr; - remainingStr = ""; - } - - instructionsText.append( printStr + "\n" ); - - }// while - - }// for - - }//printInstructions() - - //DO NOT call this directly, go through Sysout - public void displayMessage( String messageIn ) - { - messageText.append( messageIn + "\n" ); - System.out.println(messageIn); - } - -}// TestDialog class +} From 50bc5573a81a44b6f369dba9802abec292c0c27e Mon Sep 17 00:00:00 2001 From: Tom Rodriguez Date: Wed, 26 Mar 2008 12:25:06 -0700 Subject: [PATCH 101/258] 6679708: No_Safepoint_Verifier and BacktraceBuilder have uninitialized fields Fix or remove uninitialized fields Reviewed-by: kvn, rasbold --- hotspot/src/share/vm/classfile/javaClasses.cpp | 5 +---- hotspot/src/share/vm/memory/gcLocker.hpp | 4 +++- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/hotspot/src/share/vm/classfile/javaClasses.cpp b/hotspot/src/share/vm/classfile/javaClasses.cpp index f2f3cb5869d..19ed2e419c0 100644 --- a/hotspot/src/share/vm/classfile/javaClasses.cpp +++ b/hotspot/src/share/vm/classfile/javaClasses.cpp @@ -1015,7 +1015,6 @@ class BacktraceBuilder: public StackObj { typeArrayOop _bcis; int _index; bool _dirty; - bool _done; No_Safepoint_Verifier _nsv; public: @@ -1029,12 +1028,10 @@ class BacktraceBuilder: public StackObj { }; // constructor for new backtrace - BacktraceBuilder(TRAPS): _methods(NULL), _bcis(NULL), _head(NULL) { + BacktraceBuilder(TRAPS): _methods(NULL), _bcis(NULL), _head(NULL), _dirty(false) { expand(CHECK); _backtrace = _head; _index = 0; - _dirty = false; - _done = false; } void flush() { diff --git a/hotspot/src/share/vm/memory/gcLocker.hpp b/hotspot/src/share/vm/memory/gcLocker.hpp index 00ba7ad89fd..b14b75797f1 100644 --- a/hotspot/src/share/vm/memory/gcLocker.hpp +++ b/hotspot/src/share/vm/memory/gcLocker.hpp @@ -184,7 +184,9 @@ class No_Safepoint_Verifier : public No_GC_Verifier { Thread *_thread; public: #ifdef ASSERT - No_Safepoint_Verifier(bool activated = true, bool verifygc = true ) : No_GC_Verifier(verifygc) { + No_Safepoint_Verifier(bool activated = true, bool verifygc = true ) : + No_GC_Verifier(verifygc), + _activated(activated) { _thread = Thread::current(); if (_activated) { _thread->_allow_allocation_count++; From e1362bb54d6b3ba3237d66209190a9893462d7ca Mon Sep 17 00:00:00 2001 From: "Daniel D. Daugherty" Date: Wed, 26 Mar 2008 20:18:22 -0700 Subject: [PATCH 102/258] 6679866: 3/2 portability issues with JLI-batch-200803 on Win* Make minor tweaks to the fix for 6274276 to make the Win* compiler happy... Reviewed-by: sspitsyn, ohair --- jdk/src/share/instrument/JarFacade.c | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/jdk/src/share/instrument/JarFacade.c b/jdk/src/share/instrument/JarFacade.c index a60bdbee134..85c5bd30b20 100644 --- a/jdk/src/share/instrument/JarFacade.c +++ b/jdk/src/share/instrument/JarFacade.c @@ -23,6 +23,14 @@ * have any questions. */ +#ifdef _WIN32 +/* + * Win* needs this include. However, Linux and Solaris do not. + * Having this include on Solaris SPARC breaks having non US-ASCII + * characters in the value of the Premain-Class attribute. + */ +#include +#endif /* _WIN32 */ #include #include @@ -45,8 +53,9 @@ doAttribute(const char* name, const char* value, void* user_data) { if (attribute->name == NULL) { free(attribute); } else { - char *begin = value; + char *begin = (char *)value; char *end; + size_t value_len; /* skip any leading white space */ while (isspace(*begin)) { @@ -66,7 +75,7 @@ doAttribute(const char* name, const char* value, void* user_data) { return; } - size_t value_len = (size_t)(end - begin); + value_len = (size_t)(end - begin); attribute->value = malloc(value_len + 1); if (attribute->value == NULL) { free(attribute->name); @@ -74,7 +83,7 @@ doAttribute(const char* name, const char* value, void* user_data) { } else { /* save the value without leading or trailing whitespace */ strncpy(attribute->value, begin, value_len); - attribute->value[value_len] = NULL; + attribute->value[value_len] = '\0'; attribute->next = NULL; if (context->head == NULL) { context->head = attribute; From fa0a3d049573c2c93174bac0e56d302a5285e8a6 Mon Sep 17 00:00:00 2001 From: Anthony Petrov Date: Thu, 27 Mar 2008 11:08:37 +0300 Subject: [PATCH 103/258] 6603312: Segmentation fault running java -jar SwingSet2.jar in 256 color mode Force hiding the splashscreen if the code cannot allocate a reasonable number of color cells on PseudoColor displays Reviewed-by: son, art --- .../sun/awt/splashscreen/splashscreen_sys.c | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/jdk/src/solaris/native/sun/awt/splashscreen/splashscreen_sys.c b/jdk/src/solaris/native/sun/awt/splashscreen/splashscreen_sys.c index 859e3b4384d..bcbc98393af 100644 --- a/jdk/src/solaris/native/sun/awt/splashscreen/splashscreen_sys.c +++ b/jdk/src/solaris/native/sun/awt/splashscreen/splashscreen_sys.c @@ -436,6 +436,7 @@ SplashInitPlatform(Splash * splash) { break; } case PseudoColor: { + int availableColors; int numColors; int numComponents[3]; unsigned long colorIndex[SPLASH_COLOR_MAP_SIZE]; @@ -444,9 +445,20 @@ SplashInitPlatform(Splash * splash) { int depth = XDefaultDepthOfScreen(splash->screen); int scale = 65535 / MAX_COLOR_VALUE; - numColors = GetNumAvailableColors(splash->display, splash->screen, + availableColors = GetNumAvailableColors(splash->display, splash->screen, splash->visual->map_entries); - numColors = quantizeColors(numColors, numComponents); + numColors = quantizeColors(availableColors, numComponents); + if (numColors > availableColors) { + // Could not allocate the color cells. Most probably + // the pool got exhausted. Disable the splash screen. + XCloseDisplay(splash->display); + splash->isVisible = -1; + splash->display = NULL; + splash->screen = NULL; + splash->visual = NULL; + fprintf(stderr, "Warning: unable to initialize the splashscreen. Not enough available color cells.\n"); + return; + } splash->cmap = AllocColors(splash->display, splash->screen, numColors, colorIndex); for (i = 0; i < numColors; i++) { From fb63e2974353b41068277eaafa28a00e10862cf6 Mon Sep 17 00:00:00 2001 From: Vladimir Kozlov Date: Thu, 27 Mar 2008 09:12:54 -0700 Subject: [PATCH 104/258] 6679854: assert in escape.cpp:397 The assert misses the case CastX2P 'base' for an unsafe field reference Reviewed-by: never, jrose --- hotspot/src/share/vm/opto/escape.cpp | 21 ++++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/hotspot/src/share/vm/opto/escape.cpp b/hotspot/src/share/vm/opto/escape.cpp index e587cee177f..0ea97731bb2 100644 --- a/hotspot/src/share/vm/opto/escape.cpp +++ b/hotspot/src/share/vm/opto/escape.cpp @@ -51,21 +51,21 @@ void PointsToNode::remove_edge(uint targIdx, PointsToNode::EdgeType et) { } #ifndef PRODUCT -static char *node_type_names[] = { +static const char *node_type_names[] = { "UnknownType", "JavaObject", "LocalVar", "Field" }; -static char *esc_names[] = { +static const char *esc_names[] = { "UnknownEscape", "NoEscape", "ArgEscape", "GlobalEscape" }; -static char *edge_type_suffix[] = { +static const char *edge_type_suffix[] = { "?", // UnknownEdge "P", // PointsToEdge "D", // DeferredEdge @@ -383,18 +383,25 @@ static Node* get_addp_base(Node *addp) { // | | // AddP ( base == address ) // - // case #6. Constant Pool or ThreadLocal or Raw object's field reference: - // ConP # Object from Constant Pool. + // case #6. Constant Pool, ThreadLocal, CastX2P or + // Raw object's field reference: + // {ConP, ThreadLocal, CastX2P, raw Load} // top | // \ | // AddP ( base == top ) // + // case #7. Klass's field reference. + // LoadKlass + // | | + // AddP ( base == address ) + // Node *base = addp->in(AddPNode::Base)->uncast(); if (base->is_top()) { // The AddP case #3 and #6. base = addp->in(AddPNode::Address)->uncast(); assert(base->Opcode() == Op_ConP || base->Opcode() == Op_ThreadLocal || - base->is_Mem() && base->bottom_type() == TypeRawPtr::NOTNULL || - base->is_Proj() && base->in(0)->is_Allocate(), "sanity"); + base->Opcode() == Op_CastX2P || + (base->is_Mem() && base->bottom_type() == TypeRawPtr::NOTNULL) || + (base->is_Proj() && base->in(0)->is_Allocate()), "sanity"); } return base; } From 0530e0d85426166c7a491530b15a5cd6a46f65cf Mon Sep 17 00:00:00 2001 From: Tom Rodriguez Date: Fri, 28 Mar 2008 09:00:39 -0700 Subject: [PATCH 105/258] 6680594: Load + Load isn't canonicalized leading to missed GVN opportunities Reviewed-by: kvn, jrose --- hotspot/src/share/vm/opto/addnode.cpp | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/hotspot/src/share/vm/opto/addnode.cpp b/hotspot/src/share/vm/opto/addnode.cpp index 2369792a1bf..35e3846ce16 100644 --- a/hotspot/src/share/vm/opto/addnode.cpp +++ b/hotspot/src/share/vm/opto/addnode.cpp @@ -70,9 +70,14 @@ static bool commute( Node *add, int con_left, int con_right ) { // Convert "Load+x" into "x+Load". // Now check for loads - if( in2->is_Load() ) return false; - // Left is a Load and Right is not; move it right. - if( in1->is_Load() ) { + if (in2->is_Load()) { + if (!in1->is_Load()) { + // already x+Load to return + return false; + } + // both are loads, so fall through to sort inputs by idx + } else if( in1->is_Load() ) { + // Left is a Load and Right is not; move it right. add->swap_edges(1, 2); return true; } From 2ea233816f40aced7c954571aed19396919a748e Mon Sep 17 00:00:00 2001 From: Vladimir Kozlov Date: Fri, 28 Mar 2008 11:52:29 -0700 Subject: [PATCH 106/258] 6680665: bytecode Escape Analyzer produces incorrect escape information for methods without oop arguments BcEscapeAnalyzer does not analyze methods with no oop arguments. Reviewed-by: rasbold --- hotspot/src/share/vm/ci/bcEscapeAnalyzer.cpp | 128 +++++++++---------- hotspot/src/share/vm/ci/bcEscapeAnalyzer.hpp | 7 +- hotspot/src/share/vm/oops/methodDataOop.hpp | 5 +- 3 files changed, 73 insertions(+), 67 deletions(-) diff --git a/hotspot/src/share/vm/ci/bcEscapeAnalyzer.cpp b/hotspot/src/share/vm/ci/bcEscapeAnalyzer.cpp index 8b9d0d7f31e..fc875ca552d 100644 --- a/hotspot/src/share/vm/ci/bcEscapeAnalyzer.cpp +++ b/hotspot/src/share/vm/ci/bcEscapeAnalyzer.cpp @@ -1247,8 +1247,14 @@ void BCEscapeAnalyzer::compute_escape_info() { initialize(); - // do not scan method if it has no object parameters - if (_arg_local.is_empty()) { + // Do not scan method if it has no object parameters and + // does not returns an object (_return_allocated is set in initialize()). + if (_arg_local.is_empty() && !_return_allocated) { + // Clear all info since method's bytecode was not analysed and + // set pessimistic escape information. + clear_escape_info(); + methodData()->set_eflag(methodDataOopDesc::allocated_escapes); + methodData()->set_eflag(methodDataOopDesc::unknown_modified); methodData()->set_eflag(methodDataOopDesc::estimated); return; } @@ -1259,45 +1265,8 @@ void BCEscapeAnalyzer::compute_escape_info() { success = do_analysis(); } - // dump result of bytecode analysis -#ifndef PRODUCT - if (BCEATraceLevel >= 3) { - tty->print("[EA] estimated escape information for"); - if (iid != vmIntrinsics::_none) - tty->print(" intrinsic"); - method()->print_short_name(); - tty->print_cr(has_dependencies() ? " (not stored)" : ""); - tty->print(" non-escaping args: "); - _arg_local.print_on(tty); - tty->print(" stack-allocatable args: "); - _arg_stack.print_on(tty); - if (_return_local) { - tty->print(" returned args: "); - _arg_returned.print_on(tty); - } else if (is_return_allocated()) { - tty->print_cr(" allocated return values"); - } else { - tty->print_cr(" non-local return values"); - } - tty->print(" modified args: "); - for (int i = 0; i < _arg_size; i++) { - if (_arg_modified[i] == 0) - tty->print(" 0"); - else - tty->print(" 0x%x", _arg_modified[i]); - } - tty->cr(); - tty->print(" flags: "); - if (_unknown_modified) - tty->print(" unknown_modified"); - if (_return_allocated) - tty->print(" return_allocated"); - tty->cr(); - } - -#endif - // don't store interprocedural escape information if it introduces dependencies - // or if method data is empty + // don't store interprocedural escape information if it introduces + // dependencies or if method data is empty // if (!has_dependencies() && !methodData()->is_empty()) { for (i = 0; i < _arg_size; i++) { @@ -1316,6 +1285,15 @@ void BCEscapeAnalyzer::compute_escape_info() { if (_return_local) { methodData()->set_eflag(methodDataOopDesc::return_local); } + if (_return_allocated) { + methodData()->set_eflag(methodDataOopDesc::return_allocated); + } + if (_allocated_escapes) { + methodData()->set_eflag(methodDataOopDesc::allocated_escapes); + } + if (_unknown_modified) { + methodData()->set_eflag(methodDataOopDesc::unknown_modified); + } methodData()->set_eflag(methodDataOopDesc::estimated); } } @@ -1331,33 +1309,47 @@ void BCEscapeAnalyzer::read_escape_info() { _arg_modified[i] = methodData()->arg_modified(i); } _return_local = methodData()->eflag_set(methodDataOopDesc::return_local); - - // dump result of loaded escape information -#ifndef PRODUCT - if (BCEATraceLevel >= 4) { - tty->print(" non-escaping args: "); - _arg_local.print_on(tty); - tty->print(" stack-allocatable args: "); - _arg_stack.print_on(tty); - if (_return_local) { - tty->print(" returned args: "); - _arg_returned.print_on(tty); - } else { - tty->print_cr(" non-local return values"); - } - tty->print(" modified args: "); - for (int i = 0; i < _arg_size; i++) { - if (_arg_modified[i] == 0) - tty->print(" 0"); - else - tty->print(" 0x%x", _arg_modified[i]); - } - tty->cr(); - } -#endif + _return_allocated = methodData()->eflag_set(methodDataOopDesc::return_allocated); + _allocated_escapes = methodData()->eflag_set(methodDataOopDesc::allocated_escapes); + _unknown_modified = methodData()->eflag_set(methodDataOopDesc::unknown_modified); } +#ifndef PRODUCT +void BCEscapeAnalyzer::dump() { + tty->print("[EA] estimated escape information for"); + method()->print_short_name(); + tty->print_cr(has_dependencies() ? " (not stored)" : ""); + tty->print(" non-escaping args: "); + _arg_local.print_on(tty); + tty->print(" stack-allocatable args: "); + _arg_stack.print_on(tty); + if (_return_local) { + tty->print(" returned args: "); + _arg_returned.print_on(tty); + } else if (is_return_allocated()) { + tty->print_cr(" return allocated value"); + } else { + tty->print_cr(" return non-local value"); + } + tty->print(" modified args: "); + for (int i = 0; i < _arg_size; i++) { + if (_arg_modified[i] == 0) + tty->print(" 0"); + else + tty->print(" 0x%x", _arg_modified[i]); + } + tty->cr(); + tty->print(" flags: "); + if (_return_allocated) + tty->print(" return_allocated"); + if (_allocated_escapes) + tty->print(" allocated_escapes"); + if (_unknown_modified) + tty->print(" unknown_modified"); + tty->cr(); +} +#endif BCEscapeAnalyzer::BCEscapeAnalyzer(ciMethod* method, BCEscapeAnalyzer* parent) : _conservative(method == NULL || !EstimateArgEscape) @@ -1401,6 +1393,12 @@ BCEscapeAnalyzer::BCEscapeAnalyzer(ciMethod* method, BCEscapeAnalyzer* parent) compute_escape_info(); methodData()->update_escape_info(); } +#ifndef PRODUCT + if (BCEATraceLevel >= 3) { + // dump escape information + dump(); + } +#endif } } diff --git a/hotspot/src/share/vm/ci/bcEscapeAnalyzer.hpp b/hotspot/src/share/vm/ci/bcEscapeAnalyzer.hpp index 53fe46ad88a..3af67e1fd59 100644 --- a/hotspot/src/share/vm/ci/bcEscapeAnalyzer.hpp +++ b/hotspot/src/share/vm/ci/bcEscapeAnalyzer.hpp @@ -50,9 +50,9 @@ class BCEscapeAnalyzer : public ResourceObj { uint *_arg_modified; bool _return_local; + bool _return_allocated; bool _allocated_escapes; bool _unknown_modified; - bool _return_allocated; ciObjectList _dependencies; @@ -153,4 +153,9 @@ class BCEscapeAnalyzer : public ResourceObj { // Copy dependencies from this analysis into "deps" void copy_dependencies(Dependencies *deps); + +#ifndef PRODUCT + // dump escape information + void dump(); +#endif }; diff --git a/hotspot/src/share/vm/oops/methodDataOop.hpp b/hotspot/src/share/vm/oops/methodDataOop.hpp index bcc1ac27eca..9c19f9b3a70 100644 --- a/hotspot/src/share/vm/oops/methodDataOop.hpp +++ b/hotspot/src/share/vm/oops/methodDataOop.hpp @@ -1253,7 +1253,10 @@ public: // Support for interprocedural escape analysis, from Thomas Kotzmann. enum EscapeFlag { estimated = 1 << 0, - return_local = 1 << 1 + return_local = 1 << 1, + return_allocated = 1 << 2, + allocated_escapes = 1 << 3, + unknown_modified = 1 << 4 }; intx eflags() { return _eflags; } From 5ac01e984f5f1d9f5be34bb1262d68f4f4ea2d5b Mon Sep 17 00:00:00 2001 From: John Coomes Date: Fri, 28 Mar 2008 23:35:42 -0700 Subject: [PATCH 107/258] 6642862: Code cache allocation fails with large pages after 6588638 Reviewed-by: apetrusenko --- hotspot/src/os/linux/vm/os_linux.cpp | 4 ++++ hotspot/src/os/solaris/vm/os_solaris.cpp | 6 ++++++ hotspot/src/os/windows/vm/os_windows.cpp | 6 +++++- .../gc_implementation/parallelScavenge/parMarkBitMap.cpp | 2 +- .../parallelScavenge/psParallelCompact.cpp | 2 +- hotspot/src/share/vm/memory/heap.cpp | 7 ++++--- hotspot/src/share/vm/runtime/os.hpp | 1 + 7 files changed, 22 insertions(+), 6 deletions(-) diff --git a/hotspot/src/os/linux/vm/os_linux.cpp b/hotspot/src/os/linux/vm/os_linux.cpp index 2a18b3423d1..28289bce61c 100644 --- a/hotspot/src/os/linux/vm/os_linux.cpp +++ b/hotspot/src/os/linux/vm/os_linux.cpp @@ -2480,6 +2480,10 @@ bool os::can_commit_large_page_memory() { return false; } +bool os::can_execute_large_page_memory() { + return false; +} + // Reserve memory at an arbitrary address, only if that area is // available (and not reserved for something else). diff --git a/hotspot/src/os/solaris/vm/os_solaris.cpp b/hotspot/src/os/solaris/vm/os_solaris.cpp index f4462669218..75ad158a9cd 100644 --- a/hotspot/src/os/solaris/vm/os_solaris.cpp +++ b/hotspot/src/os/solaris/vm/os_solaris.cpp @@ -3089,6 +3089,8 @@ bool os::large_page_init() { if (UseISM) { // ISM disables MPSS to be compatible with old JDK behavior UseMPSS = false; + _page_sizes[0] = _large_page_size; + _page_sizes[1] = vm_page_size(); } UseMPSS = UseMPSS && @@ -3178,6 +3180,10 @@ bool os::can_commit_large_page_memory() { return UseISM ? false : true; } +bool os::can_execute_large_page_memory() { + return UseISM ? false : true; +} + static int os_sleep(jlong millis, bool interruptible) { const jlong limit = INT_MAX; jlong prevtime; diff --git a/hotspot/src/os/windows/vm/os_windows.cpp b/hotspot/src/os/windows/vm/os_windows.cpp index 62e1f7a85c4..8794b3f2d4d 100644 --- a/hotspot/src/os/windows/vm/os_windows.cpp +++ b/hotspot/src/os/windows/vm/os_windows.cpp @@ -2516,9 +2516,13 @@ bool os::can_commit_large_page_memory() { return false; } +bool os::can_execute_large_page_memory() { + return true; +} + char* os::reserve_memory_special(size_t bytes) { DWORD flag = MEM_RESERVE | MEM_COMMIT | MEM_LARGE_PAGES; - char * res = (char *)VirtualAlloc(NULL, bytes, flag, PAGE_READWRITE); + char * res = (char *)VirtualAlloc(NULL, bytes, flag, PAGE_EXECUTE_READWRITE); return res; } diff --git a/hotspot/src/share/vm/gc_implementation/parallelScavenge/parMarkBitMap.cpp b/hotspot/src/share/vm/gc_implementation/parallelScavenge/parMarkBitMap.cpp index 614a16c4aed..7281b10f7db 100644 --- a/hotspot/src/share/vm/gc_implementation/parallelScavenge/parMarkBitMap.cpp +++ b/hotspot/src/share/vm/gc_implementation/parallelScavenge/parMarkBitMap.cpp @@ -41,7 +41,7 @@ ParMarkBitMap::initialize(MemRegion covered_region) const size_t rs_align = page_sz == (size_t) os::vm_page_size() ? 0 : MAX2(page_sz, granularity); - ReservedSpace rs(bytes, rs_align, false); + ReservedSpace rs(bytes, rs_align, rs_align > 0); os::trace_page_sizes("par bitmap", raw_bytes, raw_bytes, page_sz, rs.base(), rs.size()); _virtual_space = new PSVirtualSpace(rs, page_sz); diff --git a/hotspot/src/share/vm/gc_implementation/parallelScavenge/psParallelCompact.cpp b/hotspot/src/share/vm/gc_implementation/parallelScavenge/psParallelCompact.cpp index 81c2d47a647..d7277b14564 100644 --- a/hotspot/src/share/vm/gc_implementation/parallelScavenge/psParallelCompact.cpp +++ b/hotspot/src/share/vm/gc_implementation/parallelScavenge/psParallelCompact.cpp @@ -413,7 +413,7 @@ ParallelCompactData::create_vspace(size_t count, size_t element_size) const size_t rs_align = page_sz == (size_t) os::vm_page_size() ? 0 : MAX2(page_sz, granularity); - ReservedSpace rs(bytes, rs_align, false); + ReservedSpace rs(bytes, rs_align, rs_align > 0); os::trace_page_sizes("par compact", raw_bytes, raw_bytes, page_sz, rs.base(), rs.size()); PSVirtualSpace* vspace = new PSVirtualSpace(rs, page_sz); diff --git a/hotspot/src/share/vm/memory/heap.cpp b/hotspot/src/share/vm/memory/heap.cpp index c271efb0d3e..c1d43d7ea36 100644 --- a/hotspot/src/share/vm/memory/heap.cpp +++ b/hotspot/src/share/vm/memory/heap.cpp @@ -102,8 +102,9 @@ bool CodeHeap::reserve(size_t reserved_size, size_t committed_size, _log2_segment_size = exact_log2(segment_size); // Reserve and initialize space for _memory. - const size_t page_size = os::page_size_for_region(committed_size, - reserved_size, 8); + const size_t page_size = os::can_execute_large_page_memory() ? + os::page_size_for_region(committed_size, reserved_size, 8) : + os::vm_page_size(); const size_t granularity = os::vm_allocation_granularity(); const size_t r_align = MAX2(page_size, granularity); const size_t r_size = align_size_up(reserved_size, r_align); @@ -111,7 +112,7 @@ bool CodeHeap::reserve(size_t reserved_size, size_t committed_size, const size_t rs_align = page_size == (size_t) os::vm_page_size() ? 0 : MAX2(page_size, granularity); - ReservedSpace rs(r_size, rs_align, false); + ReservedSpace rs(r_size, rs_align, rs_align > 0); os::trace_page_sizes("code heap", committed_size, reserved_size, page_size, rs.base(), rs.size()); if (!_memory.initialize(rs, c_size)) { diff --git a/hotspot/src/share/vm/runtime/os.hpp b/hotspot/src/share/vm/runtime/os.hpp index 9cd4eb4763d..59a057193b0 100644 --- a/hotspot/src/share/vm/runtime/os.hpp +++ b/hotspot/src/share/vm/runtime/os.hpp @@ -228,6 +228,7 @@ class os: AllStatic { static bool large_page_init(); static size_t large_page_size(); static bool can_commit_large_page_memory(); + static bool can_execute_large_page_memory(); // OS interface to polling page static address get_polling_page() { return _polling_page; } From b63d2cdd275e8c485242bef125aae68fff24f41d Mon Sep 17 00:00:00 2001 From: John Coomes Date: Fri, 28 Mar 2008 23:35:42 -0700 Subject: [PATCH 108/258] 6679422: networkStream::connect() in ostream.cpp is not 64-bit clean Reviewed-by: jmasa, xlu --- hotspot/src/share/vm/utilities/ostream.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/hotspot/src/share/vm/utilities/ostream.cpp b/hotspot/src/share/vm/utilities/ostream.cpp index d5ad211fc01..1543ff7d715 100644 --- a/hotspot/src/share/vm/utilities/ostream.cpp +++ b/hotspot/src/share/vm/utilities/ostream.cpp @@ -829,7 +829,7 @@ bool networkStream::connect(const char *ip, short port) { server.sin_port = htons(port); server.sin_addr.s_addr = inet_addr(ip); - if (server.sin_addr.s_addr == (unsigned long)-1) { + if (server.sin_addr.s_addr == (uint32_t)-1) { #ifdef _WINDOWS struct hostent* host = hpi::get_host_by_name((char*)ip); #else From b2b125f8a93bd33671928018eea4b8d3d2bbd147 Mon Sep 17 00:00:00 2001 From: Dmitry Cherepanov Date: Mon, 31 Mar 2008 15:41:56 +0400 Subject: [PATCH 109/258] 6508505: JComboBox collapses immediately if it is placed to embedded frame XWindowPeer should translate absolute coordinates to local Reviewed-by: son --- jdk/src/solaris/classes/sun/awt/X11/XWindowPeer.java | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/jdk/src/solaris/classes/sun/awt/X11/XWindowPeer.java b/jdk/src/solaris/classes/sun/awt/X11/XWindowPeer.java index be679208974..c5fc7e1a7d4 100644 --- a/jdk/src/solaris/classes/sun/awt/X11/XWindowPeer.java +++ b/jdk/src/solaris/classes/sun/awt/X11/XWindowPeer.java @@ -1974,8 +1974,9 @@ class XWindowPeer extends XPanelPeer implements WindowPeer, // So, I do not want to implement complicated logic for better retargeting. target = pressTarget.isVisible() ? pressTarget : this; xme.set_window(target.getWindow()); - xme.set_x(xme.get_x_root() - target.getX()); - xme.set_y(xme.get_y_root() - target.getY()); + Point localCoord = target.toLocal(xme.get_x_root(), xme.get_y_root()); + xme.set_x(localCoord.x); + xme.set_y(localCoord.y); } grabLog.log(Level.FINER, " - Grab event target {0}", new Object[] {target}); if (target != null) { @@ -2026,8 +2027,9 @@ class XWindowPeer extends XPanelPeer implements WindowPeer, // see 6390326 for more information. target = pressTarget.isVisible() ? pressTarget : this; xbe.set_window(target.getWindow()); - xbe.set_x(xbe.get_x_root() - target.getX()); - xbe.set_y(xbe.get_y_root() - target.getY()); + Point localCoord = target.toLocal(xbe.get_x_root(), xbe.get_y_root()); + xbe.set_x(localCoord.x); + xbe.set_y(localCoord.y); pressTarget = this; } if (target != null && target != getContentXWindow() && target != this) { From cfaf19f278767e57ea355daf9d04c9379f95f40f Mon Sep 17 00:00:00 2001 From: Dmitry Cherepanov Date: Mon, 31 Mar 2008 15:56:12 +0400 Subject: [PATCH 110/258] 6637204: TrayIcon.displayMessage fails to show icon twice The icon canvas should be validated to finalize its layout Reviewed-by: ant --- jdk/src/solaris/classes/sun/awt/X11/XTrayIconPeer.java | 1 + 1 file changed, 1 insertion(+) diff --git a/jdk/src/solaris/classes/sun/awt/X11/XTrayIconPeer.java b/jdk/src/solaris/classes/sun/awt/X11/XTrayIconPeer.java index 5c8ccd02913..e3bfacb4353 100644 --- a/jdk/src/solaris/classes/sun/awt/X11/XTrayIconPeer.java +++ b/jdk/src/solaris/classes/sun/awt/X11/XTrayIconPeer.java @@ -833,6 +833,7 @@ public class XTrayIconPeer implements TrayIconPeer { Dimension tpSize = textPanel.getSize(); iconCanvas.setSize(BALLOON_ICON_WIDTH, (BALLOON_ICON_HEIGHT > tpSize.height ? BALLOON_ICON_HEIGHT : tpSize.height)); + iconCanvas.validate(); } SunToolkit.executeOnEventHandlerThread(xtiPeer.target, new Runnable() { From 3470103a939d299425cf447679e48deb96815a2b Mon Sep 17 00:00:00 2001 From: Valerie Peng Date: Mon, 31 Mar 2008 11:09:57 -0700 Subject: [PATCH 111/258] 6681652: Two new regression test failures in pkcs11 code Fixed the test to not assume SunJCE provider being the provider for DES Reviewed-by: wetmore --- jdk/test/javax/crypto/Cipher/TestGetInstance.java | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/jdk/test/javax/crypto/Cipher/TestGetInstance.java b/jdk/test/javax/crypto/Cipher/TestGetInstance.java index 736bac9bb2f..125fd4fc255 100644 --- a/jdk/test/javax/crypto/Cipher/TestGetInstance.java +++ b/jdk/test/javax/crypto/Cipher/TestGetInstance.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2007 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2003-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -46,9 +46,7 @@ public class TestGetInstance { Cipher c; - c = Cipher.getInstance("des"); - same(p, c.getProvider()); - c = Cipher.getInstance("des/cbc/pkcs5padding"); + c = Cipher.getInstance("PBEWithMD5AndTripleDES"); same(p, c.getProvider()); c = Cipher.getInstance("des", "SunJCE"); From b9705263ec8ffdcc001ba2702b153cc9fa94e3e7 Mon Sep 17 00:00:00 2001 From: Chris Phillips Date: Mon, 31 Mar 2008 13:27:10 -0700 Subject: [PATCH 112/258] 6469580: 1.5.0_08 JVM crashes in SignatureHandlerLibrary::add on Fujitsu Primepower platform Reviewed-by: andreas, valeriep, wetmore --- jdk/src/solaris/native/sun/security/pkcs11/wrapper/p11_md.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/jdk/src/solaris/native/sun/security/pkcs11/wrapper/p11_md.c b/jdk/src/solaris/native/sun/security/pkcs11/wrapper/p11_md.c index 40c38e0640f..ea46ea59c9a 100644 --- a/jdk/src/solaris/native/sun/security/pkcs11/wrapper/p11_md.c +++ b/jdk/src/solaris/native/sun/security/pkcs11/wrapper/p11_md.c @@ -123,7 +123,10 @@ JNIEXPORT void JNICALL Java_sun_security_pkcs11_wrapper_PKCS11_connect C_GetFunctionList = (CK_C_GetFunctionList) dlsym(hModule, getFunctionListStr); (*env)->ReleaseStringUTFChars(env, jGetFunctionList, getFunctionListStr); } - if ((C_GetFunctionList == NULL) || ((systemErrorMessage = dlerror()) != NULL)){ + if (C_GetFunctionList == NULL) { + throwIOException(env, "ERROR: C_GetFunctionList == NULL"); + return; + } else if ( (systemErrorMessage = dlerror()) != NULL ){ throwIOException(env, systemErrorMessage); return; } From c10465ee58c938b6af0d3504d3d895e342a26da6 Mon Sep 17 00:00:00 2001 From: Valerie Peng Date: Mon, 31 Mar 2008 16:12:37 -0700 Subject: [PATCH 113/258] 6682411: JCK test failed w/ ArrayIndexOutOfBoundException (-1) when decrypting with no data Fixed PKCS5Padding class with additional check and throw BadPaddingException if the check failed Reviewed-by: wetmore --- .../classes/sun/security/pkcs11/P11Cipher.java | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/jdk/src/share/classes/sun/security/pkcs11/P11Cipher.java b/jdk/src/share/classes/sun/security/pkcs11/P11Cipher.java index 97e0bb5f64b..918c5ad262d 100644 --- a/jdk/src/share/classes/sun/security/pkcs11/P11Cipher.java +++ b/jdk/src/share/classes/sun/security/pkcs11/P11Cipher.java @@ -72,7 +72,7 @@ final class P11Cipher extends CipherSpi { // DEC: return the length of trailing padding bytes given the specified // padded data - int unpad(byte[] paddedData, int ofs, int len) + int unpad(byte[] paddedData, int len) throws BadPaddingException; } @@ -94,14 +94,17 @@ final class P11Cipher extends CipherSpi { return padLen; } - public int unpad(byte[] paddedData, int ofs, int len) + public int unpad(byte[] paddedData, int len) throws BadPaddingException { - byte padValue = paddedData[ofs + len - 1]; + if (len < 1 || len > paddedData.length) { + throw new BadPaddingException("Invalid pad array length!"); + } + byte padValue = paddedData[len - 1]; if (padValue < 1 || padValue > blockSize) { throw new BadPaddingException("Invalid pad value!"); } // sanity check padding bytes - int padStartIndex = ofs + len - padValue; + int padStartIndex = len - padValue; for (int i = padStartIndex; i < len; i++) { if (paddedData[i] != padValue) { throw new BadPaddingException("Invalid pad bytes!"); @@ -712,7 +715,7 @@ final class P11Cipher extends CipherSpi { } k += token.p11.C_DecryptFinal(session.id(), 0, padBuffer, k, padBuffer.length - k); - int actualPadLen = paddingObj.unpad(padBuffer, 0, k); + int actualPadLen = paddingObj.unpad(padBuffer, k); k -= actualPadLen; System.arraycopy(padBuffer, 0, out, outOfs, k); } else { @@ -781,7 +784,7 @@ final class P11Cipher extends CipherSpi { } k += token.p11.C_DecryptFinal(session.id(), 0, padBuffer, k, padBuffer.length - k); - int actualPadLen = paddingObj.unpad(padBuffer, 0, k); + int actualPadLen = paddingObj.unpad(padBuffer, k); k -= actualPadLen; outArray = padBuffer; outOfs = 0; From 0397417ad8461a77297771a9d8ec912b1aa84ba4 Mon Sep 17 00:00:00 2001 From: Valerie Peng Date: Mon, 31 Mar 2008 16:16:12 -0700 Subject: [PATCH 114/258] 6682417: JCK test failed w/ ProviderException when decrypted data is not multiple of blocks Check for CKR_ENCRYPTED_DATA_LEN_RANGE and throw IllegalBlockSizeException Reviewed-by: wetmore --- jdk/src/share/classes/sun/security/pkcs11/P11Cipher.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/jdk/src/share/classes/sun/security/pkcs11/P11Cipher.java b/jdk/src/share/classes/sun/security/pkcs11/P11Cipher.java index 918c5ad262d..f5da56bec64 100644 --- a/jdk/src/share/classes/sun/security/pkcs11/P11Cipher.java +++ b/jdk/src/share/classes/sun/security/pkcs11/P11Cipher.java @@ -817,7 +817,8 @@ final class P11Cipher extends CipherSpi { if (errorCode == CKR_BUFFER_TOO_SMALL) { throw (ShortBufferException) (new ShortBufferException().initCause(e)); - } else if (errorCode == CKR_DATA_LEN_RANGE) { + } else if (errorCode == CKR_DATA_LEN_RANGE || + errorCode == CKR_ENCRYPTED_DATA_LEN_RANGE) { throw (IllegalBlockSizeException) (new IllegalBlockSizeException(e.toString()).initCause(e)); } From 1a350ad182a4a21c624adda8e20cca988aaf9965 Mon Sep 17 00:00:00 2001 From: Tom Rodriguez Date: Mon, 31 Mar 2008 16:22:52 -0700 Subject: [PATCH 115/258] 6636352: Unit tests for supplementary character support fail with -XX:+AggressiveOpts Incorrect encoding Reviewed-by: kvn, rasbold, sgoldman, jrose --- hotspot/src/cpu/sparc/vm/sparc.ad | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/hotspot/src/cpu/sparc/vm/sparc.ad b/hotspot/src/cpu/sparc/vm/sparc.ad index d940498efa5..9360631b077 100644 --- a/hotspot/src/cpu/sparc/vm/sparc.ad +++ b/hotspot/src/cpu/sparc/vm/sparc.ad @@ -6023,7 +6023,7 @@ instruct cmovII_imm(cmpOp cmp, flagsReg icc, iRegI dst, immI11 src) %{ ins_pipe(ialu_imm); %} -instruct cmovII_U_reg(cmpOp cmp, flagsRegU icc, iRegI dst, iRegI src) %{ +instruct cmovII_U_reg(cmpOpU cmp, flagsRegU icc, iRegI dst, iRegI src) %{ match(Set dst (CMoveI (Binary cmp icc) (Binary dst src))); ins_cost(150); size(4); @@ -6032,7 +6032,7 @@ instruct cmovII_U_reg(cmpOp cmp, flagsRegU icc, iRegI dst, iRegI src) %{ ins_pipe(ialu_reg); %} -instruct cmovII_U_imm(cmpOp cmp, flagsRegU icc, iRegI dst, immI11 src) %{ +instruct cmovII_U_imm(cmpOpU cmp, flagsRegU icc, iRegI dst, immI11 src) %{ match(Set dst (CMoveI (Binary cmp icc) (Binary dst src))); ins_cost(140); size(4); From ea297b80d982963188f6dfe23597e626c9a85427 Mon Sep 17 00:00:00 2001 From: Kelly O'Hair Date: Mon, 31 Mar 2008 17:17:18 -0700 Subject: [PATCH 116/258] 6672405: OPENJDK build: jdk7/jdk/make/tools/freetypecheck leaves dirt behind OpenJDK freetype sanity check cleanup. Reviewed-by: tbell --- jdk/make/common/Defs.gmk | 2 + jdk/make/common/shared/Sanity.gmk | 22 ++++----- jdk/make/tools/Makefile | 2 + jdk/make/tools/freetypecheck/Makefile | 69 ++++++++++++++------------- 4 files changed, 49 insertions(+), 46 deletions(-) diff --git a/jdk/make/common/Defs.gmk b/jdk/make/common/Defs.gmk index 268533ba608..e83095ae917 100644 --- a/jdk/make/common/Defs.gmk +++ b/jdk/make/common/Defs.gmk @@ -303,6 +303,8 @@ BUILDTOOLCLASSDIR = $(OUTPUTDIR)/btclasses # for build tool jar files BUILDTOOLJARDIR = $(OUTPUTDIR)/btjars ABS_BUILDTOOLJARDIR = $(ABS_OUTPUTDIR)/btjars +# for generated tool class files +BUILDTOOLBINDIR = $(OUTPUTDIR)/btbins # for generated java source files GENSRCDIR = $(OUTPUTDIR)/gensrc # for generated C source files (not javah) diff --git a/jdk/make/common/shared/Sanity.gmk b/jdk/make/common/shared/Sanity.gmk index 9f6bd2a55ab..98bd5b4346c 100644 --- a/jdk/make/common/shared/Sanity.gmk +++ b/jdk/make/common/shared/Sanity.gmk @@ -788,21 +788,17 @@ sane-cacerts: ifdef OPENJDK -#name of test program that prints out "Failed" if freetype is not good enough -FREETYPE_VERSION_CHECK_NAME = freetype_versioncheck -FREETYPE_VERSION_CHECK = $(TEMPDIR)/$(FREETYPE_VERSION_CHECK_NAME)$(EXE_SUFFIX) +# The freetypecheck Makefile prints out "Failed" if not good enough +$(TEMPDIR)/freetypeinfo: FRC + @$(prep-target) + @(($(CD) $(BUILDDIR)/tools/freetypecheck && $(MAKE)) || \ + $(ECHO) "Failed to build freetypecheck." ) > $@ -sane-freetype: - @-($(CD) $(BUILDDIR)/tools/freetypecheck && \ - $(MAKE) REQUIRED_FREETYPE_VERSION=$(REQUIRED_FREETYPE_VERSION) \ - FT_TEST=$(FREETYPE_VERSION_CHECK_NAME) \ - FT_HEADERS=$(FREETYPE_HEADERS_PATH) \ - FT_LIB=$(FREETYPE_LIB_PATH) \ - XARCH=$(XARCH)) - @if [ ! -r $(FREETYPE_VERSION_CHECK) -o \ - "`$(FREETYPE_VERSION_CHECK) | $(GREP) Fail`" != "" ]; then \ +sane-freetype: $(TEMPDIR)/freetypeinfo + @if [ "`$(CAT) $< | $(GREP) Fail`" != "" ]; then \ $(ECHO) "ERROR: FreeType version " $(REQUIRED_FREETYPE_VERSION) \ - "or higher is required. \n" >> $(ERROR_FILE) ; \ + " or higher is required. \n" \ + "`$(CAT) $<` \n" >> $(ERROR_FILE) ; \ fi else diff --git a/jdk/make/tools/Makefile b/jdk/make/tools/Makefile index 0428e3c5585..3bc1cacd0ff 100644 --- a/jdk/make/tools/Makefile +++ b/jdk/make/tools/Makefile @@ -40,6 +40,7 @@ SUBDIRS = \ dir_diff \ dtdbuilder \ fontchecker \ + freetypecheck \ generate_break_iterator \ GenerateCharacter \ generatecurrencydata \ @@ -58,4 +59,5 @@ all build clean clobber:: clean clobber:: $(RM) -r $(BUILDTOOLCLASSDIR) $(RM) -r $(BUILDTOOLJARDIR) + $(RM) -r $(BUILDTOOLBINDIR) diff --git a/jdk/make/tools/freetypecheck/Makefile b/jdk/make/tools/freetypecheck/Makefile index 7bcfe6300c1..c96854309f2 100644 --- a/jdk/make/tools/freetypecheck/Makefile +++ b/jdk/make/tools/freetypecheck/Makefile @@ -22,55 +22,58 @@ # CA 95054 USA or visit www.sun.com if you need additional information or # have any questions. -# Builds test program for freetype sanity check. -# -# Makefile should be called with following input parameters -# FT_TEST - full name of test program -# FT_HEADERS - path to freetype headers -# FT_LIB - location of directory with library -# XARCH - xarch option if required +# Builds and runs test program for freetype sanity check. BUILDDIR = ../.. include $(BUILDDIR)/common/Defs.gmk -#test program is expected in the TEMPDIR -FT_TEST_PATH = $(TEMPDIR)/$(FT_TEST) +# Default name +FT_TEST = $(BUILDTOOLBINDIR)/freetype_versioncheck$(EXE_SUFFIX) -all: $(FT_TEST_PATH) +# Used on openjdk only +ifeq ($(OPENJDK),true) # Start with CFLAGS (which gets us the required -xarch setting on solaris) ifeq ($(PLATFORM), windows) - FT_OPTIONS = + FT_OPTIONS = /nologo $(CC_OBJECT_OUTPUT_FLAG)$(TEMPDIR) + FREETYPE_DLL = $(FREETYPE_LIB_PATH)/freetype.dll + FT_LD_OPTIONS = $(FREETYPE_LIB_PATH)/freetype.lib else FT_OPTIONS = $(CFLAGS) -endif - -FT_OPTIONS += -I$(FT_HEADERS) -I$(FT_HEADERS)/freetype2 -FT_OPTIONS += $(XARCH) - -#add runtime library search path -ifeq ($(PLATFORM), windows) - FREETYPE_LIB=$(FT_LIB)/freetype.lib - FREETYPE_DLL=$(FT_LIB)/freetype.dll - DFLAG=/D -else - FT_OPTIONS += -L$(FT_LIB) - DFLAG = -D - - #add runtime lib search path to ensure test will be runnable + FT_LD_OPTIONS = -L$(FREETYPE_LIB_PATH) + # Add runtime lib search path to ensure test will be runnable ifeq ($(PLATFORM), solaris) - FT_OPTIONS += -R $(FT_LIB) -lfreetype + FT_LD_OPTIONS += -R $(FREETYPE_LIB_PATH) -lfreetype else #linux - FT_OPTIONS += -Wl,-rpath -Wl,$(FT_LIB) -lfreetype + FT_LD_OPTIONS += -Wl,-rpath -Wl,$(FREETYPE_LIB_PATH) -lfreetype endif endif +FT_OPTIONS += -I$(FREETYPE_HEADERS_PATH) +FT_OPTIONS += -I$(FREETYPE_HEADERS_PATH)/freetype2 +FT_OPTIONS += -DREQUIRED_FREETYPE_VERSION=$(REQUIRED_FREETYPE_VERSION) +FT_LD_OPTIONS += $(LFLAGS_$(COMPILER_VERSION)) -FT_OPTIONS += $(DFLAG)REQUIRED_FREETYPE_VERSION=$(REQUIRED_FREETYPE_VERSION) +# Create test program +all: $(FT_TEST) + @$(FT_TEST) -# On windows we need to copy dll to test dir -# ti ensure it will be found in runtime -$(FT_TEST_PATH): freetypecheck.c - @$(CC) $(FT_OPTIONS) $(CC_PROGRAM_OUTPUT_FLAG)$@ $< $(FREETYPE_LIB) $(LFLAGS_$(COMPILER_VERSION)) +# On windows we need to copy dll to test dir to ensure it will be found +# at runtime +$(FT_TEST): freetypecheck.c + @$(prep-target) + @$(CC) $(FT_OPTIONS) $(CC_PROGRAM_OUTPUT_FLAG)$@ $< $(FT_LD_OPTIONS) ifeq ($(PLATFORM), windows) @$(CP) $(FREETYPE_DLL) `dirname $@` endif + +else + +# Inform user this is openjdk only +all: + @$(ECHO) "The freetype files are only used with OpenJDK" + +endif + +clean:: + $(RM) $(FT_TEST) + From 298642faa153738786cc08acfd0844111ae6749c Mon Sep 17 00:00:00 2001 From: Kelly O'Hair Date: Mon, 31 Mar 2008 17:19:06 -0700 Subject: [PATCH 117/258] 6482445: j2se/make/java/java/localegen.sh uses 'sort' from PATH, could get system32/sort Making sure the right 'sort' utility is found. Reviewed-by: tbell --- jdk/make/java/java/genlocales.gmk | 3 ++- jdk/make/java/java/localegen.sh | 4 ++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/jdk/make/java/java/genlocales.gmk b/jdk/make/java/java/genlocales.gmk index 05ad9f36dd5..8ea0a0f2559 100644 --- a/jdk/make/java/java/genlocales.gmk +++ b/jdk/make/java/java/genlocales.gmk @@ -80,7 +80,8 @@ $(LocaleDataMetaInfo_Dest):$(LocaleDataMetaInfo_Src) $(LOCALEGEN_SH) @$(ECHO) $(subst .java,'\n',$(Euro_Resources_java)) >> $@.tmp.euro; @$(ECHO) $(subst .properties,'\n',$(NonEuro_Resources_properties)) > $@.tmp.noneuro; @$(ECHO) $(subst .java,'\n',$(NonEuro_Resources_java)) >> $@.tmp.noneuro; - NAWK=$(NAWK) SED=$(SED) $(SH) $(LOCALEGEN_SH) $(RESOURCE_NAMES) $@.tmp.euro \ + NAWK="$(NAWK)" SED="$(SED)" SORT="$(SORT)" \ + $(SH) $(LOCALEGEN_SH) $(RESOURCE_NAMES) $@.tmp.euro \ $@.tmp.noneuro $< $@ @$(RM) $@.tmp.euro $@.tmp.noneuro; diff --git a/jdk/make/java/java/localegen.sh b/jdk/make/java/java/localegen.sh index 70e26838bc4..b4506b97854 100644 --- a/jdk/make/java/java/localegen.sh +++ b/jdk/make/java/java/localegen.sh @@ -29,7 +29,7 @@ # This script is to generate the supported locale list string and replace the # LocaleDataMetaInfo-XLocales.java in /src/share/classes/sun/util # -# NAWK & SED is passed in as environment variables. +# SORT, NAWK & SED is passed in as environment variables. # # A list of resource base name list; @@ -47,7 +47,7 @@ OUTPUT_FILE=$5 localelist= getlocalelist() { localelist="" - localelist=`$NAWK -F$1_ '{print $2}' $2 | sort` + localelist=`$NAWK -F$1_ '{print $2}' $2 | $SORT` } sed_script="$SED -e \"s@^#warn .*@// -- This file was mechanically generated: Do not edit! -- //@\" " From 4a807d5ed375231b1eb5f5ad686cf749e5b0f481 Mon Sep 17 00:00:00 2001 From: Kelly O'Hair Date: Mon, 31 Mar 2008 17:20:48 -0700 Subject: [PATCH 118/258] 6501543: Username can have non-alphanumeric characters User version string issues, including a L10n issue with month names. Reviewed-by: tbell --- jdk/make/common/shared/Defs.gmk | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/jdk/make/common/shared/Defs.gmk b/jdk/make/common/shared/Defs.gmk index 6b0adfcb533..811c87df1e8 100644 --- a/jdk/make/common/shared/Defs.gmk +++ b/jdk/make/common/shared/Defs.gmk @@ -265,7 +265,9 @@ ifdef BUILD_NUMBER FULL_VERSION = $(RELEASE)-$(BUILD_NUMBER) else BUILD_NUMBER = b00 - USER_RELEASE_SUFFIX := $(shell echo $(USER)_`date '+%d_%b_%Y_%H_%M' | tr "A-Z" "a-z"`) + BUILD_DATE := $(shell $(DATE) '+%Y_%m_%d_%H_%M') + CLEAN_USERNAME := $(shell $(ECHO) "$(USER)" | $(TR) -d -c '[:alnum:]') + USER_RELEASE_SUFFIX := $(shell $(ECHO) "$(CLEAN_USERNAME)_$(BUILD_DATE)" | $(TR) '[:upper:]' '[:lower:]' ) FULL_VERSION = $(RELEASE)-$(USER_RELEASE_SUFFIX)-$(BUILD_NUMBER) endif From 833746644c41b9ca60963c7a9d129571955b5de2 Mon Sep 17 00:00:00 2001 From: Vladimir Kozlov Date: Mon, 31 Mar 2008 18:37:36 -0700 Subject: [PATCH 119/258] 6682236: C2 hits ideal nodes limit during IGVN optimization with EA Missing check in LoadNode::Ideal() causes infinite generation of a value Phi. Reviewed-by: jrose, never --- hotspot/src/share/vm/opto/memnode.cpp | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/hotspot/src/share/vm/opto/memnode.cpp b/hotspot/src/share/vm/opto/memnode.cpp index d3027cec715..df47ccb0e96 100644 --- a/hotspot/src/share/vm/opto/memnode.cpp +++ b/hotspot/src/share/vm/opto/memnode.cpp @@ -1122,6 +1122,12 @@ Node *LoadNode::Ideal(PhaseGVN *phase, bool can_reshape) { } // Split through Phi (see original code in loopopts.cpp). assert(phase->C->have_alias_type(addr_t), "instance should have alias type"); + + // Do nothing here if Identity will find a value + // (to avoid infinite chain of value phis generation). + if ( !phase->eqv(this, this->Identity(phase)) ) + return NULL; + const Type* this_type = this->bottom_type(); int this_index = phase->C->get_alias_index(addr_t); int this_offset = addr_t->offset(); From 252a10cf1a84bb2710655b7d337ee27fdb3c4538 Mon Sep 17 00:00:00 2001 From: Andrey Petrusenko Date: Tue, 1 Apr 2008 15:13:47 +0400 Subject: [PATCH 120/258] 6539517: CR 6186200 should be extended to perm gen allocation to prevent spurious OOM's from perm gen Reviewed-by: ysr, jmasa --- .../concurrentMarkSweep/cmsPermGen.cpp | 44 +-------- .../concurrentMarkSweep/cmsPermGen.hpp | 1 - .../parallelScavenge/parallelScavengeHeap.cpp | 31 ++++++ .../parallelScavenge/psParallelCompact.cpp | 4 +- .../parallelScavenge/vmPSOperations.cpp | 3 + .../shared/vmGCOperations.cpp | 15 +++ .../shared/vmGCOperations.hpp | 21 ++++ hotspot/src/share/vm/includeDB_core | 13 ++- hotspot/src/share/vm/memory/gcLocker.cpp | 6 ++ .../src/share/vm/memory/genCollectedHeap.hpp | 1 + hotspot/src/share/vm/memory/permGen.cpp | 99 ++++++++++++------- hotspot/src/share/vm/memory/permGen.hpp | 2 + hotspot/src/share/vm/runtime/globals.hpp | 4 + .../src/share/vm/runtime/vm_operations.hpp | 1 + 14 files changed, 165 insertions(+), 80 deletions(-) diff --git a/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/cmsPermGen.cpp b/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/cmsPermGen.cpp index ead077be1e3..9fd85d6b4f1 100644 --- a/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/cmsPermGen.cpp +++ b/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/cmsPermGen.cpp @@ -44,52 +44,12 @@ HeapWord* CMSPermGen::mem_allocate(size_t size) { bool lock_owned = lock->owned_by_self(); if (lock_owned) { MutexUnlocker mul(lock); - return mem_allocate_work(size); + return mem_allocate_in_gen(size, _gen); } else { - return mem_allocate_work(size); + return mem_allocate_in_gen(size, _gen); } } -HeapWord* CMSPermGen::mem_allocate_work(size_t size) { - assert(!_gen->freelistLock()->owned_by_self(), "Potetntial deadlock"); - - MutexLocker ml(Heap_lock); - HeapWord* obj = NULL; - - obj = _gen->allocate(size, false); - // Since we want to minimize pause times, we will prefer - // expanding the perm gen rather than doing a stop-world - // collection to satisfy the allocation request. - if (obj == NULL) { - // Try to expand the perm gen and allocate space. - obj = _gen->expand_and_allocate(size, false, false); - if (obj == NULL) { - // Let's see if a normal stop-world full collection will - // free up enough space. - SharedHeap::heap()->collect_locked(GCCause::_permanent_generation_full); - obj = _gen->allocate(size, false); - if (obj == NULL) { - // The collection above may have shrunk the space, so try - // to expand again and allocate space. - obj = _gen->expand_and_allocate(size, false, false); - } - if (obj == NULL) { - // We have not been able to allocate space despite a - // full stop-world collection. We now make a last-ditch collection - // attempt (in which soft refs are all aggressively freed) - // that will try to reclaim as much space as possible. - SharedHeap::heap()->collect_locked(GCCause::_last_ditch_collection); - obj = _gen->allocate(size, false); - if (obj == NULL) { - // Expand generation in case it was shrunk following the collection. - obj = _gen->expand_and_allocate(size, false, false); - } - } - } - } - return obj; -} - void CMSPermGen::compute_new_size() { _gen->compute_new_size(); } diff --git a/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/cmsPermGen.hpp b/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/cmsPermGen.hpp index e7b7096f89c..8e1d07760ab 100644 --- a/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/cmsPermGen.hpp +++ b/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/cmsPermGen.hpp @@ -29,7 +29,6 @@ class ConcurrentMarkSweepGeneration; class CMSPermGen: public PermGen { friend class VMStructs; - HeapWord* mem_allocate_work(size_t size); protected: // The "generation" view. ConcurrentMarkSweepGeneration* _gen; diff --git a/hotspot/src/share/vm/gc_implementation/parallelScavenge/parallelScavengeHeap.cpp b/hotspot/src/share/vm/gc_implementation/parallelScavenge/parallelScavengeHeap.cpp index 8088f0c5d0d..6fd50b39fc5 100644 --- a/hotspot/src/share/vm/gc_implementation/parallelScavenge/parallelScavengeHeap.cpp +++ b/hotspot/src/share/vm/gc_implementation/parallelScavenge/parallelScavengeHeap.cpp @@ -590,6 +590,31 @@ HeapWord* ParallelScavengeHeap::permanent_mem_allocate(size_t size) { full_gc_count = Universe::heap()->total_full_collections(); result = perm_gen()->allocate_permanent(size); + + if (result != NULL) { + return result; + } + + if (GC_locker::is_active_and_needs_gc()) { + // If this thread is not in a jni critical section, we stall + // the requestor until the critical section has cleared and + // GC allowed. When the critical section clears, a GC is + // initiated by the last thread exiting the critical section; so + // we retry the allocation sequence from the beginning of the loop, + // rather than causing more, now probably unnecessary, GC attempts. + JavaThread* jthr = JavaThread::current(); + if (!jthr->in_critical()) { + MutexUnlocker mul(Heap_lock); + GC_locker::stall_until_clear(); + continue; + } else { + if (CheckJNICalls) { + fatal("Possible deadlock due to allocating while" + " in jni critical section"); + } + return NULL; + } + } } if (result == NULL) { @@ -622,6 +647,12 @@ HeapWord* ParallelScavengeHeap::permanent_mem_allocate(size_t size) { if (op.prologue_succeeded()) { assert(Universe::heap()->is_in_permanent_or_null(op.result()), "result not in heap"); + // If GC was locked out during VM operation then retry allocation + // and/or stall as necessary. + if (op.gc_locked()) { + assert(op.result() == NULL, "must be NULL if gc_locked() is true"); + continue; // retry and/or stall as necessary + } // If a NULL results is being returned, an out-of-memory // will be thrown now. Clear the gc_time_limit_exceeded // flag to avoid the following situation. diff --git a/hotspot/src/share/vm/gc_implementation/parallelScavenge/psParallelCompact.cpp b/hotspot/src/share/vm/gc_implementation/parallelScavenge/psParallelCompact.cpp index 81c2d47a647..b42b130894d 100644 --- a/hotspot/src/share/vm/gc_implementation/parallelScavenge/psParallelCompact.cpp +++ b/hotspot/src/share/vm/gc_implementation/parallelScavenge/psParallelCompact.cpp @@ -999,7 +999,7 @@ void PSParallelCompact::pre_compact(PreGCValues* pre_gc_values) DEBUG_ONLY(mark_bitmap_count = mark_bitmap_size = 0;) // Increment the invocation count - heap->increment_total_collections(); + heap->increment_total_collections(true); // We need to track unique mark sweep invocations as well. _total_invocations++; @@ -1964,7 +1964,7 @@ void PSParallelCompact::invoke_no_policy(bool maximum_heap_compaction) { assert(SafepointSynchronize::is_at_safepoint(), "must be at a safepoint"); assert(ref_processor() != NULL, "Sanity"); - if (GC_locker::is_active()) { + if (GC_locker::check_active_before_gc()) { return; } diff --git a/hotspot/src/share/vm/gc_implementation/parallelScavenge/vmPSOperations.cpp b/hotspot/src/share/vm/gc_implementation/parallelScavenge/vmPSOperations.cpp index 7f12cf55c55..0b21861397b 100644 --- a/hotspot/src/share/vm/gc_implementation/parallelScavenge/vmPSOperations.cpp +++ b/hotspot/src/share/vm/gc_implementation/parallelScavenge/vmPSOperations.cpp @@ -69,6 +69,9 @@ void VM_ParallelGCFailedPermanentAllocation::doit() { GCCauseSetter gccs(heap, _gc_cause); _result = heap->failed_permanent_mem_allocate(_size); + if (_result == NULL && GC_locker::is_active_and_needs_gc()) { + set_gc_locked(); + } notify_gc_end(); } diff --git a/hotspot/src/share/vm/gc_implementation/shared/vmGCOperations.cpp b/hotspot/src/share/vm/gc_implementation/shared/vmGCOperations.cpp index 7108f318ec0..7cab57dd727 100644 --- a/hotspot/src/share/vm/gc_implementation/shared/vmGCOperations.cpp +++ b/hotspot/src/share/vm/gc_implementation/shared/vmGCOperations.cpp @@ -144,3 +144,18 @@ void VM_GenCollectFull::doit() { gch->do_full_collection(gch->must_clear_all_soft_refs(), _max_level); notify_gc_end(); } + +void VM_GenCollectForPermanentAllocation::doit() { + JvmtiGCForAllocationMarker jgcm; + notify_gc_begin(true); + GenCollectedHeap* gch = GenCollectedHeap::heap(); + GCCauseSetter gccs(gch, _gc_cause); + gch->do_full_collection(gch->must_clear_all_soft_refs(), + gch->n_gens() - 1); + _res = gch->perm_gen()->allocate(_size, false); + assert(gch->is_in_reserved_or_null(_res), "result not in heap"); + if (_res == NULL && GC_locker::is_active_and_needs_gc()) { + set_gc_locked(); + } + notify_gc_end(); +} diff --git a/hotspot/src/share/vm/gc_implementation/shared/vmGCOperations.hpp b/hotspot/src/share/vm/gc_implementation/shared/vmGCOperations.hpp index ee850f70e8f..7777dc71c84 100644 --- a/hotspot/src/share/vm/gc_implementation/shared/vmGCOperations.hpp +++ b/hotspot/src/share/vm/gc_implementation/shared/vmGCOperations.hpp @@ -43,6 +43,7 @@ // is specified; and also the attach "inspectheap" operation // // VM_GenCollectForAllocation +// VM_GenCollectForPermanentAllocation // VM_ParallelGCFailedAllocation // VM_ParallelGCFailedPermanentAllocation // - this operation is invoked when allocation is failed; @@ -166,3 +167,23 @@ class VM_GenCollectFull: public VM_GC_Operation { virtual VMOp_Type type() const { return VMOp_GenCollectFull; } virtual void doit(); }; + +class VM_GenCollectForPermanentAllocation: public VM_GC_Operation { + private: + HeapWord* _res; + size_t _size; // size of object to be allocated + public: + VM_GenCollectForPermanentAllocation(size_t size, + unsigned int gc_count_before, + unsigned int full_gc_count_before, + GCCause::Cause gc_cause) + : VM_GC_Operation(gc_count_before, full_gc_count_before, true), + _size(size) { + _res = NULL; + _gc_cause = gc_cause; + } + ~VM_GenCollectForPermanentAllocation() {} + virtual VMOp_Type type() const { return VMOp_GenCollectForPermanentAllocation; } + virtual void doit(); + HeapWord* result() const { return _res; } +}; diff --git a/hotspot/src/share/vm/includeDB_core b/hotspot/src/share/vm/includeDB_core index 17404cec658..4893e97b2b7 100644 --- a/hotspot/src/share/vm/includeDB_core +++ b/hotspot/src/share/vm/includeDB_core @@ -719,6 +719,11 @@ ciObjArray.cpp ciNullObject.hpp ciObjArray.cpp ciUtilities.hpp ciObjArray.cpp objArrayOop.hpp +ciObjArray.cpp ciObjArray.hpp +ciObjArray.cpp ciNullObject.hpp +ciObjArray.cpp ciUtilities.hpp +ciObjArray.cpp objArrayOop.hpp + ciObjArrayKlass.cpp ciInstanceKlass.hpp ciObjArrayKlass.cpp ciObjArrayKlass.hpp ciObjArrayKlass.cpp ciObjArrayKlassKlass.hpp @@ -1636,6 +1641,7 @@ frame_.inline.hpp generate_platform_dependent_include gcLocker.cpp gcLocker.inline.hpp gcLocker.cpp sharedHeap.hpp +gcLocker.cpp resourceArea.hpp gcLocker.hpp collectedHeap.hpp gcLocker.hpp genCollectedHeap.hpp @@ -3061,13 +3067,14 @@ oopMap.cpp scopeDesc.hpp oopMap.cpp signature.hpp oopMap.hpp allocation.hpp +oopMapCache.cpp jvmtiRedefineClassesTrace.hpp oopMap.hpp compressedStream.hpp oopMap.hpp growableArray.hpp oopMap.hpp vmreg.hpp oopMapCache.cpp allocation.inline.hpp -oopMapCache.cpp handles.inline.hpp oopMapCache.cpp jvmtiRedefineClassesTrace.hpp +oopMapCache.cpp handles.inline.hpp oopMapCache.cpp oop.inline.hpp oopMapCache.cpp oopMapCache.hpp oopMapCache.cpp resourceArea.hpp @@ -3315,6 +3322,10 @@ permGen.cpp java.hpp permGen.cpp oop.inline.hpp permGen.cpp permGen.hpp permGen.cpp universe.hpp +permGen.cpp gcLocker.hpp +permGen.cpp gcLocker.inline.hpp +permGen.cpp vmGCOperations.hpp +permGen.cpp vmThread.hpp permGen.hpp gcCause.hpp permGen.hpp generation.hpp diff --git a/hotspot/src/share/vm/memory/gcLocker.cpp b/hotspot/src/share/vm/memory/gcLocker.cpp index 428a5d27553..4e770e01b36 100644 --- a/hotspot/src/share/vm/memory/gcLocker.cpp +++ b/hotspot/src/share/vm/memory/gcLocker.cpp @@ -32,6 +32,12 @@ volatile bool GC_locker::_doing_gc = false; void GC_locker::stall_until_clear() { assert(!JavaThread::current()->in_critical(), "Would deadlock"); + if (PrintJNIGCStalls && PrintGCDetails) { + ResourceMark rm; // JavaThread::name() allocates to convert to UTF8 + gclog_or_tty->print_cr( + "Allocation failed. Thread \"%s\" is stalled by JNI critical section.", + JavaThread::current()->name()); + } MutexLocker ml(JNICritical_lock); // Wait for _needs_gc to be cleared while (GC_locker::needs_gc()) { diff --git a/hotspot/src/share/vm/memory/genCollectedHeap.hpp b/hotspot/src/share/vm/memory/genCollectedHeap.hpp index b3cf2de0f4b..36cf0a6959d 100644 --- a/hotspot/src/share/vm/memory/genCollectedHeap.hpp +++ b/hotspot/src/share/vm/memory/genCollectedHeap.hpp @@ -35,6 +35,7 @@ class GenCollectedHeap : public SharedHeap { friend class CMSCollector; friend class GenMarkSweep; friend class VM_GenCollectForAllocation; + friend class VM_GenCollectForPermanentAllocation; friend class VM_GenCollectFull; friend class VM_GenCollectFullConcurrent; friend class VM_GC_HeapInspection; diff --git a/hotspot/src/share/vm/memory/permGen.cpp b/hotspot/src/share/vm/memory/permGen.cpp index f611cc36e1a..1c8fa9681ec 100644 --- a/hotspot/src/share/vm/memory/permGen.cpp +++ b/hotspot/src/share/vm/memory/permGen.cpp @@ -25,6 +25,70 @@ #include "incls/_precompiled.incl" #include "incls/_permGen.cpp.incl" +HeapWord* PermGen::mem_allocate_in_gen(size_t size, Generation* gen) { + MutexLocker ml(Heap_lock); + GCCause::Cause next_cause = GCCause::_permanent_generation_full; + GCCause::Cause prev_cause = GCCause::_no_gc; + + for (;;) { + HeapWord* obj = gen->allocate(size, false); + if (obj != NULL) { + return obj; + } + if (gen->capacity() < _capacity_expansion_limit || + prev_cause != GCCause::_no_gc) { + obj = gen->expand_and_allocate(size, false); + } + if (obj == NULL && prev_cause != GCCause::_last_ditch_collection) { + if (GC_locker::is_active_and_needs_gc()) { + // If this thread is not in a jni critical section, we stall + // the requestor until the critical section has cleared and + // GC allowed. When the critical section clears, a GC is + // initiated by the last thread exiting the critical section; so + // we retry the allocation sequence from the beginning of the loop, + // rather than causing more, now probably unnecessary, GC attempts. + JavaThread* jthr = JavaThread::current(); + if (!jthr->in_critical()) { + MutexUnlocker mul(Heap_lock); + // Wait for JNI critical section to be exited + GC_locker::stall_until_clear(); + continue; + } else { + if (CheckJNICalls) { + fatal("Possible deadlock due to allocating while" + " in jni critical section"); + } + return NULL; + } + } + + // Read the GC count while holding the Heap_lock + unsigned int gc_count_before = SharedHeap::heap()->total_collections(); + unsigned int full_gc_count_before = SharedHeap::heap()->total_full_collections(); + { + MutexUnlocker mu(Heap_lock); // give up heap lock, execute gets it back + VM_GenCollectForPermanentAllocation op(size, gc_count_before, full_gc_count_before, + next_cause); + VMThread::execute(&op); + if (!op.prologue_succeeded() || op.gc_locked()) { + assert(op.result() == NULL, "must be NULL if gc_locked() is true"); + continue; // retry and/or stall as necessary + } + obj = op.result(); + assert(obj == NULL || SharedHeap::heap()->is_in_reserved(obj), + "result not in heap"); + if (obj != NULL) { + return obj; + } + } + prev_cause = next_cause; + next_cause = GCCause::_last_ditch_collection; + } else { + return obj; + } + } +} + CompactingPermGen::CompactingPermGen(ReservedSpace rs, ReservedSpace shared_rs, size_t initial_byte_size, @@ -44,40 +108,7 @@ CompactingPermGen::CompactingPermGen(ReservedSpace rs, } HeapWord* CompactingPermGen::mem_allocate(size_t size) { - MutexLocker ml(Heap_lock); - HeapWord* obj = _gen->allocate(size, false); - bool tried_collection = false; - bool tried_expansion = false; - while (obj == NULL) { - if (_gen->capacity() >= _capacity_expansion_limit || tried_expansion) { - // Expansion limit reached, try collection before expanding further - // For now we force a full collection, this could be changed - SharedHeap::heap()->collect_locked(GCCause::_permanent_generation_full); - obj = _gen->allocate(size, false); - tried_collection = true; - tried_expansion = false; // ... following the collection: - // the collection may have shrunk the space. - } - if (obj == NULL && !tried_expansion) { - obj = _gen->expand_and_allocate(size, false); - tried_expansion = true; - } - if (obj == NULL && tried_collection && tried_expansion) { - // We have not been able to allocate despite a collection and - // an attempted space expansion. We now make a last-ditch collection - // attempt that will try to reclaim as much space as possible (for - // example by aggressively clearing all soft refs). - SharedHeap::heap()->collect_locked(GCCause::_last_ditch_collection); - obj = _gen->allocate(size, false); - if (obj == NULL) { - // An expansion attempt is necessary since the previous - // collection may have shrunk the space. - obj = _gen->expand_and_allocate(size, false); - } - break; - } - } - return obj; + return mem_allocate_in_gen(size, _gen); } void CompactingPermGen::compute_new_size() { diff --git a/hotspot/src/share/vm/memory/permGen.hpp b/hotspot/src/share/vm/memory/permGen.hpp index 47f16b83b0f..263a589b272 100644 --- a/hotspot/src/share/vm/memory/permGen.hpp +++ b/hotspot/src/share/vm/memory/permGen.hpp @@ -38,6 +38,8 @@ class PermGen : public CHeapObj { size_t _capacity_expansion_limit; // maximum expansion allowed without a // full gc occuring + HeapWord* mem_allocate_in_gen(size_t size, Generation* gen); + public: enum Name { MarkSweepCompact, MarkSweep, ConcurrentMarkSweep diff --git a/hotspot/src/share/vm/runtime/globals.hpp b/hotspot/src/share/vm/runtime/globals.hpp index 19f005aa887..66ff00b31d7 100644 --- a/hotspot/src/share/vm/runtime/globals.hpp +++ b/hotspot/src/share/vm/runtime/globals.hpp @@ -1919,6 +1919,10 @@ class CommandLineFlags { develop(bool, IgnoreLibthreadGPFault, false, \ "Suppress workaround for libthread GP fault") \ \ + product(bool, PrintJNIGCStalls, false, \ + "Print diagnostic message when GC is stalled" \ + "by JNI critical section") \ + \ /* JVMTI heap profiling */ \ \ diagnostic(bool, TraceJVMTIObjectTagging, false, \ diff --git a/hotspot/src/share/vm/runtime/vm_operations.hpp b/hotspot/src/share/vm/runtime/vm_operations.hpp index 778a46dd718..54264ad0dde 100644 --- a/hotspot/src/share/vm/runtime/vm_operations.hpp +++ b/hotspot/src/share/vm/runtime/vm_operations.hpp @@ -49,6 +49,7 @@ template(GenCollectFull) \ template(GenCollectFullConcurrent) \ template(GenCollectForAllocation) \ + template(GenCollectForPermanentAllocation) \ template(ParallelGCFailedAllocation) \ template(ParallelGCFailedPermanentAllocation) \ template(ParallelGCSystemGC) \ From 332059a5554e9119861041a5e9efa66ec61a0aac Mon Sep 17 00:00:00 2001 From: Eamonn McManus Date: Tue, 1 Apr 2008 14:45:23 +0200 Subject: [PATCH 121/258] 6610917: Define a generic NotificationFilter Adds javax.management.QueryNotificationFilter Reviewed-by: dfuchs --- .../DefaultMBeanServerInterceptor.java | 17 +- .../sun/jmx/mbeanserver/MBeanAnalyzer.java | 20 +- .../jmx/mbeanserver/MBeanIntrospector.java | 14 + .../mbeanserver/NotificationMBeanSupport.java | 81 ++++ .../sun/jmx/mbeanserver/OpenConverter.java | 2 +- .../com/sun/jmx/mbeanserver/Repository.java | 13 +- .../classes/com/sun/jmx/mbeanserver/Util.java | 10 + .../classes/javax/management/ObjectName.java | 17 +- .../management/QueryNotificationFilter.java | 417 ++++++++++++++++++ .../query/QueryNotifFilterTest.java | 347 +++++++++++++++ 10 files changed, 885 insertions(+), 53 deletions(-) create mode 100644 jdk/src/share/classes/com/sun/jmx/mbeanserver/NotificationMBeanSupport.java create mode 100644 jdk/src/share/classes/javax/management/QueryNotificationFilter.java create mode 100644 jdk/test/javax/management/query/QueryNotifFilterTest.java diff --git a/jdk/src/share/classes/com/sun/jmx/interceptor/DefaultMBeanServerInterceptor.java b/jdk/src/share/classes/com/sun/jmx/interceptor/DefaultMBeanServerInterceptor.java index a637aa14745..eea8d4309eb 100644 --- a/jdk/src/share/classes/com/sun/jmx/interceptor/DefaultMBeanServerInterceptor.java +++ b/jdk/src/share/classes/com/sun/jmx/interceptor/DefaultMBeanServerInterceptor.java @@ -34,8 +34,6 @@ import java.util.Set; import java.util.HashSet; import java.util.WeakHashMap; import java.lang.ref.WeakReference; -import java.io.PrintWriter; -import java.io.StringWriter; import java.security.AccessControlContext; import java.security.Permission; import java.security.ProtectionDomain; @@ -51,7 +49,6 @@ import javax.management.InstanceAlreadyExistsException; import javax.management.InstanceNotFoundException; import javax.management.IntrospectionException; import javax.management.InvalidAttributeValueException; -import javax.management.JMException; import javax.management.JMRuntimeException; import javax.management.ListenerNotFoundException; import javax.management.MalformedObjectNameException; @@ -84,11 +81,10 @@ import static com.sun.jmx.defaults.JmxProperties.MBEANSERVER_LOGGER; import com.sun.jmx.mbeanserver.DynamicMBean2; import com.sun.jmx.mbeanserver.ModifiableClassLoaderRepository; import com.sun.jmx.mbeanserver.MBeanInstantiator; -import com.sun.jmx.mbeanserver.MXBeanSupport; import com.sun.jmx.mbeanserver.Repository; import com.sun.jmx.mbeanserver.NamedObject; -import com.sun.jmx.defaults.ServiceName; import com.sun.jmx.mbeanserver.Introspector; +import com.sun.jmx.mbeanserver.Util; import com.sun.jmx.remote.util.EnvHelp; /** @@ -623,18 +619,9 @@ public class DefaultMBeanServerInterceptor implements MBeanServerInterceptor { List result = new ArrayList(domains.length); for (int i = 0; i < domains.length; i++) { try { - ObjectName domain = new ObjectName(domains[i] + ":x=x"); + ObjectName domain = Util.newObjectName(domains[i] + ":x=x"); checkMBeanPermission((String) null, null, domain, "getDomains"); result.add(domains[i]); - } catch (MalformedObjectNameException e) { - // Should never occur... But let's log it just in case. - if (MBEANSERVER_LOGGER.isLoggable(Level.SEVERE)) { - MBEANSERVER_LOGGER.logp(Level.SEVERE, - DefaultMBeanServerInterceptor.class.getName(), - "getDomains", - "Failed to check permission for domain = " + - domains[i], e); - } } catch (SecurityException e) { // OK: Do not add this domain to the list } diff --git a/jdk/src/share/classes/com/sun/jmx/mbeanserver/MBeanAnalyzer.java b/jdk/src/share/classes/com/sun/jmx/mbeanserver/MBeanAnalyzer.java index f908a352a2b..5975f1a391b 100644 --- a/jdk/src/share/classes/com/sun/jmx/mbeanserver/MBeanAnalyzer.java +++ b/jdk/src/share/classes/com/sun/jmx/mbeanserver/MBeanAnalyzer.java @@ -107,10 +107,7 @@ class MBeanAnalyzer { private MBeanAnalyzer(Class mbeanInterface, MBeanIntrospector introspector) throws NotCompliantMBeanException { - if (!mbeanInterface.isInterface()) { - throw new NotCompliantMBeanException("Not an interface: " + - mbeanInterface.getName()); - } + introspector.checkCompliance(mbeanInterface); try { initMaps(mbeanInterface, introspector); @@ -121,11 +118,10 @@ class MBeanAnalyzer { // Introspect the mbeanInterface and initialize this object's maps. // - private void initMaps(Class mbeanInterface, + private void initMaps(Class mbeanType, MBeanIntrospector introspector) throws Exception { - final Method[] methodArray = mbeanInterface.getMethods(); - - final List methods = eliminateCovariantMethods(methodArray); + final List methods1 = introspector.getMethods(mbeanType); + final List methods = eliminateCovariantMethods(methods1); /* Run through the methods to detect inconsistencies and to enable us to give getter and setter together to visitAttribute. */ @@ -234,13 +230,13 @@ class MBeanAnalyzer { but existing code may depend on it and users may be used to seeing operations or attributes appear in a particular order. */ static List - eliminateCovariantMethods(Method[] methodArray) { + eliminateCovariantMethods(List startMethods) { // We are assuming that you never have very many methods with the // same name, so it is OK to use algorithms that are quadratic // in the number of methods with the same name. - final int len = methodArray.length; - final Method[] sorted = methodArray.clone(); + final int len = startMethods.size(); + final Method[] sorted = startMethods.toArray(new Method[len]); Arrays.sort(sorted,MethodOrder.instance); final Set overridden = newSet(); for (int i=1;i { } } - final List methods = newList(Arrays.asList(methodArray)); + final List methods = newList(startMethods); methods.removeAll(overridden); return methods; } diff --git a/jdk/src/share/classes/com/sun/jmx/mbeanserver/MBeanIntrospector.java b/jdk/src/share/classes/com/sun/jmx/mbeanserver/MBeanIntrospector.java index c191005d621..ea7dbdade33 100644 --- a/jdk/src/share/classes/com/sun/jmx/mbeanserver/MBeanIntrospector.java +++ b/jdk/src/share/classes/com/sun/jmx/mbeanserver/MBeanIntrospector.java @@ -34,6 +34,7 @@ import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Type; +import java.util.Arrays; import java.util.List; import java.util.WeakHashMap; @@ -169,6 +170,19 @@ abstract class MBeanIntrospector { */ abstract Descriptor getMBeanDescriptor(Class resourceClass); + void checkCompliance(Class mbeanType) throws NotCompliantMBeanException { + if (!mbeanType.isInterface()) { + throw new NotCompliantMBeanException("Not an interface: " + + mbeanType.getName()); + } + } + + /** + * Get the methods to be analyzed to build the MBean interface. + */ + List getMethods(final Class mbeanType) throws Exception { + return Arrays.asList(mbeanType.getMethods()); + } final PerInterface getPerInterface(Class mbeanInterface) throws NotCompliantMBeanException { diff --git a/jdk/src/share/classes/com/sun/jmx/mbeanserver/NotificationMBeanSupport.java b/jdk/src/share/classes/com/sun/jmx/mbeanserver/NotificationMBeanSupport.java new file mode 100644 index 00000000000..f1e3a13c891 --- /dev/null +++ b/jdk/src/share/classes/com/sun/jmx/mbeanserver/NotificationMBeanSupport.java @@ -0,0 +1,81 @@ +/* + * Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package com.sun.jmx.mbeanserver; + +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.List; +import javax.management.NotCompliantMBeanException; +import javax.management.Notification; + +/** + *

A variant of {@code StandardMBeanSupport} where the only + * methods included are public getters. This is used by + * {@code QueryNotificationFilter} to pretend that a Notification is + * an MBean so it can have a query evaluated on it. Standard queries + * never set attributes or invoke methods but custom queries could and + * we don't want to allow that. Also we don't want to fail if a + * Notification happens to have inconsistent types in a pair of getX and + * setX methods, and we want to include the Object.getClass() method. + */ +public class NotificationMBeanSupport extends StandardMBeanSupport { + public NotificationMBeanSupport(T n) + throws NotCompliantMBeanException { + super(n, Util.>cast(n.getClass())); + } + + @Override + MBeanIntrospector getMBeanIntrospector() { + return introspector; + } + + private static class Introspector extends StandardMBeanIntrospector { + @Override + void checkCompliance(Class mbeanType) {} + + @Override + List getMethods(final Class mbeanType) + throws Exception { + List methods = new ArrayList(); + for (Method m : mbeanType.getMethods()) { + String name = m.getName(); + Class ret = m.getReturnType(); + if (m.getParameterTypes().length == 0) { + if ((name.startsWith("is") && name.length() > 2 && + ret == boolean.class) || + (name.startsWith("get") && name.length() > 3 && + ret != void.class)) { + methods.add(m); + } + } + } + return methods; + } + + } + private static final MBeanIntrospector introspector = + new Introspector(); +} diff --git a/jdk/src/share/classes/com/sun/jmx/mbeanserver/OpenConverter.java b/jdk/src/share/classes/com/sun/jmx/mbeanserver/OpenConverter.java index ccd0ed57bf5..25ac0a28e10 100644 --- a/jdk/src/share/classes/com/sun/jmx/mbeanserver/OpenConverter.java +++ b/jdk/src/share/classes/com/sun/jmx/mbeanserver/OpenConverter.java @@ -438,7 +438,7 @@ public abstract class OpenConverter { c.getClassLoader() == null); final List methods = - MBeanAnalyzer.eliminateCovariantMethods(c.getMethods()); + MBeanAnalyzer.eliminateCovariantMethods(Arrays.asList(c.getMethods())); final SortedMap getterMap = newSortedMap(); /* Select public methods that look like "T getX()" or "boolean diff --git a/jdk/src/share/classes/com/sun/jmx/mbeanserver/Repository.java b/jdk/src/share/classes/com/sun/jmx/mbeanserver/Repository.java index e33492d945e..38a1fc6d4f4 100644 --- a/jdk/src/share/classes/com/sun/jmx/mbeanserver/Repository.java +++ b/jdk/src/share/classes/com/sun/jmx/mbeanserver/Repository.java @@ -415,17 +415,8 @@ public class Repository { boolean to_default_domain = false; // Set domain to default if domain is empty and not already set - if (dom.length() == 0) { - try { - name = new ObjectName(domain + name.toString()); - } catch (MalformedObjectNameException e) { - if (MBEANSERVER_LOGGER.isLoggable(Level.FINEST)) { - MBEANSERVER_LOGGER.logp(Level.FINEST, - Repository.class.getName(), "addMBean", - "Unexpected MalformedObjectNameException", e); - } - } - } + if (dom.length() == 0) + name = Util.newObjectName(domain + name.toString()); // Do we have default domain ? if (dom == domain) { diff --git a/jdk/src/share/classes/com/sun/jmx/mbeanserver/Util.java b/jdk/src/share/classes/com/sun/jmx/mbeanserver/Util.java index 712b4e378a8..f2dbe60bbdf 100644 --- a/jdk/src/share/classes/com/sun/jmx/mbeanserver/Util.java +++ b/jdk/src/share/classes/com/sun/jmx/mbeanserver/Util.java @@ -38,6 +38,8 @@ import java.util.Map; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; +import javax.management.MalformedObjectNameException; +import javax.management.ObjectName; public class Util { static Map newMap() { @@ -85,6 +87,14 @@ public class Util { return new ArrayList(c); } + public static ObjectName newObjectName(String s) { + try { + return new ObjectName(s); + } catch (MalformedObjectNameException e) { + throw new IllegalArgumentException(e); + } + } + /* This method can be used by code that is deliberately violating the * allowed checked casts. Rather than marking the whole method containing * the code with @SuppressWarnings, you can use a call to this method for diff --git a/jdk/src/share/classes/javax/management/ObjectName.java b/jdk/src/share/classes/javax/management/ObjectName.java index cef869510b1..ff11962b666 100644 --- a/jdk/src/share/classes/javax/management/ObjectName.java +++ b/jdk/src/share/classes/javax/management/ObjectName.java @@ -26,6 +26,7 @@ package javax.management; import com.sun.jmx.mbeanserver.GetPropertyAction; +import com.sun.jmx.mbeanserver.Util; import java.io.IOException; import java.io.InvalidObjectException; import java.io.ObjectInputStream; @@ -1386,12 +1387,7 @@ public class ObjectName extends ToQueryString throws NullPointerException { if (name.getClass().equals(ObjectName.class)) return name; - try { - return new ObjectName(name.getSerializedNameString()); - } catch (MalformedObjectNameException e) { - throw new IllegalArgumentException("Unexpected: " + e); - // can't happen - } + return Util.newObjectName(name.getSerializedNameString()); } /** @@ -1950,14 +1946,7 @@ public class ObjectName extends ToQueryString * * @since 1.6 */ - public static final ObjectName WILDCARD; - static { - try { - WILDCARD = new ObjectName("*:*"); - } catch (MalformedObjectNameException e) { - throw new Error("Can't initialize wildcard name", e); - } - } + public static final ObjectName WILDCARD = Util.newObjectName("*:*"); // Category : Utilities <=================================== diff --git a/jdk/src/share/classes/javax/management/QueryNotificationFilter.java b/jdk/src/share/classes/javax/management/QueryNotificationFilter.java new file mode 100644 index 00000000000..c6c10393902 --- /dev/null +++ b/jdk/src/share/classes/javax/management/QueryNotificationFilter.java @@ -0,0 +1,417 @@ +/* + * Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package javax.management; + +import com.sun.jmx.mbeanserver.NotificationMBeanSupport; +import com.sun.jmx.mbeanserver.Util; +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; +import java.util.Collections; +import java.util.Set; + +/** + *

General-purpose notification filter. This filter can be used to + * filter notifications from a possibly-remote MBean. Most filtering + * decisions can be coded using this filter, which avoids having to + * write a custom implementation of the {@link NotificationFilter} + * class. Writing a custom implementation requires you to deploy it + * on both the client and the server in the remote case, so using this class + * instead is recommended where possible.

+ * + * + * + *

This class uses the {@linkplain Query Query API} to specify the + * filtering logic. For example, to select only notifications where the + * {@linkplain Notification#getType() type} is {@code "com.example.mytype"}, + * you could use

+ * + *
+ * NotificationFilter filter =
+ *     new QueryNotificationFilter("Type = 'com.example.mytype'");
+ * 
+ * + *

or equivalently

+ * + *
+ * NotificationFilter filter =
+ *     new QueryNotificationFilter(
+ *             Query.eq(Query.attr("Type"), Query.value("com.example.mytype")));
+ * 
+ * + *

(This particular example could also use + * {@link NotificationFilterSupport}.)

+ * + *

Here are some other examples of filters you can specify with this class.

+ * + *
+ * + *
{@code QueryNotificationFilter("Type = 'com.example.type1' or + * Type = 'com.example.type2'")} + *
Notifications where the type is either of the given strings. + * + *
{@code QueryNotificationFilter("Type in ('com.example.type1', + * 'com.example.type2')")} + *
Another way to write the previous example. + * + *
{@code QueryNotificationFilter("SequenceNumber > 1000")} + *
Notifications where the {@linkplain Notification#getSequenceNumber() + * sequence number} is greater than 1000. + * + *
{@code QueryNotificationFilter(AttributeChangeNotification.class, null)} + *
Notifications where the notification class is + * {@link AttributeChangeNotification} or a subclass of it. + * + *
{@code QueryNotificationFilter(AttributeChangeNotification.class, + * "AttributeName = 'Size'")} + *
Notifications where the notification class is + * {@link AttributeChangeNotification} or a subclass, and where the + * {@linkplain AttributeChangeNotification#getAttributeName() name of the + * changed attribute} is {@code Size}. + * + *
{@code QueryNotificationFilter(AttributeChangeNotification.class, + * "AttributeName = 'Size' and NewValue - OldValue > 100")} + *
As above, but the difference between the + * {@linkplain AttributeChangeNotification#getNewValue() new value} and the + * {@linkplain AttributeChangeNotification#getOldValue() old value} must be + * greater than 100. + * + *
{@code QueryNotificationFilter("like 'com.example.mydomain:*'")} + *
Notifications where the {@linkplain Notification#getSource() source} + * is an ObjectName that matches the pattern. + * + *
{@code QueryNotificationFilter("Source.canonicalName like + * 'com.example.mydomain:%'")} + *
Another way to write the previous example. + * + *
{@code QueryNotificationFilter(MBeanServerNotification.class, + * "Type = 'JMX.mbean.registered' and MBeanName.canonicalName like + * 'com.example.mydomain:%'")} + *
Notifications of class {@link MBeanServerNotification} representing + * an object registered in the domain {@code com.example.mydomain}. + * + *
+ * + *

How it works

+ * + *

Although the examples above are clear, looking closely at the + * Query API reveals a subtlety. A {@link QueryExp} is evaluated on + * an {@link ObjectName}, not a {@code Notification}.

+ * + *

Every time a {@code Notification} is to be filtered by a + * {@code QueryNotificationFilter}, a special {@link MBeanServer} is created. + * This {@code MBeanServer} contains exactly one MBean, which represents the + * {@code Notification}. If the {@linkplain Notification#getSource() + * source} of the notification is an {@code ObjectName}, which is + * recommended practice, then the name of the MBean representing the + * {@code Notification} will be this {@code ObjectName}. Otherwise the + * name is unspecified.

+ * + *

The query specified in the {@code QueryNotificationFilter} constructor + * is evaluated against this {@code MBeanServer} and {@code ObjectName}, + * and the filter returns true if and only if the query does. If the + * query throws an exception, then the filter will return false.

+ * + *

The MBean representing the {@code Notification} has one attribute for + * every property of the {@code Notification}. Specifically, for every public + * method {@code T getX()} in the {@code NotificationClass}, the MBean will + * have an attribute called {@code X} of type {@code T}. For example, if the + * {@code Notification} is an {@code AttributeChangeNotification}, then the + * MBean will have an attribute called {@code AttributeName} of type + * {@code "java.lang.String"}, corresponding to the method {@link + * AttributeChangeNotification#getAttributeName}.

+ * + *

Query evaluation usually involves calls to the methods of {@code + * MBeanServer}. The methods have the following behavior:

+ * + *
    + *
  • The {@link MBeanServer#getAttribute getAttribute} method returns the + * value of the corresponding property. + *
  • The {@link MBeanServer#getObjectInstance getObjectInstance} + * method returns an {@link ObjectInstance} where the {@link + * ObjectInstance#getObjectName ObjectName} is the name of the MBean and the + * {@link ObjectInstance#getClassName ClassName} is the class name of the + * {@code Notification}. + *
  • The {@link MBeanServer#isInstanceOf isInstanceOf} method returns true + * if and only if the {@code Notification}'s {@code ClassLoader} can load the + * named class, and the {@code Notification} is an {@linkplain Class#isInstance + * instance} of that class. + *
+ * + *

These are the only {@code MBeanServer} methods that are needed to + * evaluate standard queries. The behavior of the other {@code MBeanServer} + * methods is unspecified.

+ * + * @since 1.7 + */ +public class QueryNotificationFilter implements NotificationFilter { + private static final long serialVersionUID = -8408613922660635231L; + + private static final ObjectName DEFAULT_NAME = + Util.newObjectName(":type=Notification"); + private static final QueryExp trueQuery; + static { + ValueExp zero = Query.value(0); + trueQuery = Query.eq(zero, zero); + } + + private final QueryExp query; + + /** + * Construct a {@code QueryNotificationFilter} that evaluates the given + * {@code QueryExp} to determine whether to accept a notification. + * + * @param query the {@code QueryExp} to evaluate. Can be null, + * in which case all notifications are accepted. + */ + public QueryNotificationFilter(QueryExp query) { + if (query == null) + this.query = trueQuery; + else + this.query = query; + } + + /** + * Construct a {@code QueryNotificationFilter} that evaluates the query + * in the given string to determine whether to accept a notification. + * The string is converted into a {@code QueryExp} using + * {@link Query#fromString Query.fromString}. + * + * @param query the string specifying the query to evaluate. Can be null, + * in which case all notifications are accepted. + * + * @throws IllegalArgumentException if the string is not a valid + * query string. + */ + public QueryNotificationFilter(String query) { + this(Query.fromString(query)); + } + + /** + *

Construct a {@code QueryNotificationFilter} that evaluates the query + * in the given string to determine whether to accept a notification, + * and where the notification must also be an instance of the given class. + * The string is converted into a {@code QueryExp} using + * {@link Query#fromString Query.fromString}.

+ * + * @param notifClass the class that the notification must be an instance of. + * Cannot be null. + * + * @param query the string specifying the query to evaluate. Can be null, + * in which case all notifications are accepted. + * + * @throws IllegalArgumentException if the string is not a valid + * query string, or if {@code notifClass} is null. + */ + public QueryNotificationFilter( + Class notifClass, String query) { + this(Query.and(Query.isInstanceOf(Query.value(notNull(notifClass).getName())), + Query.fromString(query))); + } + + private static T notNull(T x) { + if (x == null) + throw new IllegalArgumentException("Null argument"); + return x; + } + + /** + * Retrieve the query that this notification filter will evaluate for + * each notification. + * + * @return the query. + */ + public QueryExp getQuery() { + return query; + } + + public boolean isNotificationEnabled(Notification notification) { + ObjectName name; + + Object source = notification.getSource(); + if (source instanceof ObjectName) + name = (ObjectName) source; + else + name = DEFAULT_NAME; + + MBS mbsImpl = new MBS(notification, name); + MBeanServer mbs = (MBeanServer) Proxy.newProxyInstance( + MBeanServer.class.getClassLoader(), + new Class[] {MBeanServer.class}, + new ForwardIH(mbsImpl)); + return evalQuery(query, mbs, name); + } + + private static boolean evalQuery( + QueryExp query, MBeanServer mbs, ObjectName name) { + MBeanServer oldMBS = QueryEval.getMBeanServer(); + try { + if (mbs != null) + query.setMBeanServer(mbs); + return query.apply(name); + } catch (Exception e) { + return false; + } finally { + query.setMBeanServer(oldMBS); + } + } + + private static class ForwardIH implements InvocationHandler { + private final MBS mbs; + + ForwardIH(MBS mbs) { + this.mbs = mbs; + } + + public Object invoke(Object proxy, Method method, Object[] args) + throws Throwable { + Method forward; + try { + forward = MBS.class.getMethod( + method.getName(), method.getParameterTypes()); + } catch (NoSuchMethodException e) { + throw new UnsupportedOperationException(method.getName()); + } + try { + return forward.invoke(mbs, args); + } catch (InvocationTargetException e) { + throw e.getCause(); + } + } + } + + private static class MBS { + private final Notification notification; + private final ObjectName objectName; + private final ObjectInstance objectInstance; + private volatile DynamicMBean mbean; + + MBS(Notification n, ObjectName name) { + this.notification = n; + this.objectName = name; + this.objectInstance = new ObjectInstance(name, n.getClass().getName()); + } + + private void checkName(ObjectName name) throws InstanceNotFoundException { + if (!objectName.equals(name)) + throw new InstanceNotFoundException(String.valueOf(name)); + } + + private DynamicMBean mbean(ObjectName name) + throws InstanceNotFoundException, ReflectionException { + if (mbean == null) { + try { + mbean = new NotificationMBeanSupport(notification); + } catch (NotCompliantMBeanException e) { + throw new ReflectionException(e); + } + } + return mbean; + } + + public ObjectInstance getObjectInstance(ObjectName name) + throws InstanceNotFoundException { + checkName(name); + return objectInstance; + } + + public Set queryMBeans(ObjectName name, QueryExp query) { + Set names = queryNames(name, query); + switch (names.size()) { + case 0: + return Collections.emptySet(); + case 1: + return Collections.singleton(objectInstance); + default: + throw new UnsupportedOperationException("Internal error"); + } + } + + public Set queryNames(ObjectName name, QueryExp query) { + if ((name != null && !name.apply(objectName)) || + (query != null && !evalQuery(query, null, name))) + return Collections.emptySet(); + return Collections.singleton(objectName); + } + + public boolean isRegistered(ObjectName name) { + return objectName.equals(name); + } + + public Integer getMBeanCount() { + return 1; + } + + public Object getAttribute(ObjectName name, String attribute) + throws MBeanException, AttributeNotFoundException, + InstanceNotFoundException, ReflectionException { + return mbean(name).getAttribute(attribute); + } + + public AttributeList getAttributes(ObjectName name, String[] attributes) + throws InstanceNotFoundException, ReflectionException { + return mbean(name).getAttributes(attributes); + } + + public String getDefaultDomain() { + return objectName.getDomain(); + } + + public String[] getDomains() { + return new String[] {objectName.getDomain()}; + } + + public MBeanInfo getMBeanInfo(ObjectName name) + throws InstanceNotFoundException, ReflectionException { + return mbean(name).getMBeanInfo(); + } + + public boolean isInstanceOf(ObjectName name, String className) + throws InstanceNotFoundException { + try { + mbean(name); + ClassLoader loader = notification.getClass().getClassLoader(); + Class c = Class.forName(className, false, loader); + return c.isInstance(notification); + } catch (ReflectionException e) { + return false; + } catch (ClassNotFoundException e) { + return false; + } + } + + public ClassLoader getClassLoaderFor(ObjectName mbeanName) + throws InstanceNotFoundException { + checkName(mbeanName); + return notification.getClass().getClassLoader(); + } + } +} diff --git a/jdk/test/javax/management/query/QueryNotifFilterTest.java b/jdk/test/javax/management/query/QueryNotifFilterTest.java new file mode 100644 index 00000000000..b22bf1baa5f --- /dev/null +++ b/jdk/test/javax/management/query/QueryNotifFilterTest.java @@ -0,0 +1,347 @@ +/* + * Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* + * @test QueryNotifFilterTest + * @bug 6610917 + * @summary Test the QueryNotificationFilter class + * @author Eamonn McManus + */ + +import java.util.Arrays; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import javax.management.Attribute; +import javax.management.AttributeChangeNotification; +import javax.management.MBeanAttributeInfo; +import javax.management.MBeanInfo; +import javax.management.MBeanServer; +import javax.management.MalformedObjectNameException; +import javax.management.Notification; +import javax.management.NotificationFilter; +import javax.management.ObjectInstance; +import javax.management.ObjectName; +import javax.management.Query; +import javax.management.QueryEval; +import javax.management.QueryExp; +import javax.management.QueryNotificationFilter; + +public class QueryNotifFilterTest { + private static class Case { + final Notification notif; + final QueryExp query; + final boolean expect; + final Class notifClass; + Case(Notification notif, String query, boolean expect) { + this(notif, query, notif.getClass(), expect); + } + Case(Notification notif, String query, + Class notifClass, boolean expect) { + this(notif, Query.fromString(query), notifClass, expect); + } + Case(Notification notif, QueryExp query, boolean expect) { + this(notif, query, notif.getClass(), expect); + } + Case(Notification notif, QueryExp query, + Class notifClass, boolean expect) { + this.notif = notif; + this.query = query; + this.expect = expect; + this.notifClass = notifClass; + } + } + + /* In principle users can create their own implementations of QueryExp + * and use them with QueryNotificationFilter. If they do so, then + * they can call any MBeanServer method. Not all of those methods + * will work with the special MBeanServer we concoct to analyze a + * Notification, but some will, including some that are not called + * by the standard queries. So we check each of those cases too. + */ + private static class ExoticCase { + final Notification trueNotif; + final Notification falseNotif; + final QueryExp query; + ExoticCase(Notification trueNotif, Notification falseNotif, QueryExp query) { + this.trueNotif = trueNotif; + this.falseNotif = falseNotif; + this.query = query; + } + } + + private static abstract class ExoticQuery + extends QueryEval implements QueryExp { + private final String queryString; + ExoticQuery(String queryString) { + this.queryString = queryString; + } + abstract boolean apply(MBeanServer mbs, ObjectName name) throws Exception; + @Override + public boolean apply(ObjectName name) { + try { + return apply(getMBeanServer(), name); + } catch (Exception e) { + e.printStackTrace(System.out); + return false; + } + } + @Override + public String toString() { + return queryString; + } + } + + private static ObjectName makeObjectName(String s) { + try { + return new ObjectName(s); + } catch (MalformedObjectNameException e) { + throw new RuntimeException(e); + } + } + + public static class CustomNotification extends Notification { + public CustomNotification(String type, Object source, long seqNo) { + super(type, source, seqNo); + } + + public String getName() { + return "claude"; + } + + public boolean isInteresting() { + return true; + } + } + + private static final Notification simpleNotif = + new Notification("mytype", "source", 0L); + private static final Notification attrChangeNotif = + new AttributeChangeNotification( + "x", 0L, 0L, "msg", "AttrName", "int", 2, 3); + private static final ObjectName testObjectName = makeObjectName("a:b=c"); + private static final Notification sourcedNotif = + new Notification("mytype", testObjectName, 0L); + private static final Notification customNotif = + new CustomNotification("mytype", testObjectName, 0L); + + private static final Case[] testCases = { + new Case(simpleNotif, "Type = 'mytype'", true), + new Case(simpleNotif, "Type = 'mytype'", + Notification.class, true), + new Case(simpleNotif, "Type = 'mytype'", + AttributeChangeNotification.class, false), + new Case(simpleNotif, "Type != 'mytype'", false), + new Case(simpleNotif, "Type = 'somethingelse'", false), + new Case(attrChangeNotif, "AttributeName = 'AttrName'", true), + new Case(attrChangeNotif, + "instanceof 'javax.management.AttributeChangeNotification'", + true), + new Case(attrChangeNotif, + "instanceof 'javax.management.Notification'", + true), + new Case(attrChangeNotif, + "instanceof 'javax.management.relation.MBeanServerNotification'", + false), + new Case(attrChangeNotif, + "class = 'javax.management.AttributeChangeNotification'", + true), + new Case(attrChangeNotif, + "javax.management.AttributeChangeNotification#AttributeName = 'AttrName'", + true), + new Case(sourcedNotif, + testObjectName, + true), + new Case(sourcedNotif, + makeObjectName("a*:b=*"), + true), + new Case(sourcedNotif, + makeObjectName("a*:c=*"), + false), + new Case(customNotif, "Name = 'claude'", true), + new Case(customNotif, "Name = 'tiddly'", false), + new Case(customNotif, "Interesting = true", true), + new Case(customNotif, "Interesting = false", false), + }; + + private static final ExoticCase[] exoticTestCases = { + new ExoticCase( + simpleNotif, new Notification("notmytype", "source", 0L), + new ExoticQuery("getAttributes") { + boolean apply(MBeanServer mbs, ObjectName name) + throws Exception { + List attrs = mbs.getAttributes( + name, new String[] {"Type", "Source"}).asList(); + return (attrs.get(0).equals(new Attribute("Type", "mytype")) && + attrs.get(1).equals(new Attribute("Source", "source"))); + } + }), + new ExoticCase( + new Notification("mytype", "source", 0L) {}, + simpleNotif, + new ExoticQuery("getClassLoaderFor") { + boolean apply(MBeanServer mbs, ObjectName name) + throws Exception { + return (mbs.getClassLoaderFor(name) == + this.getClass().getClassLoader()); + } + }), + new ExoticCase( + sourcedNotif, simpleNotif, + new ExoticQuery("getDomains") { + boolean apply(MBeanServer mbs, ObjectName name) + throws Exception { + return Arrays.equals(mbs.getDomains(), + new String[] {testObjectName.getDomain()}); + } + }), + new ExoticCase( + simpleNotif, attrChangeNotif, + new ExoticQuery("getMBeanInfo") { + boolean apply(MBeanServer mbs, ObjectName name) + throws Exception { + MBeanInfo mbi = mbs.getMBeanInfo(name); + // If we ever add a constructor to Notification then + // we will have to change the 4 below. + if (mbi.getOperations().length > 0 || + mbi.getConstructors().length != 4 || + mbi.getNotifications().length > 0) + return false; + Set expect = new HashSet( + Arrays.asList( + "Class", "Message", "SequenceNumber", "Source", + "TimeStamp", "Type", "UserData")); + Set actual = new HashSet(); + for (MBeanAttributeInfo mbai : mbi.getAttributes()) + actual.add(mbai.getName()); + return actual.equals(expect); + } + }), + new ExoticCase( + simpleNotif, attrChangeNotif, + new ExoticQuery("getObjectInstance") { + boolean apply(MBeanServer mbs, ObjectName name) + throws Exception { + ObjectInstance oi = mbs.getObjectInstance(name); + return oi.getClassName().equals(Notification.class.getName()); + } + }), + new ExoticCase( + sourcedNotif, simpleNotif, + new ExoticQuery("queryNames") { + boolean apply(MBeanServer mbs, ObjectName name) + throws Exception { + Set names = mbs.queryNames(null, + Query.eq(Query.attr("Type"), Query.value("mytype"))); + return names.equals(Collections.singleton(testObjectName)); + } + }), + new ExoticCase( + sourcedNotif, simpleNotif, + new ExoticQuery("queryMBeans") { + boolean apply(MBeanServer mbs, ObjectName name) + throws Exception { + Set insts = mbs.queryMBeans(null, + Query.eq(Query.attr("Type"), Query.value("mytype"))); + if (insts.size() != 1) + return false; + ObjectInstance inst = insts.iterator().next(); + return (inst.getObjectName().equals(testObjectName) && + inst.getClassName().equals(Notification.class.getName())); + } + }), + }; + + private static enum Test { + QUERY_EXP("query"), STRING("string"), STRING_PLUS_CLASS("string with class"); + private final String name; + Test(String name) { + this.name = name; + } + @Override + public String toString() { + return name; + } + } + + public static void main(String[] args) throws Exception { + boolean allok = true; + for (Case testCase : testCases) { + for (Test test : Test.values()) { + QueryNotificationFilter nf; + String queryString; + switch (test) { + case QUERY_EXP: { + QueryExp inst = Query.isInstanceOf( + Query.value(testCase.notifClass.getName())); + QueryExp and = Query.and(inst, testCase.query); + queryString = Query.toString(and); + nf = new QueryNotificationFilter(and); + break; + } + case STRING: { + String s = "instanceof '" + testCase.notifClass.getName() + "'"; + queryString = s + " and " + Query.toString(testCase.query); + nf = new QueryNotificationFilter(queryString); + break; + } + case STRING_PLUS_CLASS: + queryString = null; + nf = new QueryNotificationFilter( + testCase.notifClass, Query.toString(testCase.query)); + break; + default: + throw new AssertionError(); + } + boolean accept = nf.isNotificationEnabled(testCase.notif); + if (queryString != null) { + queryString = Query.toString(Query.fromString(queryString)); + if (!queryString.equals(Query.toString(nf.getQuery()))) { + System.out.println("FAIL: query string mismatch: expected " + + "\"" + queryString + "\", got \"" + + Query.toString(nf.getQuery())); + allok = false; + } + } + boolean ok = (accept == testCase.expect); + System.out.println((ok ? "pass" : "FAIL") + ": " + + testCase.query + " (" + test + ")"); + allok &= ok; + } + } + for (ExoticCase testCase : exoticTestCases) { + NotificationFilter nf = new QueryNotificationFilter(testCase.query); + for (boolean expect : new boolean[] {true, false}) { + Notification n = expect ? testCase.trueNotif : testCase.falseNotif; + boolean accept = nf.isNotificationEnabled(n); + boolean ok = (accept == expect); + System.out.println((ok ? "pass" : "FAIL") + ": " + + testCase.query + ": " + n); + allok &= ok; + } + } + if (!allok) + throw new Exception("TEST FAILED"); + } +} From 4eb04f83d50bd58d385f5e14f76c56bbd2b088f9 Mon Sep 17 00:00:00 2001 From: Anthony Petrov Date: Tue, 1 Apr 2008 17:38:46 +0400 Subject: [PATCH 122/258] 6681889: JSN security test headline/noWarningApp failed with NPE exception The java.awt.Component.changeSupportLock field should be initialized in the readObject() method. Reviewed-by: son, art --- jdk/src/share/classes/java/awt/Component.java | 6 +- ...opertyChangeListenerLockSerialization.java | 402 ++++++++++++++++++ 2 files changed, 407 insertions(+), 1 deletion(-) create mode 100644 jdk/test/java/awt/Window/PropertyChangeListenerLockSerialization/PropertyChangeListenerLockSerialization.java diff --git a/jdk/src/share/classes/java/awt/Component.java b/jdk/src/share/classes/java/awt/Component.java index b48b8c552fd..005a282442a 100644 --- a/jdk/src/share/classes/java/awt/Component.java +++ b/jdk/src/share/classes/java/awt/Component.java @@ -634,7 +634,9 @@ public abstract class Component implements ImageObserver, MenuContainer, */ private PropertyChangeSupport changeSupport; - private transient final Object changeSupportLock = new Object(); + // Note: this field is considered final, though readObject() prohibits + // initializing final fields. + private transient Object changeSupportLock = new Object(); private Object getChangeSupportLock() { return changeSupportLock; } @@ -8310,6 +8312,8 @@ public abstract class Component implements ImageObserver, MenuContainer, private void readObject(ObjectInputStream s) throws ClassNotFoundException, IOException { + changeSupportLock = new Object(); + s.defaultReadObject(); appContext = AppContext.getAppContext(); diff --git a/jdk/test/java/awt/Window/PropertyChangeListenerLockSerialization/PropertyChangeListenerLockSerialization.java b/jdk/test/java/awt/Window/PropertyChangeListenerLockSerialization/PropertyChangeListenerLockSerialization.java new file mode 100644 index 00000000000..1a50818148a --- /dev/null +++ b/jdk/test/java/awt/Window/PropertyChangeListenerLockSerialization/PropertyChangeListenerLockSerialization.java @@ -0,0 +1,402 @@ +/* + * Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* + @test + @bug 6681889 + @summary Showing a deserialized frame should not throw NPE + @author anthony.petrov@...: area=awt.toplevel + @run main PropertyChangeListenerLockSerialization +*/ + + +/** + * PropertyChangeListenerLockSerialization.java + * + * summary: Showing a deserialized frame should not throw NPE + */ + +import java.awt.*; +import java.awt.event.*; +import java.io.*; +import java.net.*; + +public class PropertyChangeListenerLockSerialization +{ + + private static void init() + { + //*** Create instructions for the user here *** + + String[] instructions = + { + "This is an AUTOMATIC test, simply wait until it is done.", + "The result (passed or failed) will be shown in the", + "message window below." + }; + Sysout.createDialog( ); + Sysout.printInstructions( instructions ); + + File file = + new File(System.getProperty("test.classes", "."), "frame.ser"); + + Frame f = new Frame("Frame"); + f.setBounds(250, 50, 300, 300); + try { + OutputStream o = new FileOutputStream(file); + ObjectOutputStream oo = new ObjectOutputStream(o); + + oo.writeObject(f); + oo.close(); + } catch (IOException ex) { + ex.printStackTrace(); + fail("Unable to serialize the frame: " + ex); + } + + // Cleanup the frame + f.dispose(); + f = null; + + try { + ObjectInputStream i = new ObjectInputStream(new FileInputStream(file)); + + f = (Frame)i.readObject(); + f.show(); + } catch (NullPointerException ex) { + ex.printStackTrace(); + fail("The NullPointerException has been thrown: " + ex); + } catch (Exception ex) { + ex.printStackTrace(); + fail("Error while deserializing the frame: " + ex); + } + + // Cleanup the frame + f.dispose(); + f = null; + + pass(); + + }//End init() + + + + /***************************************************** + * Standard Test Machinery Section + * DO NOT modify anything in this section -- it's a + * standard chunk of code which has all of the + * synchronisation necessary for the test harness. + * By keeping it the same in all tests, it is easier + * to read and understand someone else's test, as + * well as insuring that all tests behave correctly + * with the test harness. + * There is a section following this for test- + * classes + ******************************************************/ + private static boolean theTestPassed = false; + private static boolean testGeneratedInterrupt = false; + private static String failureMessage = ""; + + private static Thread mainThread = null; + + private static int sleepTime = 300000; + + // Not sure about what happens if multiple of this test are + // instantiated in the same VM. Being static (and using + // static vars), it aint gonna work. Not worrying about + // it for now. + public static void main( String args[] ) throws InterruptedException + { + mainThread = Thread.currentThread(); + try + { + init(); + } + catch( TestPassedException e ) + { + //The test passed, so just return from main and harness will + // interepret this return as a pass + return; + } + //At this point, neither test pass nor test fail has been + // called -- either would have thrown an exception and ended the + // test, so we know we have multiple threads. + + //Test involves other threads, so sleep and wait for them to + // called pass() or fail() + try + { + Thread.sleep( sleepTime ); + //Timed out, so fail the test + throw new RuntimeException( "Timed out after " + sleepTime/1000 + " seconds" ); + } + catch (InterruptedException e) + { + //The test harness may have interrupted the test. If so, rethrow the exception + // so that the harness gets it and deals with it. + if( ! testGeneratedInterrupt ) throw e; + + //reset flag in case hit this code more than once for some reason (just safety) + testGeneratedInterrupt = false; + + if ( theTestPassed == false ) + { + throw new RuntimeException( failureMessage ); + } + } + + }//main + + public static synchronized void setTimeoutTo( int seconds ) + { + sleepTime = seconds * 1000; + } + + public static synchronized void pass() + { + Sysout.println( "The test passed." ); + Sysout.println( "The test is over, hit Ctl-C to stop Java VM" ); + //first check if this is executing in main thread + if ( mainThread == Thread.currentThread() ) + { + //Still in the main thread, so set the flag just for kicks, + // and throw a test passed exception which will be caught + // and end the test. + theTestPassed = true; + throw new TestPassedException(); + } + theTestPassed = true; + testGeneratedInterrupt = true; + mainThread.interrupt(); + }//pass() + + public static synchronized void fail() + { + //test writer didn't specify why test failed, so give generic + fail( "it just plain failed! :-)" ); + } + + public static synchronized void fail( String whyFailed ) + { + Sysout.println( "The test failed: " + whyFailed ); + Sysout.println( "The test is over, hit Ctl-C to stop Java VM" ); + //check if this called from main thread + if ( mainThread == Thread.currentThread() ) + { + //If main thread, fail now 'cause not sleeping + throw new RuntimeException( whyFailed ); + } + theTestPassed = false; + testGeneratedInterrupt = true; + failureMessage = whyFailed; + mainThread.interrupt(); + }//fail() + +}// class PropertyChangeListenerLockSerialization + +//This exception is used to exit from any level of call nesting +// when it's determined that the test has passed, and immediately +// end the test. +class TestPassedException extends RuntimeException +{ +} + +//*********** End Standard Test Machinery Section ********** + + +//************ Begin classes defined for the test **************** + +// if want to make listeners, here is the recommended place for them, then instantiate +// them in init() + +/* Example of a class which may be written as part of a test +class NewClass implements anInterface + { + static int newVar = 0; + + public void eventDispatched(AWTEvent e) + { + //Counting events to see if we get enough + eventCount++; + + if( eventCount == 20 ) + { + //got enough events, so pass + + PropertyChangeListenerLockSerialization.pass(); + } + else if( tries == 20 ) + { + //tried too many times without getting enough events so fail + + PropertyChangeListenerLockSerialization.fail(); + } + + }// eventDispatched() + + }// NewClass class + +*/ + + +//************** End classes defined for the test ******************* + + + + +/**************************************************** + Standard Test Machinery + DO NOT modify anything below -- it's a standard + chunk of code whose purpose is to make user + interaction uniform, and thereby make it simpler + to read and understand someone else's test. + ****************************************************/ + +/** + This is part of the standard test machinery. + It creates a dialog (with the instructions), and is the interface + for sending text messages to the user. + To print the instructions, send an array of strings to Sysout.createDialog + WithInstructions method. Put one line of instructions per array entry. + To display a message for the tester to see, simply call Sysout.println + with the string to be displayed. + This mimics System.out.println but works within the test harness as well + as standalone. + */ + +class Sysout +{ + private static TestDialog dialog; + + public static void createDialogWithInstructions( String[] instructions ) + { + dialog = new TestDialog( new Frame(), "Instructions" ); + dialog.printInstructions( instructions ); + dialog.setVisible(true); + println( "Any messages for the tester will display here." ); + } + + public static void createDialog( ) + { + dialog = new TestDialog( new Frame(), "Instructions" ); + String[] defInstr = { "Instructions will appear here. ", "" } ; + dialog.printInstructions( defInstr ); + dialog.setVisible(true); + println( "Any messages for the tester will display here." ); + } + + + public static void printInstructions( String[] instructions ) + { + dialog.printInstructions( instructions ); + } + + + public static void println( String messageIn ) + { + dialog.displayMessage( messageIn ); + System.out.println(messageIn); + } + +}// Sysout class + +/** + This is part of the standard test machinery. It provides a place for the + test instructions to be displayed, and a place for interactive messages + to the user to be displayed. + To have the test instructions displayed, see Sysout. + To have a message to the user be displayed, see Sysout. + Do not call anything in this dialog directly. + */ +class TestDialog extends Dialog +{ + + TextArea instructionsText; + TextArea messageText; + int maxStringLength = 80; + + //DO NOT call this directly, go through Sysout + public TestDialog( Frame frame, String name ) + { + super( frame, name ); + int scrollBoth = TextArea.SCROLLBARS_BOTH; + instructionsText = new TextArea( "", 15, maxStringLength, scrollBoth ); + add( "North", instructionsText ); + + messageText = new TextArea( "", 5, maxStringLength, scrollBoth ); + add("Center", messageText); + + pack(); + + setVisible(true); + }// TestDialog() + + //DO NOT call this directly, go through Sysout + public void printInstructions( String[] instructions ) + { + //Clear out any current instructions + instructionsText.setText( "" ); + + //Go down array of instruction strings + + String printStr, remainingStr; + for( int i=0; i < instructions.length; i++ ) + { + //chop up each into pieces maxSringLength long + remainingStr = instructions[ i ]; + while( remainingStr.length() > 0 ) + { + //if longer than max then chop off first max chars to print + if( remainingStr.length() >= maxStringLength ) + { + //Try to chop on a word boundary + int posOfSpace = remainingStr. + lastIndexOf( ' ', maxStringLength - 1 ); + + if( posOfSpace <= 0 ) posOfSpace = maxStringLength - 1; + + printStr = remainingStr.substring( 0, posOfSpace + 1 ); + remainingStr = remainingStr.substring( posOfSpace + 1 ); + } + //else just print + else + { + printStr = remainingStr; + remainingStr = ""; + } + + instructionsText.append( printStr + "\n" ); + + }// while + + }// for + + }//printInstructions() + + //DO NOT call this directly, go through Sysout + public void displayMessage( String messageIn ) + { + messageText.append( messageIn + "\n" ); + System.out.println(messageIn); + } + +}// TestDialog class From 3d9e4854d0ac80e98234861d75c7350c101de15e Mon Sep 17 00:00:00 2001 From: Kelly O'Hair Date: Tue, 1 Apr 2008 15:14:53 -0700 Subject: [PATCH 123/258] 6482134: JDK 6 build error on Windows, Visual Studio .NET on Japanese locale Fix scanning of cl.exe version output, removed CC_TYPE. Reviewed-by: tbell --- jdk/make/common/shared/Compiler-gcc.gmk | 2 -- jdk/make/common/shared/Compiler-msvc.gmk | 8 +++----- jdk/make/common/shared/Sanity.gmk | 2 +- 3 files changed, 4 insertions(+), 8 deletions(-) diff --git a/jdk/make/common/shared/Compiler-gcc.gmk b/jdk/make/common/shared/Compiler-gcc.gmk index 74f9807e09d..d12adac959e 100644 --- a/jdk/make/common/shared/Compiler-gcc.gmk +++ b/jdk/make/common/shared/Compiler-gcc.gmk @@ -45,10 +45,8 @@ ifeq ($(PLATFORM), windows) NMAKE = MFLAGS= MAKEFLAGS= $(COMPILER_PATH)nmake -nologo ifeq ($(ARCH_DATA_MODEL), 32) CC_VER = UNKNOWN - CC_TYPE = UNKNOWN else CC_VER = UNKNOWN - CC_TYPE = UNKNOWN endif _LINK_VER :=$(shell $(LINK) 2>&1 | $(HEAD) -n 1) LINK_VER :=$(call GetVersion,"$(_LINK_VER)") diff --git a/jdk/make/common/shared/Compiler-msvc.gmk b/jdk/make/common/shared/Compiler-msvc.gmk index fbb8e8a5664..41509e51b09 100644 --- a/jdk/make/common/shared/Compiler-msvc.gmk +++ b/jdk/make/common/shared/Compiler-msvc.gmk @@ -47,13 +47,13 @@ ifeq ($(PLATFORM), windows) # unset any GNU Make settings of MFLAGS and MAKEFLAGS which may mess up nmake NMAKE = MFLAGS= MAKEFLAGS= $(COMPILER_PATH)nmake -nologo + # Compiler version and type (Always get word after "Version") + CC_VER := $(shell $(CC) 2>&1 | $(HEAD) -n 1 | $(SED) 's/.*\(Version.*\)/\1/' | $(NAWK) '{print $$2}') + # SDK-64 and MSVC6 put REBASE.EXE in a different places - go figure... ifeq ($(ARCH_DATA_MODEL), 32) - CC_VER := $(shell $(CC) 2>&1 | $(HEAD) -n 1 | $(NAWK) '{print $$8}') LINK_VER := $(shell $(LINK) | $(HEAD) -n 1 | $(NAWK) '{print $$6}') - CC_TYPE := $(shell $(CC) 2>&1 | $(HEAD) -n 1 | $(NAWK) '{print $$5}') CC_MAJORVER :=$(call MajorVersion,$(CC_VER)) - REQUIRED_CCTYPE = Optimizing REQUIRED_CC_VER = 13.10.3077 REQUIRED_LINK_VER = 7.10.3077 ifeq ($(CC_MAJORVER), 12) @@ -85,9 +85,7 @@ ifeq ($(PLATFORM), windows) endif endif else - CC_VER := $(shell $(CC) 2>&1 | $(HEAD) -n 1 | $(NAWK) '{print $$7}') LINK_VER := $(shell $(LINK) | $(HEAD) -n 1 | $(NAWK) '{print $$6}') - CC_TYPE := $(shell $(CC) 2>&1 | $(HEAD) -n 1 | $(NAWK) '{print $$4}') CC_MAJORVER :=$(call MajorVersion,$(CC_VER)) CC_MINORVER :=$(call MinorVersion,$(CC_VER)) CC_MICROVER :=$(call MicroVersion,$(CC_VER)) diff --git a/jdk/make/common/shared/Sanity.gmk b/jdk/make/common/shared/Sanity.gmk index 98bd5b4346c..a6b19476c0b 100644 --- a/jdk/make/common/shared/Sanity.gmk +++ b/jdk/make/common/shared/Sanity.gmk @@ -1335,7 +1335,7 @@ sane-compiler: sane-link ifndef OPENJDK @if [ "$(CC_CHECK)" != "same" ]; then \ $(ECHO) "WARNING: The $(PLATFORM) compiler is not version $(COMPILER_VERSION) $(REQUIRED_CC_VER) \n" \ - " Specifically the $(COMPILER_NAME) $(CC_TYPE) compiler. \n " \ + " Specifically the $(COMPILER_NAME) compiler. \n " \ " $(YOU_ARE_USING) compiler version: $(CC_VER) \n" \ " The compiler was obtained from the following location: \n" \ " $(COMPILER_PATH) \n" \ From de514b4b6eb583ef275bb4bdff42908f96b4a864 Mon Sep 17 00:00:00 2001 From: Kelly O'Hair Date: Tue, 1 Apr 2008 15:41:23 -0700 Subject: [PATCH 124/258] 6627823: Missed whitespace normalization files: jdk/test/java/rmi Just missed a few files being normalized in rev 0. Reviewed-by: xdono --- .../CreatePrivateActivatable.java | 204 ++++---- .../activateFails/ActivateFails.java | 205 ++++---- .../activateFails/ActivateFails_Stub.java | 126 ++--- .../activateFails/ActivateMe.java | 2 +- .../activateFails/ShutdownThread.java | 17 +- .../DownloadActivationGroup.java | 144 +++--- .../DownloadActivationGroup_Stub.java | 54 +- .../MyActivationGroupImpl.java | 10 +- .../CheckDefaultGroupName.java | 26 +- .../activeGroup/IdempotentActiveGroup.java | 134 ++--- .../modifyDescriptor/ActivateMe.java | 2 +- .../modifyDescriptor/ModifyDescriptor.java | 308 +++++------ .../ModifyDescriptor_Stub.java | 262 +++++----- .../stubClassesPermitted/CanCreateStubs.java | 3 +- .../StubClassesPermitted.java | 244 ++++----- .../StubClassesPermitted_Stub.java | 234 ++++----- .../unregisterGroup/ActivateMe.java | 2 +- .../unregisterGroup/CallbackInterface.java | 3 +- .../unregisterGroup/Callback_Stub.java | 138 ++--- .../unregisterGroup/UnregisterGroup.java | 262 +++++----- .../unregisterGroup/UnregisterGroup_Stub.java | 162 +++--- jdk/test/java/rmi/dgc/VMID/CheckVMID.java | 22 +- .../rmi/dgc/dgcAckFailure/DGCAckFailure.java | 194 +++---- .../dgc/dgcAckFailure/DGCAckFailure_Stub.java | 48 +- .../dgcImplInsulation/DGCImplInsulation.java | 86 ++-- .../DGCImplInsulation_Stub.java | 8 +- .../dgc/retryDirtyCalls/RetryDirtyCalls.java | 194 +++---- .../retryDirtyCalls/RetryDirtyCalls_Stub.java | 48 +- .../AltSecurityManager.java | 116 ++--- .../TestSecurityManager.java | 22 +- .../rmi/registry/checkusage/CheckUsage.java | 76 +-- .../classPathCodebase/ClassPathCodebase.java | 204 ++++---- .../rmi/registry/classPathCodebase/Dummy.java | 6 +- .../rmi/registry/emptyName/EmptyName.java | 16 +- .../registry/interfaceHash/InterfaceHash.java | 268 +++++----- .../interfaceHash/ReferenceRegistryStub.java | 260 +++++----- .../MultipleRegistries.java | 68 +-- .../java/rmi/registry/reexport/Reexport.java | 176 +++---- .../benchmark/bench/rmi/BenchServer.java | 23 +- .../benchmark/bench/rmi/BenchServerImpl.java | 51 +- .../bench/rmi/BooleanArrayCalls.java | 51 +- .../benchmark/bench/rmi/BooleanCalls.java | 47 +- .../benchmark/bench/rmi/ByteArrayCalls.java | 51 +- .../benchmark/bench/rmi/ByteCalls.java | 47 +- .../benchmark/bench/rmi/CharArrayCalls.java | 51 +- .../benchmark/bench/rmi/CharCalls.java | 47 +- .../benchmark/bench/rmi/ClassLoading.java | 23 +- .../benchmark/bench/rmi/DoubleArrayCalls.java | 51 +- .../benchmark/bench/rmi/DoubleCalls.java | 47 +- .../benchmark/bench/rmi/ExceptionCalls.java | 53 +- .../benchmark/bench/rmi/ExportObjs.java | 31 +- .../benchmark/bench/rmi/FloatArrayCalls.java | 51 +- .../benchmark/bench/rmi/FloatCalls.java | 47 +- .../benchmark/bench/rmi/IntArrayCalls.java | 51 +- .../benchmark/bench/rmi/IntCalls.java | 47 +- .../benchmark/bench/rmi/LongArrayCalls.java | 51 +- .../benchmark/bench/rmi/LongCalls.java | 47 +- .../reliability/benchmark/bench/rmi/Main.java | 477 +++++++++--------- .../benchmark/bench/rmi/NullCalls.java | 45 +- .../benchmark/bench/rmi/ObjArrayCalls.java | 71 ++- .../benchmark/bench/rmi/ObjTreeCalls.java | 67 ++- .../benchmark/bench/rmi/ProxyArrayCalls.java | 83 ++- .../bench/rmi/RemoteObjArrayCalls.java | 57 +-- .../benchmark/bench/rmi/ShortArrayCalls.java | 53 +- .../benchmark/bench/rmi/ShortCalls.java | 47 +- .../bench/rmi/SmallObjTreeCalls.java | 51 +- .../benchmark/bench/serial/BooleanArrays.java | 60 ++- .../benchmark/bench/serial/Booleans.java | 54 +- .../benchmark/bench/serial/ByteArrays.java | 60 ++- .../benchmark/bench/serial/Bytes.java | 53 +- .../benchmark/bench/serial/CharArrays.java | 60 ++- .../benchmark/bench/serial/Chars.java | 53 +- .../benchmark/bench/serial/ClassDesc.java | 47 +- .../benchmark/bench/serial/Cons.java | 35 +- .../bench/serial/CustomDefaultObjTrees.java | 97 ++-- .../bench/serial/CustomObjTrees.java | 141 +++--- .../benchmark/bench/serial/DoubleArrays.java | 60 ++- .../benchmark/bench/serial/Doubles.java | 53 +- .../bench/serial/ExternObjTrees.java | 157 +++--- .../benchmark/bench/serial/FloatArrays.java | 60 ++- .../benchmark/bench/serial/Floats.java | 53 +- .../bench/serial/GetPutFieldTrees.java | 109 ++-- .../benchmark/bench/serial/IntArrays.java | 60 ++- .../benchmark/bench/serial/Ints.java | 53 +- .../benchmark/bench/serial/LongArrays.java | 60 ++- .../benchmark/bench/serial/Longs.java | 53 +- .../benchmark/bench/serial/Main.java | 201 ++++---- .../benchmark/bench/serial/ObjArrays.java | 92 ++-- .../benchmark/bench/serial/ObjTrees.java | 89 ++-- .../benchmark/bench/serial/ProxyArrays.java | 98 ++-- .../bench/serial/ProxyClassDesc.java | 103 ++-- .../benchmark/bench/serial/RepeatObjs.java | 67 ++- .../benchmark/bench/serial/ReplaceTrees.java | 115 +++-- .../benchmark/bench/serial/ShortArrays.java | 60 ++- .../benchmark/bench/serial/Shorts.java | 53 +- .../benchmark/bench/serial/SmallObjTrees.java | 71 ++- .../benchmark/bench/serial/StreamBuffer.java | 165 +++--- .../benchmark/bench/serial/Strings.java | 75 ++- .../java/rmi/reliability/juicer/Apple.java | 4 +- .../rmi/reliability/juicer/AppleEvent.java | 36 +- .../rmi/reliability/juicer/AppleImpl.java | 44 +- .../rmi/reliability/juicer/AppleUser.java | 2 +- .../rmi/reliability/juicer/AppleUserImpl.java | 422 ++++++++-------- .../reliability/juicer/ApplicationServer.java | 158 +++--- .../java/rmi/reliability/juicer/Orange.java | 8 +- .../rmi/reliability/juicer/OrangeEcho.java | 6 +- .../reliability/juicer/OrangeEchoImpl.java | 30 +- .../rmi/reliability/juicer/OrangeImpl.java | 42 +- .../activatable/CompressConstants.java | 10 +- .../activatable/CompressInputStream.java | 112 ++-- .../activatable/CompressOutputStream.java | 60 +-- .../useSocketFactory/activatable/Echo.java | 2 +- .../activatable/EchoImpl.java | 120 ++--- .../activatable/EchoImpl_Stub.java | 56 +- .../activatable/MultiSocketFactory.java | 301 ++++++----- .../activatable/UseCustomSocketFactory.java | 202 ++++---- .../useSocketFactory/registry/Compress.java | 370 +++++++------- .../useSocketFactory/registry/Hello.java | 2 +- .../useSocketFactory/registry/HelloImpl.java | 72 +-- .../registry/HelloImpl_Stub.java | 104 ++-- .../registry/UseCustomSocketFactory.java | 136 ++--- .../unicast/CompressConstants.java | 10 +- .../unicast/CompressInputStream.java | 112 ++-- .../unicast/CompressOutputStream.java | 60 +-- .../useSocketFactory/unicast/Echo.java | 2 +- .../useSocketFactory/unicast/EchoImpl.java | 68 +-- .../unicast/EchoImpl_Stub.java | 48 +- .../unicast/MultiSocketFactory.java | 301 ++++++----- .../unicast/UseCustomSocketFactory.java | 132 ++--- .../setLogPermission/SetLogPermission.java | 74 +-- .../changeHostName/ChangeHostName.java | 54 +- .../changeHostName/ChangeHostName_Stub.java | 46 +- .../KeepAliveDuringCall.java | 124 ++--- .../KeepAliveDuringCall_Stub.java | 70 +-- .../keepAliveDuringCall/Shutdown.java | 2 +- .../keepAliveDuringCall/ShutdownImpl.java | 76 +-- .../ShutdownImpl_Stub.java | 46 +- .../keepAliveDuringCall/ShutdownMonitor.java | 2 +- .../MarshalAfterUnexport.java | 48 +- .../MarshalAfterUnexport2.java | 60 +-- .../MarshalAfterUnexport2_Stub.java | 46 +- .../MarshalAfterUnexport_Stub.java | 46 +- .../unexportObject/Ping.java | 3 +- .../unexportObject/UnexportLeak.java | 70 ++- .../unexportObject/UnexportLeak_Stub.java | 46 +- .../useDynamicProxies/UseDynamicProxies.java | 110 ++-- .../UseDynamicProxies_Stub.java | 100 ++-- .../CheckUnmarshalOnStopThread.java | 150 +++--- .../CheckUnmarshalOnStopThread_Stub.java | 216 ++++---- .../CheckUnmarshall.java | 5 +- .../PoisonPill.java | 4 +- .../RuntimeExceptionParameter.java | 5 +- .../finiteGCLatency/FiniteGCLatency.java | 106 ++-- .../finiteGCLatency/FiniteGCLatency_Stub.java | 8 +- .../LeaseCheckInterval.java | 108 ++-- .../LeaseCheckInterval_Stub.java | 8 +- .../leaseCheckInterval/SelfTerminator.java | 18 +- .../MarshalledObjectGet.java | 110 ++-- .../MarshalledObjectGet_Stub.java | 8 +- .../UnreferencedContext.java | 210 ++++---- .../UnreferencedContext_Stub.java | 8 +- .../CloseServerSocketOnTermination.java | 122 ++--- .../rmi/transport/checkFQDN/CheckFQDN.java | 180 +++---- .../transport/checkFQDN/CheckFQDNClient.java | 106 ++-- .../transport/checkFQDN/CheckFQDN_Stub.java | 92 ++-- .../transport/checkFQDN/TellServerName.java | 5 +- .../checkLeaseInfoLeak/CheckLeaseLeak.java | 248 ++++----- .../CheckLeaseLeak_Stub.java | 80 +-- .../checkLeaseInfoLeak/LeaseLeak.java | 2 +- .../checkLeaseInfoLeak/LeaseLeakClient.java | 38 +- .../closeServerSocket/CloseServerSocket.java | 120 ++--- .../transport/dgcDeadLock/DGCDeadLock.java | 144 +++--- .../java/rmi/transport/dgcDeadLock/Test.java | 2 +- .../rmi/transport/dgcDeadLock/TestImpl.java | 312 ++++++------ .../transport/dgcDeadLock/TestImpl_Stub.java | 116 ++--- .../handshakeFailure/HandshakeFailure.java | 138 ++--- .../handshakeTimeout/HandshakeTimeout.java | 130 ++--- .../transport/httpSocket/HttpSocketTest.java | 55 +- .../httpSocket/HttpSocketTest_Stub.java | 154 +++--- .../PinClientSocketFactory.java | 160 +++--- .../pinLastArguments/PinLastArguments.java | 62 +-- .../RapidExportUnexport.java | 34 +- .../readTimeout/ReadTimeoutTest.java | 210 ++++---- .../rmi/transport/readTimeout/TestIface.java | 4 +- .../rmi/transport/readTimeout/TestImpl.java | 13 +- .../transport/readTimeout/TestImpl_Stub.java | 48 +- .../reuseDefaultPort/ReuseDefaultPort.java | 50 +- .../RuntimeThreadInheritanceLeak.java | 156 +++--- .../RuntimeThreadInheritanceLeak_Stub.java | 8 +- 189 files changed, 8229 insertions(+), 8318 deletions(-) diff --git a/jdk/test/java/rmi/activation/Activatable/createPrivateActivable/CreatePrivateActivatable.java b/jdk/test/java/rmi/activation/Activatable/createPrivateActivable/CreatePrivateActivatable.java index 32d5747cd5e..f91916430fb 100644 --- a/jdk/test/java/rmi/activation/Activatable/createPrivateActivable/CreatePrivateActivatable.java +++ b/jdk/test/java/rmi/activation/Activatable/createPrivateActivable/CreatePrivateActivatable.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1999-2001 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -49,116 +49,116 @@ import java.util.Properties; public class CreatePrivateActivatable { private static class PrivateActivatable extends Activatable - implements ActivateMe, Runnable + implements ActivateMe, Runnable { - private PrivateActivatable(ActivationID id, MarshalledObject obj) - throws ActivationException, RemoteException - { - super(id, 0); - } + private PrivateActivatable(ActivationID id, MarshalledObject obj) + throws ActivationException, RemoteException + { + super(id, 0); + } - public void ping() - {} + public void ping() + {} - /** - * Spawns a thread to deactivate the object. - */ - public void shutdown() throws Exception - { - (new Thread(this, "CreatePrivateActivatable$PrivateActivatable")).start(); - } + /** + * Spawns a thread to deactivate the object. + */ + public void shutdown() throws Exception + { + (new Thread(this, "CreatePrivateActivatable$PrivateActivatable")).start(); + } - /** - * Thread to deactivate object. First attempts to make object - * inactive (via the inactive method). If that fails (the - * object may still have pending/executing calls), then - * unexport the object forcibly. - */ - public void run() { - ActivationLibrary.deactivate(this, getID()); - } + /** + * Thread to deactivate object. First attempts to make object + * inactive (via the inactive method). If that fails (the + * object may still have pending/executing calls), then + * unexport the object forcibly. + */ + public void run() { + ActivationLibrary.deactivate(this, getID()); + } } - + public static void main(String[] args) { - /* - * The following line is required with the JDK 1.2 VM so that the - * VM can exit gracefully when this test completes. Otherwise, the - * conservative garbage collector will find a handle to the server - * object on the native stack and not clear the weak reference to - * it in the RMI runtime's object table. - */ - Object dummy = new Object(); - RMID rmid = null; - ActivateMe obj; + /* + * The following line is required with the JDK 1.2 VM so that the + * VM can exit gracefully when this test completes. Otherwise, the + * conservative garbage collector will find a handle to the server + * object on the native stack and not clear the weak reference to + * it in the RMI runtime's object table. + */ + Object dummy = new Object(); + RMID rmid = null; + ActivateMe obj; - System.err.println("\nRegression test for bug 4164971\n"); - System.err.println("java.security.policy = " + - System.getProperty("java.security.policy", "no policy")); + System.err.println("\nRegression test for bug 4164971\n"); + System.err.println("java.security.policy = " + + System.getProperty("java.security.policy", "no policy")); - CreatePrivateActivatable server; - try { - TestLibrary.suggestSecurityManager(TestParams.defaultSecurityManager); + CreatePrivateActivatable server; + try { + TestLibrary.suggestSecurityManager(TestParams.defaultSecurityManager); - // start an rmid. - RMID.removeLog(); - rmid = RMID.createRMID(); - rmid.start(); - - /* Cause activation groups to have a security policy that will - * allow security managers to be downloaded and installed - */ - Properties p = new Properties(); - // this test must always set policies/managers in its - // activation groups - p.put("java.security.policy", - TestParams.defaultGroupPolicy); - p.put("java.security.manager", - TestParams.defaultSecurityManager); - - /* - * Activate an object by registering its object - * descriptor and invoking a method on the - * stub returned from the register call. - */ - ActivationGroupDesc groupDesc = - new ActivationGroupDesc(p, null); - ActivationSystem system = ActivationGroup.getSystem(); - ActivationGroupID groupID = system.registerGroup(groupDesc); + // start an rmid. + RMID.removeLog(); + rmid = RMID.createRMID(); + rmid.start(); - System.err.println("Creating descriptor"); - ActivationDesc desc = - new ActivationDesc(groupID, - "CreatePrivateActivatable$PrivateActivatable", - null, null); - - System.err.println("Registering descriptor"); - obj = (ActivateMe) Activatable.register(desc); - - /* - * Loop a bunch of times to force activator to - * spawn VMs (groups) - */ - System.err.println("Activate object via method call"); - obj.ping(); - - /* - * Clean up object too. - */ - System.err.println("Deactivate object via method call"); - obj.shutdown(); - - System.err.println("\nsuccess: CreatePrivateActivatable test passed "); - - } catch (Exception e) { - if (e instanceof java.security.PrivilegedActionException) { - e = ((java.security.PrivilegedActionException)e).getException(); - } - TestLibrary.bomb("\nfailure: unexpected exception " + - e.getClass().getName(), e); - - } finally { - ActivationLibrary.rmidCleanup(rmid); - obj = null; - } + /* Cause activation groups to have a security policy that will + * allow security managers to be downloaded and installed + */ + Properties p = new Properties(); + // this test must always set policies/managers in its + // activation groups + p.put("java.security.policy", + TestParams.defaultGroupPolicy); + p.put("java.security.manager", + TestParams.defaultSecurityManager); + + /* + * Activate an object by registering its object + * descriptor and invoking a method on the + * stub returned from the register call. + */ + ActivationGroupDesc groupDesc = + new ActivationGroupDesc(p, null); + ActivationSystem system = ActivationGroup.getSystem(); + ActivationGroupID groupID = system.registerGroup(groupDesc); + + System.err.println("Creating descriptor"); + ActivationDesc desc = + new ActivationDesc(groupID, + "CreatePrivateActivatable$PrivateActivatable", + null, null); + + System.err.println("Registering descriptor"); + obj = (ActivateMe) Activatable.register(desc); + + /* + * Loop a bunch of times to force activator to + * spawn VMs (groups) + */ + System.err.println("Activate object via method call"); + obj.ping(); + + /* + * Clean up object too. + */ + System.err.println("Deactivate object via method call"); + obj.shutdown(); + + System.err.println("\nsuccess: CreatePrivateActivatable test passed "); + + } catch (Exception e) { + if (e instanceof java.security.PrivilegedActionException) { + e = ((java.security.PrivilegedActionException)e).getException(); + } + TestLibrary.bomb("\nfailure: unexpected exception " + + e.getClass().getName(), e); + + } finally { + ActivationLibrary.rmidCleanup(rmid); + obj = null; + } } } diff --git a/jdk/test/java/rmi/activation/ActivateFailedException/activateFails/ActivateFails.java b/jdk/test/java/rmi/activation/ActivateFailedException/activateFails/ActivateFails.java index 49c7fbb3c47..b5aa5360317 100644 --- a/jdk/test/java/rmi/activation/ActivateFailedException/activateFails/ActivateFails.java +++ b/jdk/test/java/rmi/activation/ActivateFailedException/activateFails/ActivateFails.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1998-2001 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -24,10 +24,10 @@ /* @test * @bug 4097135 * @summary Need a specific subtype of RemoteException for activation failure. - * If activation fails to happen during a call to a remote object, - * then the call should end in an ActivateFailedException. In this - * test, the actual "activatable" remote object fails to activate - * since its * "activation" constructor throws an exception. + * If activation fails to happen during a call to a remote object, + * then the call should end in an ActivateFailedException. In this + * test, the actual "activatable" remote object fails to activate + * since its * "activation" constructor throws an exception. * @author Ann Wollrath * * @library ../../../testlibrary @@ -46,128 +46,127 @@ import java.io.*; import java.util.Properties; public class ActivateFails - extends Activatable - implements ActivateMe + extends Activatable + implements ActivateMe { public ActivateFails(ActivationID id, MarshalledObject obj) - throws ActivationException, RemoteException + throws ActivationException, RemoteException { - super(id, 0); + super(id, 0); - boolean refuseToActivate = false; - try { - refuseToActivate = ((Boolean)obj.get()).booleanValue(); - } catch (Exception impossible) { - } - - if (refuseToActivate) - throw new RemoteException("object refuses to activate"); + boolean refuseToActivate = false; + try { + refuseToActivate = ((Boolean)obj.get()).booleanValue(); + } catch (Exception impossible) { + } + + if (refuseToActivate) + throw new RemoteException("object refuses to activate"); } public void ping() {} - + /** * Spawns a thread to deactivate the object. */ public ShutdownThread shutdown() throws Exception { - ShutdownThread shutdownThread = new ShutdownThread(this, getID()); - shutdownThread.start(); - return(shutdownThread); + ShutdownThread shutdownThread = new ShutdownThread(this, getID()); + shutdownThread.start(); + return(shutdownThread); } - - public static void main(String[] args) + + public static void main(String[] args) { - RMID rmid = null; - ActivateMe obj1, obj2; - ShutdownThread shutdownThread; - - System.err.println("\nRegression test for bug 4097135\n"); - try { - TestLibrary.suggestSecurityManager("java.rmi.RMISecurityManager"); + RMID rmid = null; + ActivateMe obj1, obj2; + ShutdownThread shutdownThread; - /* - * First run "rmid" and wait for it to start up. - */ - RMID.removeLog(); - rmid = RMID.createRMID(); - rmid.start(); + System.err.println("\nRegression test for bug 4097135\n"); + try { + TestLibrary.suggestSecurityManager("java.rmi.RMISecurityManager"); - /* Cause activation groups to have a security policy that will - * allow security managers to be downloaded and installed - */ - Properties p = new Properties(); - // this test must always set policies/managers in its - // activation groups - p.put("java.security.policy", - TestParams.defaultGroupPolicy); - p.put("java.security.manager", - TestParams.defaultSecurityManager); + /* + * First run "rmid" and wait for it to start up. + */ + RMID.removeLog(); + rmid = RMID.createRMID(); + rmid.start(); - /* - * Create activation descriptor... - */ - System.err.println("creating activation descriptor..."); - ActivationGroupDesc groupDesc = - new ActivationGroupDesc(p, null); - ActivationGroupID groupID = - ActivationGroup.getSystem().registerGroup(groupDesc); - - ActivationDesc desc1 = - new ActivationDesc(groupID, "ActivateFails", - null, - new MarshalledObject(new Boolean(true))); - - ActivationDesc desc2 = - new ActivationDesc(groupID, "ActivateFails", - null, - new MarshalledObject(new Boolean(false))); - /* - * Register activation descriptor and make a call on - * the stub. Activation should fail with an - * ActivateFailedException. If not, report an - * error as a RuntimeException - */ + /* Cause activation groups to have a security policy that will + * allow security managers to be downloaded and installed + */ + Properties p = new Properties(); + // this test must always set policies/managers in its + // activation groups + p.put("java.security.policy", + TestParams.defaultGroupPolicy); + p.put("java.security.manager", + TestParams.defaultSecurityManager); - System.err.println("registering activation descriptor..."); - obj1 = (ActivateMe)Activatable.register(desc1); - obj2 = (ActivateMe)Activatable.register(desc2); + /* + * Create activation descriptor... + */ + System.err.println("creating activation descriptor..."); + ActivationGroupDesc groupDesc = + new ActivationGroupDesc(p, null); + ActivationGroupID groupID = + ActivationGroup.getSystem().registerGroup(groupDesc); - System.err.println("invoking method on activatable object..."); - try { - obj1.ping(); - - } catch (ActivateFailedException e) { + ActivationDesc desc1 = + new ActivationDesc(groupID, "ActivateFails", + null, + new MarshalledObject(new Boolean(true))); - /* - * This is what is expected so exit with status 0 - */ - System.err.println("\nsuccess: ActivateFailedException " + - "generated"); - e.getMessage(); - } + ActivationDesc desc2 = + new ActivationDesc(groupID, "ActivateFails", + null, + new MarshalledObject(new Boolean(false))); + /* + * Register activation descriptor and make a call on + * the stub. Activation should fail with an + * ActivateFailedException. If not, report an + * error as a RuntimeException + */ - obj2.ping(); - shutdownThread = obj2.shutdown(); + System.err.println("registering activation descriptor..."); + obj1 = (ActivateMe)Activatable.register(desc1); + obj2 = (ActivateMe)Activatable.register(desc2); - // wait for shutdown to work - Thread.sleep(2000); + System.err.println("invoking method on activatable object..."); + try { + obj1.ping(); - shutdownThread = null; - - } catch (Exception e) { - /* - * Test failed; unexpected exception generated. - */ - TestLibrary.bomb("\nfailure: unexpected exception " + - e.getClass().getName() + ": " + e.getMessage(), e); - - } finally { - obj1 = obj2 = null; - ActivationLibrary.rmidCleanup(rmid); - } + } catch (ActivateFailedException e) { + + /* + * This is what is expected so exit with status 0 + */ + System.err.println("\nsuccess: ActivateFailedException " + + "generated"); + e.getMessage(); + } + + obj2.ping(); + shutdownThread = obj2.shutdown(); + + // wait for shutdown to work + Thread.sleep(2000); + + shutdownThread = null; + + } catch (Exception e) { + /* + * Test failed; unexpected exception generated. + */ + TestLibrary.bomb("\nfailure: unexpected exception " + + e.getClass().getName() + ": " + e.getMessage(), e); + + } finally { + obj1 = obj2 = null; + ActivationLibrary.rmidCleanup(rmid); + } } } - diff --git a/jdk/test/java/rmi/activation/ActivateFailedException/activateFails/ActivateFails_Stub.java b/jdk/test/java/rmi/activation/ActivateFailedException/activateFails/ActivateFails_Stub.java index 08bded1f71b..5c1047f7860 100644 --- a/jdk/test/java/rmi/activation/ActivateFailedException/activateFails/ActivateFails_Stub.java +++ b/jdk/test/java/rmi/activation/ActivateFailedException/activateFails/ActivateFails_Stub.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1998-2001 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -29,88 +29,88 @@ public final class ActivateFails_Stub implements ActivateMe, java.rmi.Remote { private static final java.rmi.server.Operation[] operations = { - new java.rmi.server.Operation("void ping()"), - new java.rmi.server.Operation("ShutdownThread shutdown()") + new java.rmi.server.Operation("void ping()"), + new java.rmi.server.Operation("ShutdownThread shutdown()") }; - + private static final long interfaceHash = -6632667923281093978L; - + private static final long serialVersionUID = 2; - + private static boolean useNewInvoke; private static java.lang.reflect.Method $method_ping_0; private static java.lang.reflect.Method $method_shutdown_1; - + static { - try { - java.rmi.server.RemoteRef.class.getMethod("invoke", - new java.lang.Class[] { - java.rmi.Remote.class, - java.lang.reflect.Method.class, - java.lang.Object[].class, - long.class - }); - useNewInvoke = true; - $method_ping_0 = ActivateMe.class.getMethod("ping", new java.lang.Class[] {}); - $method_shutdown_1 = ActivateMe.class.getMethod("shutdown", new java.lang.Class[] {}); - } catch (java.lang.NoSuchMethodException e) { - useNewInvoke = false; - } + try { + java.rmi.server.RemoteRef.class.getMethod("invoke", + new java.lang.Class[] { + java.rmi.Remote.class, + java.lang.reflect.Method.class, + java.lang.Object[].class, + long.class + }); + useNewInvoke = true; + $method_ping_0 = ActivateMe.class.getMethod("ping", new java.lang.Class[] {}); + $method_shutdown_1 = ActivateMe.class.getMethod("shutdown", new java.lang.Class[] {}); + } catch (java.lang.NoSuchMethodException e) { + useNewInvoke = false; + } } - + // constructors public ActivateFails_Stub() { - super(); + super(); } public ActivateFails_Stub(java.rmi.server.RemoteRef ref) { - super(ref); + super(ref); } - + // methods from remote interfaces - + // implementation of ping() public void ping() - throws java.rmi.RemoteException + throws java.rmi.RemoteException { - try { - if (useNewInvoke) { - ref.invoke(this, $method_ping_0, null, 5866401369815527589L); - } else { - java.rmi.server.RemoteCall call = ref.newCall((java.rmi.server.RemoteObject) this, operations, 0, interfaceHash); - ref.invoke(call); - ref.done(call); - } - } catch (java.lang.RuntimeException e) { - throw e; - } catch (java.rmi.RemoteException e) { - throw e; - } catch (java.lang.Exception e) { - throw new java.rmi.UnexpectedException("undeclared checked exception", e); - } + try { + if (useNewInvoke) { + ref.invoke(this, $method_ping_0, null, 5866401369815527589L); + } else { + java.rmi.server.RemoteCall call = ref.newCall((java.rmi.server.RemoteObject) this, operations, 0, interfaceHash); + ref.invoke(call); + ref.done(call); + } + } catch (java.lang.RuntimeException e) { + throw e; + } catch (java.rmi.RemoteException e) { + throw e; + } catch (java.lang.Exception e) { + throw new java.rmi.UnexpectedException("undeclared checked exception", e); + } } - + // implementation of shutdown() public ShutdownThread shutdown() - throws java.lang.Exception + throws java.lang.Exception { - if (useNewInvoke) { - Object $result = ref.invoke(this, $method_shutdown_1, null, -3616843253114182719L); - return ((ShutdownThread) $result); - } else { - java.rmi.server.RemoteCall call = ref.newCall((java.rmi.server.RemoteObject) this, operations, 1, interfaceHash); - ref.invoke(call); - ShutdownThread $result; - try { - java.io.ObjectInput in = call.getInputStream(); - $result = (ShutdownThread) in.readObject(); - } catch (java.io.IOException e) { - throw new java.rmi.UnmarshalException("error unmarshalling return", e); - } catch (java.lang.ClassNotFoundException e) { - throw new java.rmi.UnmarshalException("error unmarshalling return", e); - } finally { - ref.done(call); - } - return $result; - } + if (useNewInvoke) { + Object $result = ref.invoke(this, $method_shutdown_1, null, -3616843253114182719L); + return ((ShutdownThread) $result); + } else { + java.rmi.server.RemoteCall call = ref.newCall((java.rmi.server.RemoteObject) this, operations, 1, interfaceHash); + ref.invoke(call); + ShutdownThread $result; + try { + java.io.ObjectInput in = call.getInputStream(); + $result = (ShutdownThread) in.readObject(); + } catch (java.io.IOException e) { + throw new java.rmi.UnmarshalException("error unmarshalling return", e); + } catch (java.lang.ClassNotFoundException e) { + throw new java.rmi.UnmarshalException("error unmarshalling return", e); + } finally { + ref.done(call); + } + return $result; + } } } diff --git a/jdk/test/java/rmi/activation/ActivateFailedException/activateFails/ActivateMe.java b/jdk/test/java/rmi/activation/ActivateFailedException/activateFails/ActivateMe.java index fb29e0925b7..92d7df3faf6 100644 --- a/jdk/test/java/rmi/activation/ActivateFailedException/activateFails/ActivateMe.java +++ b/jdk/test/java/rmi/activation/ActivateFailedException/activateFails/ActivateMe.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1999-2001 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * diff --git a/jdk/test/java/rmi/activation/ActivateFailedException/activateFails/ShutdownThread.java b/jdk/test/java/rmi/activation/ActivateFailedException/activateFails/ShutdownThread.java index 3636c2877bc..a902289234b 100644 --- a/jdk/test/java/rmi/activation/ActivateFailedException/activateFails/ShutdownThread.java +++ b/jdk/test/java/rmi/activation/ActivateFailedException/activateFails/ShutdownThread.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -31,21 +31,20 @@ public class ShutdownThread extends Thread implements Serializable { ActivationID activationID = null; public ShutdownThread(Remote remoteObject, ActivationID activationID) { - remoteObject = remoteObject; - activationID = activationID; + remoteObject = remoteObject; + activationID = activationID; } public void run() { - try { + try { - Activatable.unexportObject(remoteObject, true); - Activatable.inactive(activationID); + Activatable.unexportObject(remoteObject, true); + Activatable.inactive(activationID); - } catch (Exception e) { - } + } catch (Exception e) { + } } } - diff --git a/jdk/test/java/rmi/activation/ActivationGroup/downloadActivationGroup/DownloadActivationGroup.java b/jdk/test/java/rmi/activation/ActivationGroup/downloadActivationGroup/DownloadActivationGroup.java index df4121f819f..a60a6b2f99e 100644 --- a/jdk/test/java/rmi/activation/ActivationGroup/downloadActivationGroup/DownloadActivationGroup.java +++ b/jdk/test/java/rmi/activation/ActivationGroup/downloadActivationGroup/DownloadActivationGroup.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -23,7 +23,7 @@ /* * @test - * @bug 4510355 + * @bug 4510355 * @summary ActivationGroup implementations cannot be downloaded by default; * Creates a custom activation group without setting a security manager * in activation group's descriptor. The custom activation group @@ -49,28 +49,28 @@ import java.util.Vector; import java.util.Properties; public class DownloadActivationGroup - implements Ping, Runnable + implements Ping, Runnable { private ActivationID id; public DownloadActivationGroup(ActivationID id, MarshalledObject mobj) - throws ActivationException, RemoteException + throws ActivationException, RemoteException { - this.id = id; - Activatable.exportObject(this, id, 0); - System.err.println("object activated in group"); + this.id = id; + Activatable.exportObject(this, id, 0); + System.err.println("object activated in group"); } public DownloadActivationGroup() throws RemoteException { - UnicastRemoteObject.exportObject(this, 0); + UnicastRemoteObject.exportObject(this, 0); } /** * Used to activate object. */ public void ping() { - System.err.println("received ping"); + System.err.println("received ping"); } /** @@ -79,87 +79,87 @@ public class DownloadActivationGroup */ public void shutdown() throws Exception { - (new Thread(this,"DownloadActivationGroup")).start(); + (new Thread(this,"DownloadActivationGroup")).start(); } /** * Thread to deactivate object. */ public void run() { - ActivationLibrary.deactivate(this, getID()); + ActivationLibrary.deactivate(this, getID()); } - + public ActivationID getID() { - return id; + return id; } public static void main(String[] args) { - RMID rmid = null; - - System.out.println("\nRegression test for bug 4510355\n"); - - try { - TestLibrary.suggestSecurityManager("java.lang.SecurityManager"); + RMID rmid = null; - /* - * Install group class file in codebase. - */ - System.err.println("install class file in codebase"); - URL groupURL = TestLibrary.installClassInCodebase( - "MyActivationGroupImpl", "group"); - System.err.println("class file installed"); + System.out.println("\nRegression test for bug 4510355\n"); - /* - * Start rmid. - */ - RMID.removeLog(); - rmid = RMID.createRMID(); - String execPolicyOption = "-Dsun.rmi.activation.execPolicy=none"; - rmid.addOptions(new String[] { execPolicyOption }); - rmid.start(); + try { + TestLibrary.suggestSecurityManager("java.lang.SecurityManager"); - /* - * Create and register descriptors for custom group and an - * activatable object in that group. - */ - System.err.println("register group"); - - Properties p = new Properties(); - p.put("java.security.policy", TestParams.defaultGroupPolicy); - - ActivationGroupDesc groupDesc = - new ActivationGroupDesc("MyActivationGroupImpl", - groupURL.toExternalForm(), - null, p, null); - ActivationGroupID groupID = - ActivationGroup.getSystem().registerGroup(groupDesc); - - - System.err.println("register activatable object"); - ActivationDesc desc = - new ActivationDesc(groupID, "DownloadActivationGroup", - null, null); - Ping obj = (Ping) Activatable.register(desc); + /* + * Install group class file in codebase. + */ + System.err.println("install class file in codebase"); + URL groupURL = TestLibrary.installClassInCodebase( + "MyActivationGroupImpl", "group"); + System.err.println("class file installed"); - /* - * Start group (by calling ping). - */ - System.err.println( - "ping object (forces download of group's class)"); - obj.ping(); - System.err.println( - "TEST PASSED: group's class downloaded successfully"); - System.err.println("shutdown object"); - obj.shutdown(); - System.err.println("TEST PASSED"); + /* + * Start rmid. + */ + RMID.removeLog(); + rmid = RMID.createRMID(); + String execPolicyOption = "-Dsun.rmi.activation.execPolicy=none"; + rmid.addOptions(new String[] { execPolicyOption }); + rmid.start(); - } catch (Exception e) { - TestLibrary.bomb(e); - } finally { - ActivationLibrary.rmidCleanup(rmid); - } + /* + * Create and register descriptors for custom group and an + * activatable object in that group. + */ + System.err.println("register group"); + + Properties p = new Properties(); + p.put("java.security.policy", TestParams.defaultGroupPolicy); + + ActivationGroupDesc groupDesc = + new ActivationGroupDesc("MyActivationGroupImpl", + groupURL.toExternalForm(), + null, p, null); + ActivationGroupID groupID = + ActivationGroup.getSystem().registerGroup(groupDesc); + + + System.err.println("register activatable object"); + ActivationDesc desc = + new ActivationDesc(groupID, "DownloadActivationGroup", + null, null); + Ping obj = (Ping) Activatable.register(desc); + + /* + * Start group (by calling ping). + */ + System.err.println( + "ping object (forces download of group's class)"); + obj.ping(); + System.err.println( + "TEST PASSED: group's class downloaded successfully"); + System.err.println("shutdown object"); + obj.shutdown(); + System.err.println("TEST PASSED"); + + } catch (Exception e) { + TestLibrary.bomb(e); + } finally { + ActivationLibrary.rmidCleanup(rmid); + } } } diff --git a/jdk/test/java/rmi/activation/ActivationGroup/downloadActivationGroup/DownloadActivationGroup_Stub.java b/jdk/test/java/rmi/activation/ActivationGroup/downloadActivationGroup/DownloadActivationGroup_Stub.java index 0d366dee98a..0ce899c6f08 100644 --- a/jdk/test/java/rmi/activation/ActivationGroup/downloadActivationGroup/DownloadActivationGroup_Stub.java +++ b/jdk/test/java/rmi/activation/ActivationGroup/downloadActivationGroup/DownloadActivationGroup_Stub.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -29,46 +29,46 @@ public final class DownloadActivationGroup_Stub implements Ping { private static final long serialVersionUID = 2; - + private static java.lang.reflect.Method $method_ping_0; private static java.lang.reflect.Method $method_shutdown_1; - + static { - try { - $method_ping_0 = Ping.class.getMethod("ping", new java.lang.Class[] {}); - $method_shutdown_1 = Ping.class.getMethod("shutdown", new java.lang.Class[] {}); - } catch (java.lang.NoSuchMethodException e) { - throw new java.lang.NoSuchMethodError( - "stub class initialization failed"); - } + try { + $method_ping_0 = Ping.class.getMethod("ping", new java.lang.Class[] {}); + $method_shutdown_1 = Ping.class.getMethod("shutdown", new java.lang.Class[] {}); + } catch (java.lang.NoSuchMethodException e) { + throw new java.lang.NoSuchMethodError( + "stub class initialization failed"); + } } - + // constructors public DownloadActivationGroup_Stub(java.rmi.server.RemoteRef ref) { - super(ref); + super(ref); } - + // methods from remote interfaces - + // implementation of ping() public void ping() - throws java.rmi.RemoteException + throws java.rmi.RemoteException { - try { - ref.invoke(this, $method_ping_0, null, 5866401369815527589L); - } catch (java.lang.RuntimeException e) { - throw e; - } catch (java.rmi.RemoteException e) { - throw e; - } catch (java.lang.Exception e) { - throw new java.rmi.UnexpectedException("undeclared checked exception", e); - } + try { + ref.invoke(this, $method_ping_0, null, 5866401369815527589L); + } catch (java.lang.RuntimeException e) { + throw e; + } catch (java.rmi.RemoteException e) { + throw e; + } catch (java.lang.Exception e) { + throw new java.rmi.UnexpectedException("undeclared checked exception", e); + } } - + // implementation of shutdown() public void shutdown() - throws java.lang.Exception + throws java.lang.Exception { - ref.invoke(this, $method_shutdown_1, null, -7207851917985848402L); + ref.invoke(this, $method_shutdown_1, null, -7207851917985848402L); } } diff --git a/jdk/test/java/rmi/activation/ActivationGroup/downloadActivationGroup/MyActivationGroupImpl.java b/jdk/test/java/rmi/activation/ActivationGroup/downloadActivationGroup/MyActivationGroupImpl.java index cc43f4f2ee1..f4392af2fcf 100644 --- a/jdk/test/java/rmi/activation/ActivationGroup/downloadActivationGroup/MyActivationGroupImpl.java +++ b/jdk/test/java/rmi/activation/ActivationGroup/downloadActivationGroup/MyActivationGroupImpl.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -27,11 +27,11 @@ import java.rmi.activation.*; public class MyActivationGroupImpl extends ActivationGroupImpl { - + public MyActivationGroupImpl(ActivationGroupID id, MarshalledObject mobj) - throws RemoteException, ActivationException + throws RemoteException, ActivationException { - super(id, mobj); - System.err.println("custom group implementation created"); + super(id, mobj); + System.err.println("custom group implementation created"); } } diff --git a/jdk/test/java/rmi/activation/ActivationGroupDesc/checkDefaultGroupName/CheckDefaultGroupName.java b/jdk/test/java/rmi/activation/ActivationGroupDesc/checkDefaultGroupName/CheckDefaultGroupName.java index 040253d1383..eed889c0e38 100644 --- a/jdk/test/java/rmi/activation/ActivationGroupDesc/checkDefaultGroupName/CheckDefaultGroupName.java +++ b/jdk/test/java/rmi/activation/ActivationGroupDesc/checkDefaultGroupName/CheckDefaultGroupName.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -42,19 +42,19 @@ import java.rmi.activation.*; */ public class CheckDefaultGroupName { public static void main(String[] args) { - System.out.println("\n\nRegression test for, 4252236\n\n"); + System.out.println("\n\nRegression test for, 4252236\n\n"); - ActivationGroupDesc groupDesc = - new ActivationGroupDesc(null, null); + ActivationGroupDesc groupDesc = + new ActivationGroupDesc(null, null); - String className = groupDesc.getClassName(); - if (className != null) { - TestLibrary.bomb("ActivationGroupDesc had incorrect default" + - " group implementation class name: " + className); - } else { - System.err.println("test passed, had correct default group" + - " implementation class name: " + className + - "\n\n"); - } + String className = groupDesc.getClassName(); + if (className != null) { + TestLibrary.bomb("ActivationGroupDesc had incorrect default" + + " group implementation class name: " + className); + } else { + System.err.println("test passed, had correct default group" + + " implementation class name: " + className + + "\n\n"); + } } } diff --git a/jdk/test/java/rmi/activation/ActivationSystem/activeGroup/IdempotentActiveGroup.java b/jdk/test/java/rmi/activation/ActivationSystem/activeGroup/IdempotentActiveGroup.java index c9e901b8779..589b93bb6c0 100644 --- a/jdk/test/java/rmi/activation/ActivationSystem/activeGroup/IdempotentActiveGroup.java +++ b/jdk/test/java/rmi/activation/ActivationSystem/activeGroup/IdempotentActiveGroup.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 2003 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -49,81 +49,81 @@ import java.rmi.activation.ActivationSystem; import java.rmi.server.UnicastRemoteObject; public class IdempotentActiveGroup { - + public static void main(String[] args) { - System.err.println("\nRegression test for bug 4720528\n"); - - TestLibrary.suggestSecurityManager("java.lang.SecurityManager"); - RMID rmid = null; - ActivationInstantiator inst1 = null; - ActivationInstantiator inst2 = null; - - try { - RMID.removeLog(); - rmid = RMID.createRMID(); - rmid.start(); + System.err.println("\nRegression test for bug 4720528\n"); - System.err.println("Create group descriptor"); - ActivationGroupDesc groupDesc = - new ActivationGroupDesc(null, null); - ActivationSystem system = ActivationGroup.getSystem(); - System.err.println("Register group descriptor"); - ActivationGroupID groupID = system.registerGroup(groupDesc); - inst1 = new FakeInstantiator(); - inst2 = new FakeInstantiator(); - - System.err.println("Invoke activeGroup with inst1"); - system.activeGroup(groupID, inst1, 0); + TestLibrary.suggestSecurityManager("java.lang.SecurityManager"); + RMID rmid = null; + ActivationInstantiator inst1 = null; + ActivationInstantiator inst2 = null; - try { - System.err.println("Invoke activeGroup with inst2"); - system.activeGroup(groupID, inst2, 0); - throw new RuntimeException( - "TEST FAILED: activeGroup with unequal groups succeeded!"); - } catch (ActivationException expected) { - System.err.println("Caught expected ActivationException"); - System.err.println("Test 1 (of 2) passed"); - } + try { + RMID.removeLog(); + rmid = RMID.createRMID(); + rmid.start(); - try { - System.err.println("Invoke activeGroup with inst1"); - system.activeGroup(groupID, inst1, 0); - System.err.println("activeGroup call succeeded"); - System.err.println("Test 2 (of 2) passed"); - } catch (ActivationException unexpected) { - throw new RuntimeException( - "TEST FAILED: activeGroup with equal groups failed!", - unexpected); - } - - } catch (Exception e) { - TestLibrary.bomb("test failed", e); - } finally { - try { - if (inst1 != null) { - UnicastRemoteObject.unexportObject(inst1, true); - } - if (inst2 != null) { - UnicastRemoteObject.unexportObject(inst2, true); - } - } catch (NoSuchObjectException unexpected) { - throw new AssertionError(unexpected); - } - ActivationLibrary.rmidCleanup(rmid); - } + System.err.println("Create group descriptor"); + ActivationGroupDesc groupDesc = + new ActivationGroupDesc(null, null); + ActivationSystem system = ActivationGroup.getSystem(); + System.err.println("Register group descriptor"); + ActivationGroupID groupID = system.registerGroup(groupDesc); + inst1 = new FakeInstantiator(); + inst2 = new FakeInstantiator(); + + System.err.println("Invoke activeGroup with inst1"); + system.activeGroup(groupID, inst1, 0); + + try { + System.err.println("Invoke activeGroup with inst2"); + system.activeGroup(groupID, inst2, 0); + throw new RuntimeException( + "TEST FAILED: activeGroup with unequal groups succeeded!"); + } catch (ActivationException expected) { + System.err.println("Caught expected ActivationException"); + System.err.println("Test 1 (of 2) passed"); + } + + try { + System.err.println("Invoke activeGroup with inst1"); + system.activeGroup(groupID, inst1, 0); + System.err.println("activeGroup call succeeded"); + System.err.println("Test 2 (of 2) passed"); + } catch (ActivationException unexpected) { + throw new RuntimeException( + "TEST FAILED: activeGroup with equal groups failed!", + unexpected); + } + + } catch (Exception e) { + TestLibrary.bomb("test failed", e); + } finally { + try { + if (inst1 != null) { + UnicastRemoteObject.unexportObject(inst1, true); + } + if (inst2 != null) { + UnicastRemoteObject.unexportObject(inst2, true); + } + } catch (NoSuchObjectException unexpected) { + throw new AssertionError(unexpected); + } + ActivationLibrary.rmidCleanup(rmid); + } } private static class FakeInstantiator - extends UnicastRemoteObject - implements ActivationInstantiator + extends UnicastRemoteObject + implements ActivationInstantiator { - FakeInstantiator() throws RemoteException {} + FakeInstantiator() throws RemoteException {} - public MarshalledObject newInstance(ActivationID id, - ActivationDesc desc) - { - throw new AssertionError(); - } + public MarshalledObject newInstance(ActivationID id, + ActivationDesc desc) + { + throw new AssertionError(); + } } } diff --git a/jdk/test/java/rmi/activation/ActivationSystem/modifyDescriptor/ActivateMe.java b/jdk/test/java/rmi/activation/ActivationSystem/modifyDescriptor/ActivateMe.java index c59f34a8451..c6a55411edd 100644 --- a/jdk/test/java/rmi/activation/ActivationSystem/modifyDescriptor/ActivateMe.java +++ b/jdk/test/java/rmi/activation/ActivationSystem/modifyDescriptor/ActivateMe.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * diff --git a/jdk/test/java/rmi/activation/ActivationSystem/modifyDescriptor/ModifyDescriptor.java b/jdk/test/java/rmi/activation/ActivationSystem/modifyDescriptor/ModifyDescriptor.java index b166890cbc2..3f9ef2b2fe6 100644 --- a/jdk/test/java/rmi/activation/ActivationSystem/modifyDescriptor/ModifyDescriptor.java +++ b/jdk/test/java/rmi/activation/ActivationSystem/modifyDescriptor/ModifyDescriptor.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1998-1999 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -25,7 +25,7 @@ * @bug 4127754 * * @summary synopsis: need to modify registered ActivationDesc and - * ActivationGroupDesc + * ActivationGroupDesc * @author Ann Wollrath * * @library ../../../testlibrary @@ -43,7 +43,7 @@ import java.rmi.registry.*; import java.util.*; public class ModifyDescriptor - implements ActivateMe, Runnable + implements ActivateMe, Runnable { private ActivationID id; @@ -54,28 +54,28 @@ public class ModifyDescriptor public ModifyDescriptor(ActivationID id, MarshalledObject mobj) - throws ActivationException, RemoteException + throws ActivationException, RemoteException { - this.id = id; - Activatable.exportObject(this, id, 0); - - try { - message = (String) mobj.get(); - } catch (Exception e) { - System.err.println("unable to get message from marshalled object"); - } + this.id = id; + Activatable.exportObject(this, id, 0); + + try { + message = (String) mobj.get(); + } catch (Exception e) { + System.err.println("unable to get message from marshalled object"); + } } public String getMessage() { - return message; + return message; } public String getProperty(String name) { - return TestLibrary.getProperty(name, null); + return TestLibrary.getProperty(name, null); } public ActivationID getID() { - return id; + return id; } /** @@ -83,7 +83,7 @@ public class ModifyDescriptor */ public void shutdown() throws Exception { - (new Thread(this,"ModifyDescriptor")).start(); + (new Thread(this,"ModifyDescriptor")).start(); } /** @@ -93,165 +93,165 @@ public class ModifyDescriptor * unexport the object forcibly. */ public void run() { - ActivationLibrary.deactivate(this, getID()); + ActivationLibrary.deactivate(this, getID()); } - + public static void main(String[] args) { - System.out.println("\nRegression test for bug 4127754\n"); - - TestLibrary.suggestSecurityManager("java.rmi.RMISecurityManager"); + System.out.println("\nRegression test for bug 4127754\n"); - RMID rmid = null; - - try { - RMID.removeLog(); - rmid = RMID.createRMID(); - rmid.start(); + TestLibrary.suggestSecurityManager("java.rmi.RMISecurityManager"); - /* - * Create and register a group and activatable object - */ + RMID rmid = null; - System.err.println("Creating group descriptor"); - Properties props = new Properties(); - props.put("java.security.policy", - TestParams.defaultGroupPolicy); - props.put("java.security.manager", - TestParams.defaultSecurityManager); - props.put("test.message", MESSAGE1); - ActivationGroupDesc initialGroupDesc = - new ActivationGroupDesc(props, null); - System.err.println("Registering group"); - ActivationSystem system = ActivationGroup.getSystem(); - ActivationGroupID groupID = system.registerGroup(initialGroupDesc); - - System.err.println("Creating descriptor"); - ActivationDesc initialDesc = - new ActivationDesc(groupID, "ModifyDescriptor", null, - new MarshalledObject(MESSAGE1), false); - - System.err.println("Registering descriptor"); - ActivateMe obj = (ActivateMe) Activatable.register(initialDesc); + try { + RMID.removeLog(); + rmid = RMID.createRMID(); + rmid.start(); - /* - * Ping object and verify that MarshalledObject is okay. - */ - System.err.println("Ping object"); - String message1 = obj.getMessage(); - System.err.println("message = " + message1); + /* + * Create and register a group and activatable object + */ - if (message1.equals(MESSAGE1)) { - System.err.println("Test1a passed: initial MarshalledObject " + - "correct"); - } else { - TestLibrary.bomb("Test1 failed: unexpected MarshalledObject passed to " + - "constructor", null); - } + System.err.println("Creating group descriptor"); + Properties props = new Properties(); + props.put("java.security.policy", + TestParams.defaultGroupPolicy); + props.put("java.security.manager", + TestParams.defaultSecurityManager); + props.put("test.message", MESSAGE1); + ActivationGroupDesc initialGroupDesc = + new ActivationGroupDesc(props, null); + System.err.println("Registering group"); + ActivationSystem system = ActivationGroup.getSystem(); + ActivationGroupID groupID = system.registerGroup(initialGroupDesc); - /* - * Get property from remote group and make sure it's okay - */ - message1 = obj.getProperty("test.message"); - if (message1.equals(MESSAGE1)) { - System.err.println("Test1b passed: initial group property " + - "correct"); - } else { - TestLibrary.bomb("Test1 failed: unexpected property passed to " + - "group", null); - } + System.err.println("Creating descriptor"); + ActivationDesc initialDesc = + new ActivationDesc(groupID, "ModifyDescriptor", null, + new MarshalledObject(MESSAGE1), false); - /* - * Update activation descriptor for object and group - */ - System.err.println("Update activation descriptor"); - ActivationDesc newDesc = - new ActivationDesc(groupID, "ModifyDescriptor", null, - new MarshalledObject(MESSAGE2), false); - ActivationID id = obj.getID(); - ActivationDesc oldDesc = system.setActivationDesc(id, newDesc); + System.err.println("Registering descriptor"); + ActivateMe obj = (ActivateMe) Activatable.register(initialDesc); - if (oldDesc.equals(initialDesc)) { - System.err.println("Test2a passed: desc returned from " + - "setActivationDesc is okay"); - } else { - TestLibrary.bomb("Test2a failed: desc returned from setActivationDesc " + - "is not the initial descriptor!", null); - } + /* + * Ping object and verify that MarshalledObject is okay. + */ + System.err.println("Ping object"); + String message1 = obj.getMessage(); + System.err.println("message = " + message1); + + if (message1.equals(MESSAGE1)) { + System.err.println("Test1a passed: initial MarshalledObject " + + "correct"); + } else { + TestLibrary.bomb("Test1 failed: unexpected MarshalledObject passed to " + + "constructor", null); + } + + /* + * Get property from remote group and make sure it's okay + */ + message1 = obj.getProperty("test.message"); + if (message1.equals(MESSAGE1)) { + System.err.println("Test1b passed: initial group property " + + "correct"); + } else { + TestLibrary.bomb("Test1 failed: unexpected property passed to " + + "group", null); + } + + /* + * Update activation descriptor for object and group + */ + System.err.println("Update activation descriptor"); + ActivationDesc newDesc = + new ActivationDesc(groupID, "ModifyDescriptor", null, + new MarshalledObject(MESSAGE2), false); + ActivationID id = obj.getID(); + ActivationDesc oldDesc = system.setActivationDesc(id, newDesc); + + if (oldDesc.equals(initialDesc)) { + System.err.println("Test2a passed: desc returned from " + + "setActivationDesc is okay"); + } else { + TestLibrary.bomb("Test2a failed: desc returned from setActivationDesc " + + "is not the initial descriptor!", null); + } - Properties props2 = new Properties(); - props2.put("test.message", MESSAGE2); - props2.put("java.security.policy", - TestParams.defaultGroupPolicy); - props2.put("java.security.manager", - TestParams.defaultSecurityManager); - ActivationGroupDesc newGroupDesc = - new ActivationGroupDesc(props2, null); + Properties props2 = new Properties(); + props2.put("test.message", MESSAGE2); + props2.put("java.security.policy", + TestParams.defaultGroupPolicy); + props2.put("java.security.manager", + TestParams.defaultSecurityManager); + ActivationGroupDesc newGroupDesc = + new ActivationGroupDesc(props2, null); - ActivationGroupDesc oldGroupDesc = - system.setActivationGroupDesc(groupID, newGroupDesc); + ActivationGroupDesc oldGroupDesc = + system.setActivationGroupDesc(groupID, newGroupDesc); - if (oldGroupDesc.equals(initialGroupDesc)) { - System.err.println("Test2b passed: group desc returned from " + - "setActivationGroupDesc is okay"); - } else { - TestLibrary.bomb("Test2b failed: group desc returned from " + - "setActivationGroupDesc is not the initial descriptor!", - null); - } - - /* - * Restart rmid; and ping object to make sure that it has - * new message. - */ - rmid.restart(); + if (oldGroupDesc.equals(initialGroupDesc)) { + System.err.println("Test2b passed: group desc returned from " + + "setActivationGroupDesc is okay"); + } else { + TestLibrary.bomb("Test2b failed: group desc returned from " + + "setActivationGroupDesc is not the initial descriptor!", + null); + } - System.err.println("Ping object after restart"); - String message2 = obj.getMessage(); + /* + * Restart rmid; and ping object to make sure that it has + * new message. + */ + rmid.restart(); - if (message2.equals(MESSAGE2)) { - System.err.println("Test3a passed: setActivationDesc takes " + - "effect after a restart"); - } else { - TestLibrary.bomb("Test3a failed: setActivationDesc did not take effect " + - "after a restart", null); - } + System.err.println("Ping object after restart"); + String message2 = obj.getMessage(); - message2 = obj.getProperty("test.message"); - - if (message2.equals(MESSAGE2)) { - System.err.println("Test3b passed: setActivationGroupDesc " + - "takes effect after a restart"); - } else { - TestLibrary.bomb("Test3b failed: setActivationGroupDesc did not take " + - "effect after a restart", null); - } + if (message2.equals(MESSAGE2)) { + System.err.println("Test3a passed: setActivationDesc takes " + + "effect after a restart"); + } else { + TestLibrary.bomb("Test3a failed: setActivationDesc did not take effect " + + "after a restart", null); + } - System.err.println("Get activation descriptor"); - ActivationDesc latestDesc = system.getActivationDesc(id); + message2 = obj.getProperty("test.message"); - if (latestDesc.equals(newDesc)) { - System.err.println("Test4a passed: desc is same as latest"); - } else { - TestLibrary.bomb("Test4a failed: there is no way this would happen", null); - } + if (message2.equals(MESSAGE2)) { + System.err.println("Test3b passed: setActivationGroupDesc " + + "takes effect after a restart"); + } else { + TestLibrary.bomb("Test3b failed: setActivationGroupDesc did not take " + + "effect after a restart", null); + } - System.err.println("Get activation group descriptor"); - ActivationGroupDesc latestGroupDesc = - system.getActivationGroupDesc(groupID); + System.err.println("Get activation descriptor"); + ActivationDesc latestDesc = system.getActivationDesc(id); - if (latestGroupDesc.equals(newGroupDesc)) { - System.err.println("Test4b passed: group desc is same as " + - "latest"); - } else { - TestLibrary.bomb("Test4b failed: there is no way this would happen", null); - } - - } catch (Exception e) { - TestLibrary.bomb("test failed", e); - } finally { - ActivationLibrary.rmidCleanup(rmid); - } + if (latestDesc.equals(newDesc)) { + System.err.println("Test4a passed: desc is same as latest"); + } else { + TestLibrary.bomb("Test4a failed: there is no way this would happen", null); + } + + System.err.println("Get activation group descriptor"); + ActivationGroupDesc latestGroupDesc = + system.getActivationGroupDesc(groupID); + + if (latestGroupDesc.equals(newGroupDesc)) { + System.err.println("Test4b passed: group desc is same as " + + "latest"); + } else { + TestLibrary.bomb("Test4b failed: there is no way this would happen", null); + } + + } catch (Exception e) { + TestLibrary.bomb("test failed", e); + } finally { + ActivationLibrary.rmidCleanup(rmid); + } } } diff --git a/jdk/test/java/rmi/activation/ActivationSystem/modifyDescriptor/ModifyDescriptor_Stub.java b/jdk/test/java/rmi/activation/ActivationSystem/modifyDescriptor/ModifyDescriptor_Stub.java index bcf33b65bfb..d7f9080c278 100644 --- a/jdk/test/java/rmi/activation/ActivationSystem/modifyDescriptor/ModifyDescriptor_Stub.java +++ b/jdk/test/java/rmi/activation/ActivationSystem/modifyDescriptor/ModifyDescriptor_Stub.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1998-1999 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -29,166 +29,166 @@ public final class ModifyDescriptor_Stub implements ActivateMe { private static final java.rmi.server.Operation[] operations = { - new java.rmi.server.Operation("java.rmi.activation.ActivationID getID()"), - new java.rmi.server.Operation("java.lang.String getMessage()"), - new java.rmi.server.Operation("java.lang.String getProperty(java.lang.String)"), - new java.rmi.server.Operation("void shutdown()") + new java.rmi.server.Operation("java.rmi.activation.ActivationID getID()"), + new java.rmi.server.Operation("java.lang.String getMessage()"), + new java.rmi.server.Operation("java.lang.String getProperty(java.lang.String)"), + new java.rmi.server.Operation("void shutdown()") }; - + private static final long interfaceHash = 7998207954486691383L; - + private static final long serialVersionUID = 2; - + private static boolean useNewInvoke; private static java.lang.reflect.Method $method_getID_0; private static java.lang.reflect.Method $method_getMessage_1; private static java.lang.reflect.Method $method_getProperty_2; private static java.lang.reflect.Method $method_shutdown_3; - + static { - try { - java.rmi.server.RemoteRef.class.getMethod("invoke", - new java.lang.Class[] { - java.rmi.Remote.class, - java.lang.reflect.Method.class, - java.lang.Object[].class, - long.class - }); - useNewInvoke = true; - $method_getID_0 = ActivateMe.class.getMethod("getID", new java.lang.Class[] {}); - $method_getMessage_1 = ActivateMe.class.getMethod("getMessage", new java.lang.Class[] {}); - $method_getProperty_2 = ActivateMe.class.getMethod("getProperty", new java.lang.Class[] {java.lang.String.class}); - $method_shutdown_3 = ActivateMe.class.getMethod("shutdown", new java.lang.Class[] {}); - } catch (java.lang.NoSuchMethodException e) { - useNewInvoke = false; - } + try { + java.rmi.server.RemoteRef.class.getMethod("invoke", + new java.lang.Class[] { + java.rmi.Remote.class, + java.lang.reflect.Method.class, + java.lang.Object[].class, + long.class + }); + useNewInvoke = true; + $method_getID_0 = ActivateMe.class.getMethod("getID", new java.lang.Class[] {}); + $method_getMessage_1 = ActivateMe.class.getMethod("getMessage", new java.lang.Class[] {}); + $method_getProperty_2 = ActivateMe.class.getMethod("getProperty", new java.lang.Class[] {java.lang.String.class}); + $method_shutdown_3 = ActivateMe.class.getMethod("shutdown", new java.lang.Class[] {}); + } catch (java.lang.NoSuchMethodException e) { + useNewInvoke = false; + } } - + // constructors public ModifyDescriptor_Stub() { - super(); + super(); } public ModifyDescriptor_Stub(java.rmi.server.RemoteRef ref) { - super(ref); + super(ref); } - + // methods from remote interfaces - + // implementation of getID() public java.rmi.activation.ActivationID getID() - throws java.rmi.RemoteException + throws java.rmi.RemoteException { - try { - if (useNewInvoke) { - Object $result = ref.invoke(this, $method_getID_0, null, -7795865521150345044L); - return ((java.rmi.activation.ActivationID) $result); - } else { - java.rmi.server.RemoteCall call = ref.newCall((java.rmi.server.RemoteObject) this, operations, 0, interfaceHash); - ref.invoke(call); - java.rmi.activation.ActivationID $result; - try { - java.io.ObjectInput in = call.getInputStream(); - $result = (java.rmi.activation.ActivationID) in.readObject(); - } catch (java.io.IOException e) { - throw new java.rmi.UnmarshalException("error unmarshalling return", e); - } catch (java.lang.ClassNotFoundException e) { - throw new java.rmi.UnmarshalException("error unmarshalling return", e); - } finally { - ref.done(call); - } - return $result; - } - } catch (java.lang.RuntimeException e) { - throw e; - } catch (java.rmi.RemoteException e) { - throw e; - } catch (java.lang.Exception e) { - throw new java.rmi.UnexpectedException("undeclared checked exception", e); - } + try { + if (useNewInvoke) { + Object $result = ref.invoke(this, $method_getID_0, null, -7795865521150345044L); + return ((java.rmi.activation.ActivationID) $result); + } else { + java.rmi.server.RemoteCall call = ref.newCall((java.rmi.server.RemoteObject) this, operations, 0, interfaceHash); + ref.invoke(call); + java.rmi.activation.ActivationID $result; + try { + java.io.ObjectInput in = call.getInputStream(); + $result = (java.rmi.activation.ActivationID) in.readObject(); + } catch (java.io.IOException e) { + throw new java.rmi.UnmarshalException("error unmarshalling return", e); + } catch (java.lang.ClassNotFoundException e) { + throw new java.rmi.UnmarshalException("error unmarshalling return", e); + } finally { + ref.done(call); + } + return $result; + } + } catch (java.lang.RuntimeException e) { + throw e; + } catch (java.rmi.RemoteException e) { + throw e; + } catch (java.lang.Exception e) { + throw new java.rmi.UnexpectedException("undeclared checked exception", e); + } } - + // implementation of getMessage() public java.lang.String getMessage() - throws java.rmi.RemoteException + throws java.rmi.RemoteException { - try { - if (useNewInvoke) { - Object $result = ref.invoke(this, $method_getMessage_1, null, 5353407034680111516L); - return ((java.lang.String) $result); - } else { - java.rmi.server.RemoteCall call = ref.newCall((java.rmi.server.RemoteObject) this, operations, 1, interfaceHash); - ref.invoke(call); - java.lang.String $result; - try { - java.io.ObjectInput in = call.getInputStream(); - $result = (java.lang.String) in.readObject(); - } catch (java.io.IOException e) { - throw new java.rmi.UnmarshalException("error unmarshalling return", e); - } catch (java.lang.ClassNotFoundException e) { - throw new java.rmi.UnmarshalException("error unmarshalling return", e); - } finally { - ref.done(call); - } - return $result; - } - } catch (java.lang.RuntimeException e) { - throw e; - } catch (java.rmi.RemoteException e) { - throw e; - } catch (java.lang.Exception e) { - throw new java.rmi.UnexpectedException("undeclared checked exception", e); - } + try { + if (useNewInvoke) { + Object $result = ref.invoke(this, $method_getMessage_1, null, 5353407034680111516L); + return ((java.lang.String) $result); + } else { + java.rmi.server.RemoteCall call = ref.newCall((java.rmi.server.RemoteObject) this, operations, 1, interfaceHash); + ref.invoke(call); + java.lang.String $result; + try { + java.io.ObjectInput in = call.getInputStream(); + $result = (java.lang.String) in.readObject(); + } catch (java.io.IOException e) { + throw new java.rmi.UnmarshalException("error unmarshalling return", e); + } catch (java.lang.ClassNotFoundException e) { + throw new java.rmi.UnmarshalException("error unmarshalling return", e); + } finally { + ref.done(call); + } + return $result; + } + } catch (java.lang.RuntimeException e) { + throw e; + } catch (java.rmi.RemoteException e) { + throw e; + } catch (java.lang.Exception e) { + throw new java.rmi.UnexpectedException("undeclared checked exception", e); + } } - + // implementation of getProperty(String) public java.lang.String getProperty(java.lang.String $param_String_1) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { - try { - if (useNewInvoke) { - Object $result = ref.invoke(this, $method_getProperty_2, new java.lang.Object[] {$param_String_1}, 77249282285080913L); - return ((java.lang.String) $result); - } else { - java.rmi.server.RemoteCall call = ref.newCall((java.rmi.server.RemoteObject) this, operations, 2, interfaceHash); - try { - java.io.ObjectOutput out = call.getOutputStream(); - out.writeObject($param_String_1); - } catch (java.io.IOException e) { - throw new java.rmi.MarshalException("error marshalling arguments", e); - } - ref.invoke(call); - java.lang.String $result; - try { - java.io.ObjectInput in = call.getInputStream(); - $result = (java.lang.String) in.readObject(); - } catch (java.io.IOException e) { - throw new java.rmi.UnmarshalException("error unmarshalling return", e); - } catch (java.lang.ClassNotFoundException e) { - throw new java.rmi.UnmarshalException("error unmarshalling return", e); - } finally { - ref.done(call); - } - return $result; - } - } catch (java.lang.RuntimeException e) { - throw e; - } catch (java.rmi.RemoteException e) { - throw e; - } catch (java.lang.Exception e) { - throw new java.rmi.UnexpectedException("undeclared checked exception", e); - } + try { + if (useNewInvoke) { + Object $result = ref.invoke(this, $method_getProperty_2, new java.lang.Object[] {$param_String_1}, 77249282285080913L); + return ((java.lang.String) $result); + } else { + java.rmi.server.RemoteCall call = ref.newCall((java.rmi.server.RemoteObject) this, operations, 2, interfaceHash); + try { + java.io.ObjectOutput out = call.getOutputStream(); + out.writeObject($param_String_1); + } catch (java.io.IOException e) { + throw new java.rmi.MarshalException("error marshalling arguments", e); + } + ref.invoke(call); + java.lang.String $result; + try { + java.io.ObjectInput in = call.getInputStream(); + $result = (java.lang.String) in.readObject(); + } catch (java.io.IOException e) { + throw new java.rmi.UnmarshalException("error unmarshalling return", e); + } catch (java.lang.ClassNotFoundException e) { + throw new java.rmi.UnmarshalException("error unmarshalling return", e); + } finally { + ref.done(call); + } + return $result; + } + } catch (java.lang.RuntimeException e) { + throw e; + } catch (java.rmi.RemoteException e) { + throw e; + } catch (java.lang.Exception e) { + throw new java.rmi.UnexpectedException("undeclared checked exception", e); + } } - + // implementation of shutdown() public void shutdown() - throws java.lang.Exception + throws java.lang.Exception { - if (useNewInvoke) { - ref.invoke(this, $method_shutdown_3, null, -7207851917985848402L); - } else { - java.rmi.server.RemoteCall call = ref.newCall((java.rmi.server.RemoteObject) this, operations, 3, interfaceHash); - ref.invoke(call); - ref.done(call); - } + if (useNewInvoke) { + ref.invoke(this, $method_shutdown_3, null, -7207851917985848402L); + } else { + java.rmi.server.RemoteCall call = ref.newCall((java.rmi.server.RemoteObject) this, operations, 3, interfaceHash); + ref.invoke(call); + ref.done(call); + } } } diff --git a/jdk/test/java/rmi/activation/ActivationSystem/stubClassesPermitted/CanCreateStubs.java b/jdk/test/java/rmi/activation/ActivationSystem/stubClassesPermitted/CanCreateStubs.java index ed12d06ed88..7ee66f59c95 100644 --- a/jdk/test/java/rmi/activation/ActivationSystem/stubClassesPermitted/CanCreateStubs.java +++ b/jdk/test/java/rmi/activation/ActivationSystem/stubClassesPermitted/CanCreateStubs.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -34,4 +34,3 @@ interface CanCreateStubs extends java.rmi.Remote { Object getForbiddenClass() throws Exception; ActivationGroupID returnGroupID() throws RemoteException; } - diff --git a/jdk/test/java/rmi/activation/ActivationSystem/stubClassesPermitted/StubClassesPermitted.java b/jdk/test/java/rmi/activation/ActivationSystem/stubClassesPermitted/StubClassesPermitted.java index ab3f28eaf41..8b47547f8a0 100644 --- a/jdk/test/java/rmi/activation/ActivationSystem/stubClassesPermitted/StubClassesPermitted.java +++ b/jdk/test/java/rmi/activation/ActivationSystem/stubClassesPermitted/StubClassesPermitted.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -20,7 +20,7 @@ * CA 95054 USA or visit www.sun.com if you need additional information or * have any questions. */ - + /* @test * @bug 4179055 * @summary Some java apps need to have access to read "accessClassInPackage.sun.rmi.server" @@ -55,151 +55,151 @@ import java.util.StringTokenizer; * * The test causes the activation system to need to create each of * these classes in turn. The test will fail if the activation system - * does not allow these classes to be created. + * does not allow these classes to be created. */ public class StubClassesPermitted extends Activatable implements Runnable, CanCreateStubs { public static boolean sameGroup = false; - + private static CanCreateStubs canCreateStubs = null; private static Registry registry = null; - public static void main(String args[]) { + public static void main(String args[]) { - sameGroup = true; - - RMID rmid = null; + sameGroup = true; - System.err.println("\nRegression test for bug/rfe 4179055\n"); - - try { - TestLibrary.suggestSecurityManager("java.lang.SecurityManager"); + RMID rmid = null; - registry = java.rmi.registry.LocateRegistry. - createRegistry(TestLibrary.REGISTRY_PORT); + System.err.println("\nRegression test for bug/rfe 4179055\n"); - // must run with java.lang.SecurityManager or the test - // result will be nullified if running with a build where - // 4180392 has not been fixed. - String smClassName = - System.getSecurityManager().getClass().getName(); - if (!smClassName.equals("java.lang.SecurityManager")) { - TestLibrary.bomb("Test must run with java.lang.SecurityManager"); - } + try { + TestLibrary.suggestSecurityManager("java.lang.SecurityManager"); - // start an rmid. - RMID.removeLog(); - rmid = RMID.createRMID(); - rmid.start(); + registry = java.rmi.registry.LocateRegistry. + createRegistry(TestLibrary.REGISTRY_PORT); - //rmid.addOptions(new String[] {"-C-Djava.rmi.server.logCalls=true"}); + // must run with java.lang.SecurityManager or the test + // result will be nullified if running with a build where + // 4180392 has not been fixed. + String smClassName = + System.getSecurityManager().getClass().getName(); + if (!smClassName.equals("java.lang.SecurityManager")) { + TestLibrary.bomb("Test must run with java.lang.SecurityManager"); + } - // Ensure that activation groups run with the correct - // security manager. - // - Properties p = new Properties(); - p.put("java.security.policy", - TestParams.defaultGroupPolicy); - p.put("java.security.manager", - "java.lang.SecurityManager"); + // start an rmid. + RMID.removeLog(); + rmid = RMID.createRMID(); + rmid.start(); - // This action causes the following classes to be created - // in this VM (RMI must permit the creation of these classes): - // - // sun.rmi.server.Activation$ActivationSystemImpl_Stub - // sun.rmi.server.Activation$ActivationMonitorImpl_Stub - // - System.err.println("Create activation group, in a new VM"); - ActivationGroupDesc groupDesc = - new ActivationGroupDesc(p, null); - ActivationSystem system = ActivationGroup.getSystem(); - ActivationGroupID groupID = system.registerGroup(groupDesc); - - System.err.println("register activatable"); - // Fix for: 4271615: make sure activation group runs in a new VM - ActivationDesc desc = new ActivationDesc - (groupID, "StubClassesPermitted", null, null); - canCreateStubs = (CanCreateStubs) Activatable.register(desc); + //rmid.addOptions(new String[] {"-C-Djava.rmi.server.logCalls=true"}); - // ensure registry stub can be passed in a remote call - System.err.println("getting the registry"); - registry = canCreateStubs.getRegistry(); + // Ensure that activation groups run with the correct + // security manager. + // + Properties p = new Properties(); + p.put("java.security.policy", + TestParams.defaultGroupPolicy); + p.put("java.security.manager", + "java.lang.SecurityManager"); - // make sure a client cant load just any sun.* class, just - // as a sanity check, try to create a class we are not - // allowed to access but which was passed in a remote call - try { - System.err.println("accessing forbidden class"); - Object secureRandom = canCreateStubs.getForbiddenClass(); - - TestLibrary.bomb("test allowed to access forbidden class," + - " sun.security.provider.SecureRandom"); - } catch (java.security.AccessControlException e) { + // This action causes the following classes to be created + // in this VM (RMI must permit the creation of these classes): + // + // sun.rmi.server.Activation$ActivationSystemImpl_Stub + // sun.rmi.server.Activation$ActivationMonitorImpl_Stub + // + System.err.println("Create activation group, in a new VM"); + ActivationGroupDesc groupDesc = + new ActivationGroupDesc(p, null); + ActivationSystem system = ActivationGroup.getSystem(); + ActivationGroupID groupID = system.registerGroup(groupDesc); - // Make sure we received a *local* AccessControlException - ByteArrayOutputStream bout = new ByteArrayOutputStream(); - PrintStream ps = new PrintStream(bout); - e.printStackTrace(ps); - ps.flush(); - String trace = new String(bout.toByteArray()); - if ((trace.indexOf("exceptionReceivedFromServer") >= 0) || - trace.equals("")) + System.err.println("register activatable"); + // Fix for: 4271615: make sure activation group runs in a new VM + ActivationDesc desc = new ActivationDesc + (groupID, "StubClassesPermitted", null, null); + canCreateStubs = (CanCreateStubs) Activatable.register(desc); + + // ensure registry stub can be passed in a remote call + System.err.println("getting the registry"); + registry = canCreateStubs.getRegistry(); + + // make sure a client cant load just any sun.* class, just + // as a sanity check, try to create a class we are not + // allowed to access but which was passed in a remote call + try { + System.err.println("accessing forbidden class"); + Object secureRandom = canCreateStubs.getForbiddenClass(); + + TestLibrary.bomb("test allowed to access forbidden class," + + " sun.security.provider.SecureRandom"); + } catch (java.security.AccessControlException e) { + + // Make sure we received a *local* AccessControlException + ByteArrayOutputStream bout = new ByteArrayOutputStream(); + PrintStream ps = new PrintStream(bout); + e.printStackTrace(ps); + ps.flush(); + String trace = new String(bout.toByteArray()); + if ((trace.indexOf("exceptionReceivedFromServer") >= 0) || + trace.equals("")) { - throw e; - } - System.err.println("received expected local access control exception"); - } + throw e; + } + System.err.println("received expected local access control exception"); + } - // make sure that an ActivationGroupID can be passed in a - // remote call; this is slightly more inclusive than - // just passing a reference to the activation system - System.err.println("returning group desc"); - canCreateStubs.returnGroupID(); - - // Clean up object - System.err.println - ("Deactivate object via method call"); - canCreateStubs.shutdown(); + // make sure that an ActivationGroupID can be passed in a + // remote call; this is slightly more inclusive than + // just passing a reference to the activation system + System.err.println("returning group desc"); + canCreateStubs.returnGroupID(); - System.err.println - ("\nsuccess: StubClassesPermitted test passed "); - - } catch (Exception e) { - TestLibrary.bomb("\nfailure: unexpected exception ", e); - } finally { - try { - Thread.sleep(4000); - } catch (InterruptedException e) { - } - - canCreateStubs = null; - ActivationLibrary.rmidCleanup(rmid); - System.err.println("rmid shut down"); - } + // Clean up object + System.err.println + ("Deactivate object via method call"); + canCreateStubs.shutdown(); + + System.err.println + ("\nsuccess: StubClassesPermitted test passed "); + + } catch (Exception e) { + TestLibrary.bomb("\nfailure: unexpected exception ", e); + } finally { + try { + Thread.sleep(4000); + } catch (InterruptedException e) { + } + + canCreateStubs = null; + ActivationLibrary.rmidCleanup(rmid); + System.err.println("rmid shut down"); + } } - + static ActivationGroupID GroupID = null; /** - * implementation of CanCreateStubs + * implementation of CanCreateStubs */ public StubClassesPermitted - (ActivationID id, MarshalledObject mo) throws RemoteException + (ActivationID id, MarshalledObject mo) throws RemoteException { - // register/export anonymously - super(id, 0); + // register/export anonymously + super(id, 0); - // obtain reference to the test registry - registry = java.rmi.registry.LocateRegistry. - getRegistry(TestLibrary.REGISTRY_PORT); + // obtain reference to the test registry + registry = java.rmi.registry.LocateRegistry. + getRegistry(TestLibrary.REGISTRY_PORT); } - + /** * Spawns a thread to deactivate the object. */ public void shutdown() throws Exception { - (new Thread(this,"StubClassesPermitted")).start(); + (new Thread(this,"StubClassesPermitted")).start(); } /** @@ -209,7 +209,7 @@ public class StubClassesPermitted * unexport the object forcibly. */ public void run() { - ActivationLibrary.deactivate(this, getID()); + ActivationLibrary.deactivate(this, getID()); } /** @@ -217,12 +217,12 @@ public class StubClassesPermitted * the stub for it can be deserialized in the test client VM. */ public Registry getRegistry() throws RemoteException { - if (sameGroup) { - System.out.println("in same group"); - } else { - System.out.println("not in same group"); - } - return registry; + if (sameGroup) { + System.out.println("in same group"); + } else { + System.out.println("not in same group"); + } + return registry; } /** @@ -232,8 +232,8 @@ public class StubClassesPermitted * can be resolved in a remote call. */ public Object getForbiddenClass() throws RemoteException { - System.err.println("creating sun class"); - return new sun.security.provider.SecureRandom(); + System.err.println("creating sun class"); + return new sun.security.provider.SecureRandom(); } /** @@ -242,6 +242,6 @@ public class StubClassesPermitted * system implementation). */ public ActivationGroupID returnGroupID() throws RemoteException { - return ActivationGroup.currentGroupID(); + return ActivationGroup.currentGroupID(); } } diff --git a/jdk/test/java/rmi/activation/ActivationSystem/stubClassesPermitted/StubClassesPermitted_Stub.java b/jdk/test/java/rmi/activation/ActivationSystem/stubClassesPermitted/StubClassesPermitted_Stub.java index 829e2abf695..a8cb2d81f5f 100644 --- a/jdk/test/java/rmi/activation/ActivationSystem/stubClassesPermitted/StubClassesPermitted_Stub.java +++ b/jdk/test/java/rmi/activation/ActivationSystem/stubClassesPermitted/StubClassesPermitted_Stub.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -29,152 +29,152 @@ public final class StubClassesPermitted_Stub implements CanCreateStubs, java.rmi.Remote { private static final java.rmi.server.Operation[] operations = { - new java.rmi.server.Operation("java.lang.Object getForbiddenClass()"), - new java.rmi.server.Operation("java.rmi.registry.Registry getRegistry()"), - new java.rmi.server.Operation("java.rmi.activation.ActivationGroupID returnGroupID()"), - new java.rmi.server.Operation("void shutdown()") + new java.rmi.server.Operation("java.lang.Object getForbiddenClass()"), + new java.rmi.server.Operation("java.rmi.registry.Registry getRegistry()"), + new java.rmi.server.Operation("java.rmi.activation.ActivationGroupID returnGroupID()"), + new java.rmi.server.Operation("void shutdown()") }; - + private static final long interfaceHash = 1677779850431817575L; - + private static final long serialVersionUID = 2; - + private static boolean useNewInvoke; private static java.lang.reflect.Method $method_getForbiddenClass_0; private static java.lang.reflect.Method $method_getRegistry_1; private static java.lang.reflect.Method $method_returnGroupID_2; private static java.lang.reflect.Method $method_shutdown_3; - + static { - try { - java.rmi.server.RemoteRef.class.getMethod("invoke", - new java.lang.Class[] { - java.rmi.Remote.class, - java.lang.reflect.Method.class, - java.lang.Object[].class, - long.class - }); - useNewInvoke = true; - $method_getForbiddenClass_0 = CanCreateStubs.class.getMethod("getForbiddenClass", new java.lang.Class[] {}); - $method_getRegistry_1 = CanCreateStubs.class.getMethod("getRegistry", new java.lang.Class[] {}); - $method_returnGroupID_2 = CanCreateStubs.class.getMethod("returnGroupID", new java.lang.Class[] {}); - $method_shutdown_3 = CanCreateStubs.class.getMethod("shutdown", new java.lang.Class[] {}); - } catch (java.lang.NoSuchMethodException e) { - useNewInvoke = false; - } + try { + java.rmi.server.RemoteRef.class.getMethod("invoke", + new java.lang.Class[] { + java.rmi.Remote.class, + java.lang.reflect.Method.class, + java.lang.Object[].class, + long.class + }); + useNewInvoke = true; + $method_getForbiddenClass_0 = CanCreateStubs.class.getMethod("getForbiddenClass", new java.lang.Class[] {}); + $method_getRegistry_1 = CanCreateStubs.class.getMethod("getRegistry", new java.lang.Class[] {}); + $method_returnGroupID_2 = CanCreateStubs.class.getMethod("returnGroupID", new java.lang.Class[] {}); + $method_shutdown_3 = CanCreateStubs.class.getMethod("shutdown", new java.lang.Class[] {}); + } catch (java.lang.NoSuchMethodException e) { + useNewInvoke = false; + } } - + // constructors public StubClassesPermitted_Stub() { - super(); + super(); } public StubClassesPermitted_Stub(java.rmi.server.RemoteRef ref) { - super(ref); + super(ref); } - + // methods from remote interfaces - + // implementation of getForbiddenClass() public java.lang.Object getForbiddenClass() - throws java.lang.Exception + throws java.lang.Exception { - if (useNewInvoke) { - Object $result = ref.invoke(this, $method_getForbiddenClass_0, null, -658265783646674294L); - return ((java.lang.Object) $result); - } else { - java.rmi.server.RemoteCall call = ref.newCall((java.rmi.server.RemoteObject) this, operations, 0, interfaceHash); - ref.invoke(call); - java.lang.Object $result; - try { - java.io.ObjectInput in = call.getInputStream(); - $result = (java.lang.Object) in.readObject(); - } catch (java.io.IOException e) { - throw new java.rmi.UnmarshalException("error unmarshalling return", e); - } catch (java.lang.ClassNotFoundException e) { - throw new java.rmi.UnmarshalException("error unmarshalling return", e); - } finally { - ref.done(call); - } - return $result; - } + if (useNewInvoke) { + Object $result = ref.invoke(this, $method_getForbiddenClass_0, null, -658265783646674294L); + return ((java.lang.Object) $result); + } else { + java.rmi.server.RemoteCall call = ref.newCall((java.rmi.server.RemoteObject) this, operations, 0, interfaceHash); + ref.invoke(call); + java.lang.Object $result; + try { + java.io.ObjectInput in = call.getInputStream(); + $result = (java.lang.Object) in.readObject(); + } catch (java.io.IOException e) { + throw new java.rmi.UnmarshalException("error unmarshalling return", e); + } catch (java.lang.ClassNotFoundException e) { + throw new java.rmi.UnmarshalException("error unmarshalling return", e); + } finally { + ref.done(call); + } + return $result; + } } - + // implementation of getRegistry() public java.rmi.registry.Registry getRegistry() - throws java.rmi.RemoteException + throws java.rmi.RemoteException { - try { - if (useNewInvoke) { - Object $result = ref.invoke(this, $method_getRegistry_1, null, 255311215504696981L); - return ((java.rmi.registry.Registry) $result); - } else { - java.rmi.server.RemoteCall call = ref.newCall((java.rmi.server.RemoteObject) this, operations, 1, interfaceHash); - ref.invoke(call); - java.rmi.registry.Registry $result; - try { - java.io.ObjectInput in = call.getInputStream(); - $result = (java.rmi.registry.Registry) in.readObject(); - } catch (java.io.IOException e) { - throw new java.rmi.UnmarshalException("error unmarshalling return", e); - } catch (java.lang.ClassNotFoundException e) { - throw new java.rmi.UnmarshalException("error unmarshalling return", e); - } finally { - ref.done(call); - } - return $result; - } - } catch (java.lang.RuntimeException e) { - throw e; - } catch (java.rmi.RemoteException e) { - throw e; - } catch (java.lang.Exception e) { - throw new java.rmi.UnexpectedException("undeclared checked exception", e); - } + try { + if (useNewInvoke) { + Object $result = ref.invoke(this, $method_getRegistry_1, null, 255311215504696981L); + return ((java.rmi.registry.Registry) $result); + } else { + java.rmi.server.RemoteCall call = ref.newCall((java.rmi.server.RemoteObject) this, operations, 1, interfaceHash); + ref.invoke(call); + java.rmi.registry.Registry $result; + try { + java.io.ObjectInput in = call.getInputStream(); + $result = (java.rmi.registry.Registry) in.readObject(); + } catch (java.io.IOException e) { + throw new java.rmi.UnmarshalException("error unmarshalling return", e); + } catch (java.lang.ClassNotFoundException e) { + throw new java.rmi.UnmarshalException("error unmarshalling return", e); + } finally { + ref.done(call); + } + return $result; + } + } catch (java.lang.RuntimeException e) { + throw e; + } catch (java.rmi.RemoteException e) { + throw e; + } catch (java.lang.Exception e) { + throw new java.rmi.UnexpectedException("undeclared checked exception", e); + } } - + // implementation of returnGroupID() public java.rmi.activation.ActivationGroupID returnGroupID() - throws java.rmi.RemoteException + throws java.rmi.RemoteException { - try { - if (useNewInvoke) { - Object $result = ref.invoke(this, $method_returnGroupID_2, null, 6267304638191237098L); - return ((java.rmi.activation.ActivationGroupID) $result); - } else { - java.rmi.server.RemoteCall call = ref.newCall((java.rmi.server.RemoteObject) this, operations, 2, interfaceHash); - ref.invoke(call); - java.rmi.activation.ActivationGroupID $result; - try { - java.io.ObjectInput in = call.getInputStream(); - $result = (java.rmi.activation.ActivationGroupID) in.readObject(); - } catch (java.io.IOException e) { - throw new java.rmi.UnmarshalException("error unmarshalling return", e); - } catch (java.lang.ClassNotFoundException e) { - throw new java.rmi.UnmarshalException("error unmarshalling return", e); - } finally { - ref.done(call); - } - return $result; - } - } catch (java.lang.RuntimeException e) { - throw e; - } catch (java.rmi.RemoteException e) { - throw e; - } catch (java.lang.Exception e) { - throw new java.rmi.UnexpectedException("undeclared checked exception", e); - } + try { + if (useNewInvoke) { + Object $result = ref.invoke(this, $method_returnGroupID_2, null, 6267304638191237098L); + return ((java.rmi.activation.ActivationGroupID) $result); + } else { + java.rmi.server.RemoteCall call = ref.newCall((java.rmi.server.RemoteObject) this, operations, 2, interfaceHash); + ref.invoke(call); + java.rmi.activation.ActivationGroupID $result; + try { + java.io.ObjectInput in = call.getInputStream(); + $result = (java.rmi.activation.ActivationGroupID) in.readObject(); + } catch (java.io.IOException e) { + throw new java.rmi.UnmarshalException("error unmarshalling return", e); + } catch (java.lang.ClassNotFoundException e) { + throw new java.rmi.UnmarshalException("error unmarshalling return", e); + } finally { + ref.done(call); + } + return $result; + } + } catch (java.lang.RuntimeException e) { + throw e; + } catch (java.rmi.RemoteException e) { + throw e; + } catch (java.lang.Exception e) { + throw new java.rmi.UnexpectedException("undeclared checked exception", e); + } } - + // implementation of shutdown() public void shutdown() - throws java.lang.Exception + throws java.lang.Exception { - if (useNewInvoke) { - ref.invoke(this, $method_shutdown_3, null, -7207851917985848402L); - } else { - java.rmi.server.RemoteCall call = ref.newCall((java.rmi.server.RemoteObject) this, operations, 3, interfaceHash); - ref.invoke(call); - ref.done(call); - } + if (useNewInvoke) { + ref.invoke(this, $method_shutdown_3, null, -7207851917985848402L); + } else { + java.rmi.server.RemoteCall call = ref.newCall((java.rmi.server.RemoteObject) this, operations, 3, interfaceHash); + ref.invoke(call); + ref.done(call); + } } } diff --git a/jdk/test/java/rmi/activation/ActivationSystem/unregisterGroup/ActivateMe.java b/jdk/test/java/rmi/activation/ActivationSystem/unregisterGroup/ActivateMe.java index cf165fb3141..d9848e3c815 100644 --- a/jdk/test/java/rmi/activation/ActivationSystem/unregisterGroup/ActivateMe.java +++ b/jdk/test/java/rmi/activation/ActivationSystem/unregisterGroup/ActivateMe.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * diff --git a/jdk/test/java/rmi/activation/ActivationSystem/unregisterGroup/CallbackInterface.java b/jdk/test/java/rmi/activation/ActivationSystem/unregisterGroup/CallbackInterface.java index 287346fa031..e737ac91603 100644 --- a/jdk/test/java/rmi/activation/ActivationSystem/unregisterGroup/CallbackInterface.java +++ b/jdk/test/java/rmi/activation/ActivationSystem/unregisterGroup/CallbackInterface.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -27,4 +27,3 @@ public interface CallbackInterface extends Remote { public void inc() throws RemoteException; public int getNumDeactivated() throws RemoteException; } - diff --git a/jdk/test/java/rmi/activation/ActivationSystem/unregisterGroup/Callback_Stub.java b/jdk/test/java/rmi/activation/ActivationSystem/unregisterGroup/Callback_Stub.java index 8e77ed15094..4e8a85d759b 100644 --- a/jdk/test/java/rmi/activation/ActivationSystem/unregisterGroup/Callback_Stub.java +++ b/jdk/test/java/rmi/activation/ActivationSystem/unregisterGroup/Callback_Stub.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -29,94 +29,94 @@ public final class Callback_Stub implements CallbackInterface, java.rmi.Remote { private static final java.rmi.server.Operation[] operations = { - new java.rmi.server.Operation("int getNumDeactivated()"), - new java.rmi.server.Operation("void inc()") + new java.rmi.server.Operation("int getNumDeactivated()"), + new java.rmi.server.Operation("void inc()") }; - + private static final long interfaceHash = -1008194523112388035L; - + private static final long serialVersionUID = 2; - + private static boolean useNewInvoke; private static java.lang.reflect.Method $method_getNumDeactivated_0; private static java.lang.reflect.Method $method_inc_1; - + static { - try { - java.rmi.server.RemoteRef.class.getMethod("invoke", - new java.lang.Class[] { - java.rmi.Remote.class, - java.lang.reflect.Method.class, - java.lang.Object[].class, - long.class - }); - useNewInvoke = true; - $method_getNumDeactivated_0 = CallbackInterface.class.getMethod("getNumDeactivated", new java.lang.Class[] {}); - $method_inc_1 = CallbackInterface.class.getMethod("inc", new java.lang.Class[] {}); - } catch (java.lang.NoSuchMethodException e) { - useNewInvoke = false; - } + try { + java.rmi.server.RemoteRef.class.getMethod("invoke", + new java.lang.Class[] { + java.rmi.Remote.class, + java.lang.reflect.Method.class, + java.lang.Object[].class, + long.class + }); + useNewInvoke = true; + $method_getNumDeactivated_0 = CallbackInterface.class.getMethod("getNumDeactivated", new java.lang.Class[] {}); + $method_inc_1 = CallbackInterface.class.getMethod("inc", new java.lang.Class[] {}); + } catch (java.lang.NoSuchMethodException e) { + useNewInvoke = false; + } } - + // constructors public Callback_Stub() { - super(); + super(); } public Callback_Stub(java.rmi.server.RemoteRef ref) { - super(ref); + super(ref); } - + // methods from remote interfaces - + // implementation of getNumDeactivated() public int getNumDeactivated() - throws java.rmi.RemoteException + throws java.rmi.RemoteException { - try { - if (useNewInvoke) { - Object $result = ref.invoke(this, $method_getNumDeactivated_0, null, -761062487639949912L); - return ((java.lang.Integer) $result).intValue(); - } else { - java.rmi.server.RemoteCall call = ref.newCall((java.rmi.server.RemoteObject) this, operations, 0, interfaceHash); - ref.invoke(call); - int $result; - try { - java.io.ObjectInput in = call.getInputStream(); - $result = in.readInt(); - } catch (java.io.IOException e) { - throw new java.rmi.UnmarshalException("error unmarshalling return", e); - } finally { - ref.done(call); - } - return $result; - } - } catch (java.lang.RuntimeException e) { - throw e; - } catch (java.rmi.RemoteException e) { - throw e; - } catch (java.lang.Exception e) { - throw new java.rmi.UnexpectedException("undeclared checked exception", e); - } + try { + if (useNewInvoke) { + Object $result = ref.invoke(this, $method_getNumDeactivated_0, null, -761062487639949912L); + return ((java.lang.Integer) $result).intValue(); + } else { + java.rmi.server.RemoteCall call = ref.newCall((java.rmi.server.RemoteObject) this, operations, 0, interfaceHash); + ref.invoke(call); + int $result; + try { + java.io.ObjectInput in = call.getInputStream(); + $result = in.readInt(); + } catch (java.io.IOException e) { + throw new java.rmi.UnmarshalException("error unmarshalling return", e); + } finally { + ref.done(call); + } + return $result; + } + } catch (java.lang.RuntimeException e) { + throw e; + } catch (java.rmi.RemoteException e) { + throw e; + } catch (java.lang.Exception e) { + throw new java.rmi.UnexpectedException("undeclared checked exception", e); + } } - + // implementation of inc() public void inc() - throws java.rmi.RemoteException + throws java.rmi.RemoteException { - try { - if (useNewInvoke) { - ref.invoke(this, $method_inc_1, null, 4394985085384332959L); - } else { - java.rmi.server.RemoteCall call = ref.newCall((java.rmi.server.RemoteObject) this, operations, 1, interfaceHash); - ref.invoke(call); - ref.done(call); - } - } catch (java.lang.RuntimeException e) { - throw e; - } catch (java.rmi.RemoteException e) { - throw e; - } catch (java.lang.Exception e) { - throw new java.rmi.UnexpectedException("undeclared checked exception", e); - } + try { + if (useNewInvoke) { + ref.invoke(this, $method_inc_1, null, 4394985085384332959L); + } else { + java.rmi.server.RemoteCall call = ref.newCall((java.rmi.server.RemoteObject) this, operations, 1, interfaceHash); + ref.invoke(call); + ref.done(call); + } + } catch (java.lang.RuntimeException e) { + throw e; + } catch (java.rmi.RemoteException e) { + throw e; + } catch (java.lang.Exception e) { + throw new java.rmi.UnexpectedException("undeclared checked exception", e); + } } } diff --git a/jdk/test/java/rmi/activation/ActivationSystem/unregisterGroup/UnregisterGroup.java b/jdk/test/java/rmi/activation/ActivationSystem/unregisterGroup/UnregisterGroup.java index 6498f738ffa..605b66b1ec8 100644 --- a/jdk/test/java/rmi/activation/ActivationSystem/unregisterGroup/UnregisterGroup.java +++ b/jdk/test/java/rmi/activation/ActivationSystem/unregisterGroup/UnregisterGroup.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1998-2000 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -65,8 +65,8 @@ class Callback extends UnicastRemoteObject implements CallbackInterface { } public class UnregisterGroup - extends Activatable - implements ActivateMe, Runnable + extends Activatable + implements ActivateMe, Runnable { private static Exception exception = null; @@ -77,30 +77,30 @@ public class UnregisterGroup private static int PORT = 2006; public UnregisterGroup(ActivationID id, MarshalledObject mobj) - throws Exception + throws Exception { - super(id, 0); + super(id, 0); } public void ping() {} public void unregister() throws Exception { - super.unregister(super.getID()); + super.unregister(super.getID()); } - + /** * Spawns a thread to deactivate the object. */ public void shutdown() throws Exception { - (new Thread(this,"UnregisterGroup")).start(); + (new Thread(this,"UnregisterGroup")).start(); } /** * To support exiting of group VM as a last resort */ public void justGoAway() { - System.exit(0); + System.exit(0); } /** @@ -111,151 +111,151 @@ public class UnregisterGroup */ public void run() { - ActivationLibrary.deactivate(this, getID()); - System.err.println("\tActivationLibrary.deactivate returned"); + ActivationLibrary.deactivate(this, getID()); + System.err.println("\tActivationLibrary.deactivate returned"); - try { - CallbackInterface cobj = - (CallbackInterface)Naming.lookup("//:" + PORT + "/Callback"); - cobj.inc(); - } catch (Exception e) { - System.err.println("cobj.inc exception"); - e.printStackTrace(); - } + try { + CallbackInterface cobj = + (CallbackInterface)Naming.lookup("//:" + PORT + "/Callback"); + cobj.inc(); + } catch (Exception e) { + System.err.println("cobj.inc exception"); + e.printStackTrace(); + } } public static void main(String[] args) { - Registry registry; + Registry registry; - System.err.println("\nRegression test for bug 4134233\n"); - - TestLibrary.suggestSecurityManager("java.rmi.RMISecurityManager"); - RMID rmid = null; - - try { - RMID.removeLog(); - rmid = RMID.createRMID(); - rmid.start(); + System.err.println("\nRegression test for bug 4134233\n"); - /* Cause activation groups to have a security policy that will - * allow security managers to be downloaded and installed - */ - final Properties p = new Properties(); - // this test must always set policies/managers in its - // activation groups - p.put("java.security.policy", - TestParams.defaultGroupPolicy); - p.put("java.security.manager", - TestParams.defaultSecurityManager); + TestLibrary.suggestSecurityManager("java.rmi.RMISecurityManager"); + RMID rmid = null; - //final int NUM_OBJECTS = 10; - - Thread t = new Thread() { - public void run () { - try { - System.err.println("Creating group descriptor"); - ActivationGroupDesc groupDesc = - new ActivationGroupDesc(p, null); - ActivationSystem system = ActivationGroup.getSystem(); - ActivationGroupID groupID = - system.registerGroup(groupDesc); + try { + RMID.removeLog(); + rmid = RMID.createRMID(); + rmid.start(); - ActivateMe[] obj = new ActivateMe[NUM_OBJECTS]; + /* Cause activation groups to have a security policy that will + * allow security managers to be downloaded and installed + */ + final Properties p = new Properties(); + // this test must always set policies/managers in its + // activation groups + p.put("java.security.policy", + TestParams.defaultGroupPolicy); + p.put("java.security.manager", + TestParams.defaultSecurityManager); - for (int i = 0; i < NUM_OBJECTS; i++) { - System.err.println("Creating descriptor: " + i); - ActivationDesc desc = - new ActivationDesc(groupID, "UnregisterGroup", - null, null); - System.err.println("Registering descriptor: " + i); - obj[i] = (ActivateMe) Activatable.register(desc); - System.err.println("Activating object: " + i); - obj[i].ping(); - } - lastResortExitObj = obj[0]; + //final int NUM_OBJECTS = 10; - System.err.println("Unregistering group"); - system.unregisterGroup(groupID); + Thread t = new Thread() { + public void run () { + try { + System.err.println("Creating group descriptor"); + ActivationGroupDesc groupDesc = + new ActivationGroupDesc(p, null); + ActivationSystem system = ActivationGroup.getSystem(); + ActivationGroupID groupID = + system.registerGroup(groupDesc); - try { - System.err.println("Get the group descriptor"); - system.getActivationGroupDesc(groupID); - error = "test failed: group still registered"; - } catch (UnknownGroupException e) { - System.err.println("Test passed: " + - "group unregistered"); - } + ActivateMe[] obj = new ActivateMe[NUM_OBJECTS]; + + for (int i = 0; i < NUM_OBJECTS; i++) { + System.err.println("Creating descriptor: " + i); + ActivationDesc desc = + new ActivationDesc(groupID, "UnregisterGroup", + null, null); + System.err.println("Registering descriptor: " + i); + obj[i] = (ActivateMe) Activatable.register(desc); + System.err.println("Activating object: " + i); + obj[i].ping(); + } + lastResortExitObj = obj[0]; + + System.err.println("Unregistering group"); + system.unregisterGroup(groupID); + + try { + System.err.println("Get the group descriptor"); + system.getActivationGroupDesc(groupID); + error = "test failed: group still registered"; + } catch (UnknownGroupException e) { + System.err.println("Test passed: " + + "group unregistered"); + } - /* - * Deactivate objects so group VM will exit. - */ - for (int i = 0; i < NUM_OBJECTS; i++) { - System.err.println("Deactivating object: " + i); - obj[i].shutdown(); - obj[i] = null; - } - lastResortExitObj = null; + /* + * Deactivate objects so group VM will exit. + */ + for (int i = 0; i < NUM_OBJECTS; i++) { + System.err.println("Deactivating object: " + i); + obj[i].shutdown(); + obj[i] = null; + } + lastResortExitObj = null; - } catch (Exception e) { - exception = e; - } + } catch (Exception e) { + exception = e; + } - done = true; - } - }; + done = true; + } + }; - t.start(); - t.join(120000); + t.start(); + t.join(120000); - if (exception != null) { - TestLibrary.bomb("test failed", exception); - } else if (error != null) { - TestLibrary.bomb(error, null); - } else if (!done) { - TestLibrary.bomb("test failed: not completed before timeout", null); - } else { - System.err.println("Test passed"); - } + if (exception != null) { + TestLibrary.bomb("test failed", exception); + } else if (error != null) { + TestLibrary.bomb(error, null); + } else if (!done) { + TestLibrary.bomb("test failed: not completed before timeout", null); + } else { + System.err.println("Test passed"); + } - - } catch (Exception e) { - TestLibrary.bomb("test failed", e); - } finally { - if (lastResortExitObj != null) { - try { - lastResortExitObj.justGoAway(); - } catch (Exception munch) { - } - } - // Wait for the object deactivation to take place first - try { + } catch (Exception e) { + TestLibrary.bomb("test failed", e); + } finally { + if (lastResortExitObj != null) { + try { + lastResortExitObj.justGoAway(); + } catch (Exception munch) { + } + } - // create reg and export callback object - registry = LocateRegistry.createRegistry(PORT); - Callback robj = new Callback(); - registry.bind("Callback", robj); + // Wait for the object deactivation to take place first + try { - //get the callback object - int maxwait=30; - int nd = robj.getNumDeactivated(); - while ((nd < NUM_OBJECTS) && (maxwait> 0)) { - System.err.println("num_deactivated="+nd); - try { - Thread.sleep(1000); - } catch (InterruptedException ie) {} - maxwait--; - nd = robj.getNumDeactivated(); - } - } catch (Exception ce) { - System.err.println("E:"+ce); - ce.printStackTrace(); - } + // create reg and export callback object + registry = LocateRegistry.createRegistry(PORT); + Callback robj = new Callback(); + registry.bind("Callback", robj); - ActivationLibrary.rmidCleanup(rmid); - } + //get the callback object + int maxwait=30; + int nd = robj.getNumDeactivated(); + while ((nd < NUM_OBJECTS) && (maxwait> 0)) { + System.err.println("num_deactivated="+nd); + try { + Thread.sleep(1000); + } catch (InterruptedException ie) {} + maxwait--; + nd = robj.getNumDeactivated(); + } + } catch (Exception ce) { + System.err.println("E:"+ce); + ce.printStackTrace(); + } + + ActivationLibrary.rmidCleanup(rmid); + } } } diff --git a/jdk/test/java/rmi/activation/ActivationSystem/unregisterGroup/UnregisterGroup_Stub.java b/jdk/test/java/rmi/activation/ActivationSystem/unregisterGroup/UnregisterGroup_Stub.java index 16a3278505b..e9a5bcfb141 100644 --- a/jdk/test/java/rmi/activation/ActivationSystem/unregisterGroup/UnregisterGroup_Stub.java +++ b/jdk/test/java/rmi/activation/ActivationSystem/unregisterGroup/UnregisterGroup_Stub.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1998-1999 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -29,116 +29,116 @@ public final class UnregisterGroup_Stub implements ActivateMe, java.rmi.Remote { private static final java.rmi.server.Operation[] operations = { - new java.rmi.server.Operation("void justGoAway()"), - new java.rmi.server.Operation("void ping()"), - new java.rmi.server.Operation("void shutdown()"), - new java.rmi.server.Operation("void unregister()") + new java.rmi.server.Operation("void justGoAway()"), + new java.rmi.server.Operation("void ping()"), + new java.rmi.server.Operation("void shutdown()"), + new java.rmi.server.Operation("void unregister()") }; - + private static final long interfaceHash = -4733924075192691630L; - + private static final long serialVersionUID = 2; - + private static boolean useNewInvoke; private static java.lang.reflect.Method $method_justGoAway_0; private static java.lang.reflect.Method $method_ping_1; private static java.lang.reflect.Method $method_shutdown_2; private static java.lang.reflect.Method $method_unregister_3; - + static { - try { - java.rmi.server.RemoteRef.class.getMethod("invoke", - new java.lang.Class[] { - java.rmi.Remote.class, - java.lang.reflect.Method.class, - java.lang.Object[].class, - long.class - }); - useNewInvoke = true; - $method_justGoAway_0 = ActivateMe.class.getMethod("justGoAway", new java.lang.Class[] {}); - $method_ping_1 = ActivateMe.class.getMethod("ping", new java.lang.Class[] {}); - $method_shutdown_2 = ActivateMe.class.getMethod("shutdown", new java.lang.Class[] {}); - $method_unregister_3 = ActivateMe.class.getMethod("unregister", new java.lang.Class[] {}); - } catch (java.lang.NoSuchMethodException e) { - useNewInvoke = false; - } + try { + java.rmi.server.RemoteRef.class.getMethod("invoke", + new java.lang.Class[] { + java.rmi.Remote.class, + java.lang.reflect.Method.class, + java.lang.Object[].class, + long.class + }); + useNewInvoke = true; + $method_justGoAway_0 = ActivateMe.class.getMethod("justGoAway", new java.lang.Class[] {}); + $method_ping_1 = ActivateMe.class.getMethod("ping", new java.lang.Class[] {}); + $method_shutdown_2 = ActivateMe.class.getMethod("shutdown", new java.lang.Class[] {}); + $method_unregister_3 = ActivateMe.class.getMethod("unregister", new java.lang.Class[] {}); + } catch (java.lang.NoSuchMethodException e) { + useNewInvoke = false; + } } - + // constructors public UnregisterGroup_Stub() { - super(); + super(); } public UnregisterGroup_Stub(java.rmi.server.RemoteRef ref) { - super(ref); + super(ref); } - + // methods from remote interfaces - + // implementation of justGoAway() public void justGoAway() - throws java.rmi.RemoteException + throws java.rmi.RemoteException { - try { - if (useNewInvoke) { - ref.invoke(this, $method_justGoAway_0, null, -5382478058620783904L); - } else { - java.rmi.server.RemoteCall call = ref.newCall((java.rmi.server.RemoteObject) this, operations, 0, interfaceHash); - ref.invoke(call); - ref.done(call); - } - } catch (java.lang.RuntimeException e) { - throw e; - } catch (java.rmi.RemoteException e) { - throw e; - } catch (java.lang.Exception e) { - throw new java.rmi.UnexpectedException("undeclared checked exception", e); - } + try { + if (useNewInvoke) { + ref.invoke(this, $method_justGoAway_0, null, -5382478058620783904L); + } else { + java.rmi.server.RemoteCall call = ref.newCall((java.rmi.server.RemoteObject) this, operations, 0, interfaceHash); + ref.invoke(call); + ref.done(call); + } + } catch (java.lang.RuntimeException e) { + throw e; + } catch (java.rmi.RemoteException e) { + throw e; + } catch (java.lang.Exception e) { + throw new java.rmi.UnexpectedException("undeclared checked exception", e); + } } - + // implementation of ping() public void ping() - throws java.rmi.RemoteException + throws java.rmi.RemoteException { - try { - if (useNewInvoke) { - ref.invoke(this, $method_ping_1, null, 5866401369815527589L); - } else { - java.rmi.server.RemoteCall call = ref.newCall((java.rmi.server.RemoteObject) this, operations, 1, interfaceHash); - ref.invoke(call); - ref.done(call); - } - } catch (java.lang.RuntimeException e) { - throw e; - } catch (java.rmi.RemoteException e) { - throw e; - } catch (java.lang.Exception e) { - throw new java.rmi.UnexpectedException("undeclared checked exception", e); - } + try { + if (useNewInvoke) { + ref.invoke(this, $method_ping_1, null, 5866401369815527589L); + } else { + java.rmi.server.RemoteCall call = ref.newCall((java.rmi.server.RemoteObject) this, operations, 1, interfaceHash); + ref.invoke(call); + ref.done(call); + } + } catch (java.lang.RuntimeException e) { + throw e; + } catch (java.rmi.RemoteException e) { + throw e; + } catch (java.lang.Exception e) { + throw new java.rmi.UnexpectedException("undeclared checked exception", e); + } } - + // implementation of shutdown() public void shutdown() - throws java.lang.Exception + throws java.lang.Exception { - if (useNewInvoke) { - ref.invoke(this, $method_shutdown_2, null, -7207851917985848402L); - } else { - java.rmi.server.RemoteCall call = ref.newCall((java.rmi.server.RemoteObject) this, operations, 2, interfaceHash); - ref.invoke(call); - ref.done(call); - } + if (useNewInvoke) { + ref.invoke(this, $method_shutdown_2, null, -7207851917985848402L); + } else { + java.rmi.server.RemoteCall call = ref.newCall((java.rmi.server.RemoteObject) this, operations, 2, interfaceHash); + ref.invoke(call); + ref.done(call); + } } - + // implementation of unregister() public void unregister() - throws java.lang.Exception + throws java.lang.Exception { - if (useNewInvoke) { - ref.invoke(this, $method_unregister_3, null, -5366864281862648102L); - } else { - java.rmi.server.RemoteCall call = ref.newCall((java.rmi.server.RemoteObject) this, operations, 3, interfaceHash); - ref.invoke(call); - ref.done(call); - } + if (useNewInvoke) { + ref.invoke(this, $method_unregister_3, null, -5366864281862648102L); + } else { + java.rmi.server.RemoteCall call = ref.newCall((java.rmi.server.RemoteObject) this, operations, 3, interfaceHash); + ref.invoke(call); + ref.done(call); + } } } diff --git a/jdk/test/java/rmi/dgc/VMID/CheckVMID.java b/jdk/test/java/rmi/dgc/VMID/CheckVMID.java index ae32872b943..09e4cbec91e 100644 --- a/jdk/test/java/rmi/dgc/VMID/CheckVMID.java +++ b/jdk/test/java/rmi/dgc/VMID/CheckVMID.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -41,17 +41,17 @@ public class CheckVMID { public static void main(String[] args) { - System.err.println("\nRegression test for bug 4171370\n"); + System.err.println("\nRegression test for bug 4171370\n"); - TestLibrary.suggestSecurityManager(null); + TestLibrary.suggestSecurityManager(null); - try { - System.err.println("Create a VMID"); - VMID vmid = new VMID(); - System.err.println("vmid = " + vmid); - } catch (Exception e) { - e.printStackTrace(); - throw new RuntimeException("TEST FAILED: " + e.toString()); - } + try { + System.err.println("Create a VMID"); + VMID vmid = new VMID(); + System.err.println("vmid = " + vmid); + } catch (Exception e) { + e.printStackTrace(); + throw new RuntimeException("TEST FAILED: " + e.toString()); + } } } diff --git a/jdk/test/java/rmi/dgc/dgcAckFailure/DGCAckFailure.java b/jdk/test/java/rmi/dgc/dgcAckFailure/DGCAckFailure.java index 446b2405ccf..2a0e4309be2 100644 --- a/jdk/test/java/rmi/dgc/dgcAckFailure/DGCAckFailure.java +++ b/jdk/test/java/rmi/dgc/dgcAckFailure/DGCAckFailure.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -51,123 +51,123 @@ public class DGCAckFailure implements ReturnRemote { private static final long TIMEOUT = 20000; public Object returnRemote() { - return new Wrapper(this); + return new Wrapper(this); } public static void main(String[] args) throws Exception { - System.setProperty("sun.rmi.dgc.ackTimeout", "10000"); + System.setProperty("sun.rmi.dgc.ackTimeout", "10000"); - /* - * Set a socket factory that has a hook for shutting down all client - * output (writes from client-created sockets and new connection - * attempts). We then use this hook right before a remote stub gets - * deserialized, so that the client will not be able to send a DGC - * dirty call, or a DGC acknowledgment. Without the DGC ack, we - * hope that the RMI runtime will still eventually allow the remote - * object to be garbage collected. - */ - RMISocketFactory.setSocketFactory(new TestSF()); - System.err.println("test socket factory set"); + /* + * Set a socket factory that has a hook for shutting down all client + * output (writes from client-created sockets and new connection + * attempts). We then use this hook right before a remote stub gets + * deserialized, so that the client will not be able to send a DGC + * dirty call, or a DGC acknowledgment. Without the DGC ack, we + * hope that the RMI runtime will still eventually allow the remote + * object to be garbage collected. + */ + RMISocketFactory.setSocketFactory(new TestSF()); + System.err.println("test socket factory set"); - Remote impl = new DGCAckFailure(); - ReferenceQueue refQueue = new ReferenceQueue(); - Reference weakRef = new WeakReference(impl, refQueue); - ReturnRemote stub = - (ReturnRemote) UnicastRemoteObject.exportObject(impl); - System.err.println("remote object exported; stub = " + stub); + Remote impl = new DGCAckFailure(); + ReferenceQueue refQueue = new ReferenceQueue(); + Reference weakRef = new WeakReference(impl, refQueue); + ReturnRemote stub = + (ReturnRemote) UnicastRemoteObject.exportObject(impl); + System.err.println("remote object exported; stub = " + stub); - try { - Object wrappedStub = stub.returnRemote(); - System.err.println("invocation returned: " + wrappedStub); + try { + Object wrappedStub = stub.returnRemote(); + System.err.println("invocation returned: " + wrappedStub); - impl = null; - stub = null; // in case 4114579 ever gets fixed - System.err.println("strong references to impl cleared"); + impl = null; + stub = null; // in case 4114579 ever gets fixed + System.err.println("strong references to impl cleared"); - System.err.println("waiting for weak reference notification:"); - Reference ref = null; - for (int i = 0; i < 6; i++) { - System.gc(); - ref = refQueue.remove(TIMEOUT / 5); - if (ref != null) { - break; - } - } - if (ref == weakRef) { - System.err.println("TEST PASSED"); - } else { - throw new RuntimeException("TEST FAILED: " + - "timed out, remote object not garbage collected"); - } - } finally { - try { - UnicastRemoteObject.unexportObject((Remote) weakRef.get(), - true); - } catch (Exception e) { - } - } + System.err.println("waiting for weak reference notification:"); + Reference ref = null; + for (int i = 0; i < 6; i++) { + System.gc(); + ref = refQueue.remove(TIMEOUT / 5); + if (ref != null) { + break; + } + } + if (ref == weakRef) { + System.err.println("TEST PASSED"); + } else { + throw new RuntimeException("TEST FAILED: " + + "timed out, remote object not garbage collected"); + } + } finally { + try { + UnicastRemoteObject.unexportObject((Remote) weakRef.get(), + true); + } catch (Exception e) { + } + } } private static class Wrapper implements Serializable { - private final Remote obj; - Wrapper(Remote obj) { this.obj = obj; } + private final Remote obj; + Wrapper(Remote obj) { this.obj = obj; } - private void readObject(ObjectInputStream in) - throws IOException, ClassNotFoundException - { - TestSF.shutdownClientOutput(); - System.err.println( - "Wrapper.readObject: SHUTTING DOWN CLIENT OUTPUT"); - in.defaultReadObject(); - } + private void readObject(ObjectInputStream in) + throws IOException, ClassNotFoundException + { + TestSF.shutdownClientOutput(); + System.err.println( + "Wrapper.readObject: SHUTTING DOWN CLIENT OUTPUT"); + in.defaultReadObject(); + } - public String toString() { return "Wrapper[" + obj + "]"; } + public String toString() { return "Wrapper[" + obj + "]"; } } private static class TestSF extends RMISocketFactory { - private static volatile boolean shutdown = false; - static void shutdownClientOutput() { shutdown = true; } + private static volatile boolean shutdown = false; + static void shutdownClientOutput() { shutdown = true; } - public Socket createSocket(String host, int port) throws IOException { - if (shutdown) { - IOException e = new java.net.ConnectException( - "test socket factory rejecting client connection"); - System.err.println(e); -// e.printStackTrace(); - throw e; - } else { - return new TestSocket(host, port); - } - } + public Socket createSocket(String host, int port) throws IOException { + if (shutdown) { + IOException e = new java.net.ConnectException( + "test socket factory rejecting client connection"); + System.err.println(e); +// e.printStackTrace(); + throw e; + } else { + return new TestSocket(host, port); + } + } - public ServerSocket createServerSocket(int port) throws IOException { - return new ServerSocket(port); - } + public ServerSocket createServerSocket(int port) throws IOException { + return new ServerSocket(port); + } - private static class TestSocket extends Socket { - TestSocket(String host, int port) throws IOException { - super(host, port); - } - public OutputStream getOutputStream() throws IOException { - return new TestOutputStream(super.getOutputStream()); - } - } + private static class TestSocket extends Socket { + TestSocket(String host, int port) throws IOException { + super(host, port); + } + public OutputStream getOutputStream() throws IOException { + return new TestOutputStream(super.getOutputStream()); + } + } - private static class TestOutputStream extends FilterOutputStream { - TestOutputStream(OutputStream out) { super(out); } - public void write(int b) throws IOException { - if (shutdown) { - IOException e = new IOException( - "connection broken by test socket factory"); - System.err.println(e); -// e.printStackTrace(); - throw e; - } else { - super.write(b); - } - } - } + private static class TestOutputStream extends FilterOutputStream { + TestOutputStream(OutputStream out) { super(out); } + public void write(int b) throws IOException { + if (shutdown) { + IOException e = new IOException( + "connection broken by test socket factory"); + System.err.println(e); +// e.printStackTrace(); + throw e; + } else { + super.write(b); + } + } + } } } diff --git a/jdk/test/java/rmi/dgc/dgcAckFailure/DGCAckFailure_Stub.java b/jdk/test/java/rmi/dgc/dgcAckFailure/DGCAckFailure_Stub.java index 1a9ecee6bea..b5819050111 100644 --- a/jdk/test/java/rmi/dgc/dgcAckFailure/DGCAckFailure_Stub.java +++ b/jdk/test/java/rmi/dgc/dgcAckFailure/DGCAckFailure_Stub.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -29,38 +29,38 @@ public final class DGCAckFailure_Stub implements ReturnRemote { private static final long serialVersionUID = 2; - + private static java.lang.reflect.Method $method_returnRemote_0; - + static { - try { - $method_returnRemote_0 = ReturnRemote.class.getMethod("returnRemote", new java.lang.Class[] {}); - } catch (java.lang.NoSuchMethodException e) { - throw new java.lang.NoSuchMethodError( - "stub class initialization failed"); - } + try { + $method_returnRemote_0 = ReturnRemote.class.getMethod("returnRemote", new java.lang.Class[] {}); + } catch (java.lang.NoSuchMethodException e) { + throw new java.lang.NoSuchMethodError( + "stub class initialization failed"); + } } - + // constructors public DGCAckFailure_Stub(java.rmi.server.RemoteRef ref) { - super(ref); + super(ref); } - + // methods from remote interfaces - + // implementation of returnRemote() public java.lang.Object returnRemote() - throws java.rmi.RemoteException + throws java.rmi.RemoteException { - try { - Object $result = ref.invoke(this, $method_returnRemote_0, null, -8981544221566403070L); - return ((java.lang.Object) $result); - } catch (java.lang.RuntimeException e) { - throw e; - } catch (java.rmi.RemoteException e) { - throw e; - } catch (java.lang.Exception e) { - throw new java.rmi.UnexpectedException("undeclared checked exception", e); - } + try { + Object $result = ref.invoke(this, $method_returnRemote_0, null, -8981544221566403070L); + return ((java.lang.Object) $result); + } catch (java.lang.RuntimeException e) { + throw e; + } catch (java.rmi.RemoteException e) { + throw e; + } catch (java.lang.Exception e) { + throw new java.rmi.UnexpectedException("undeclared checked exception", e); + } } } diff --git a/jdk/test/java/rmi/dgc/dgcImplInsulation/DGCImplInsulation.java b/jdk/test/java/rmi/dgc/dgcImplInsulation/DGCImplInsulation.java index 83520d217b2..3f06432f352 100644 --- a/jdk/test/java/rmi/dgc/dgcImplInsulation/DGCImplInsulation.java +++ b/jdk/test/java/rmi/dgc/dgcImplInsulation/DGCImplInsulation.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 2001-2003 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -57,55 +57,55 @@ public class DGCImplInsulation implements java.rmi.Remote { public static void main(String[] args) throws Exception { - TestLibrary.suggestSecurityManager(null); + TestLibrary.suggestSecurityManager(null); - Permissions perms = new Permissions(); - perms.add(new SocketPermission("*:1024-", "listen")); - AccessControlContext acc = - new AccessControlContext(new ProtectionDomain[] { - new ProtectionDomain( - new CodeSource(null, (Certificate[]) null), perms) }); + Permissions perms = new Permissions(); + perms.add(new SocketPermission("*:1024-", "listen")); + AccessControlContext acc = + new AccessControlContext(new ProtectionDomain[] { + new ProtectionDomain( + new CodeSource(null, (Certificate[]) null), perms) }); - Remote impl = new DGCImplInsulation();; + Remote impl = new DGCImplInsulation();; - try { - Remote stub = (Remote) java.security.AccessController.doPrivileged( - new ExportAction(impl)); - System.err.println("exported remote object; local stub: " + stub); + try { + Remote stub = (Remote) java.security.AccessController.doPrivileged( + new ExportAction(impl)); + System.err.println("exported remote object; local stub: " + stub); - MarshalledObject mobj = new MarshalledObject(stub); - stub = (Remote) mobj.get(); - System.err.println("marshalled/unmarshalled stub: " + stub); + MarshalledObject mobj = new MarshalledObject(stub); + stub = (Remote) mobj.get(); + System.err.println("marshalled/unmarshalled stub: " + stub); - ReferenceQueue refQueue = new ReferenceQueue(); - Reference weakRef = new WeakReference(impl, refQueue); - impl = null; - System.gc(); - if (refQueue.remove(TIMEOUT) == weakRef) { - throw new RuntimeException( - "TEST FAILED: remote object garbage collected"); - } else { - System.err.println("TEST PASSED"); - stub = null; - System.gc(); - Thread.sleep(2000); - System.gc(); - } - } finally { - try { - UnicastRemoteObject.unexportObject(impl, true); - } catch (Exception e) { - } - } + ReferenceQueue refQueue = new ReferenceQueue(); + Reference weakRef = new WeakReference(impl, refQueue); + impl = null; + System.gc(); + if (refQueue.remove(TIMEOUT) == weakRef) { + throw new RuntimeException( + "TEST FAILED: remote object garbage collected"); + } else { + System.err.println("TEST PASSED"); + stub = null; + System.gc(); + Thread.sleep(2000); + System.gc(); + } + } finally { + try { + UnicastRemoteObject.unexportObject(impl, true); + } catch (Exception e) { + } + } } private static class ExportAction implements PrivilegedExceptionAction { - private final Remote impl; - ExportAction(Remote impl) { - this.impl = impl; - } - public Object run() throws Exception { - return UnicastRemoteObject.exportObject(impl); - } + private final Remote impl; + ExportAction(Remote impl) { + this.impl = impl; + } + public Object run() throws Exception { + return UnicastRemoteObject.exportObject(impl); + } } } diff --git a/jdk/test/java/rmi/dgc/dgcImplInsulation/DGCImplInsulation_Stub.java b/jdk/test/java/rmi/dgc/dgcImplInsulation/DGCImplInsulation_Stub.java index e77edf0948e..b73581aa1de 100644 --- a/jdk/test/java/rmi/dgc/dgcImplInsulation/DGCImplInsulation_Stub.java +++ b/jdk/test/java/rmi/dgc/dgcImplInsulation/DGCImplInsulation_Stub.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -29,10 +29,10 @@ public final class DGCImplInsulation_Stub implements java.rmi.Remote { private static final long serialVersionUID = 2; - + // constructors public DGCImplInsulation_Stub(java.rmi.server.RemoteRef ref) { - super(ref); + super(ref); } - + } diff --git a/jdk/test/java/rmi/dgc/retryDirtyCalls/RetryDirtyCalls.java b/jdk/test/java/rmi/dgc/retryDirtyCalls/RetryDirtyCalls.java index 954615d0f0b..b74931a0943 100644 --- a/jdk/test/java/rmi/dgc/retryDirtyCalls/RetryDirtyCalls.java +++ b/jdk/test/java/rmi/dgc/retryDirtyCalls/RetryDirtyCalls.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -55,108 +55,108 @@ public class RetryDirtyCalls implements Self, Unreferenced { * Return this object. The need for this method is explained below. */ public Self getSelf() { - return this; + return this; } public void unreferenced() { - synchronized (this) { - unreferenced = true; - notifyAll(); - } + synchronized (this) { + unreferenced = true; + notifyAll(); + } } public static void main(String[] args) { - System.err.println("\nRegression test for bug 4268258\n"); + System.err.println("\nRegression test for bug 4268258\n"); - /* - * Set properties to tweak DGC behavior so that this test will execute - * quickly: set the granted lease duration to 10 seconds, the interval - * that leases are checked to 3 seconds. - */ - System.setProperty("java.rmi.dgc.leaseValue", "10000"); - System.setProperty("sun.rmi.dgc.checkInterval", "3000"); + /* + * Set properties to tweak DGC behavior so that this test will execute + * quickly: set the granted lease duration to 10 seconds, the interval + * that leases are checked to 3 seconds. + */ + System.setProperty("java.rmi.dgc.leaseValue", "10000"); + System.setProperty("sun.rmi.dgc.checkInterval", "3000"); - /* - * Make idle connections time out almost instantly (0.1 seconds) so - * that the DGC implementation will have to make a new connection for - * each dirty call, thus going through the socket factory, where we - * can easily cause the operation to fail. - */ - System.setProperty("sun.rmi.transport.connectionTimeout", "100"); + /* + * Make idle connections time out almost instantly (0.1 seconds) so + * that the DGC implementation will have to make a new connection for + * each dirty call, thus going through the socket factory, where we + * can easily cause the operation to fail. + */ + System.setProperty("sun.rmi.transport.connectionTimeout", "100"); - RetryDirtyCalls impl = new RetryDirtyCalls(); + RetryDirtyCalls impl = new RetryDirtyCalls(); - try { - TestSF sf = new TestSF(); - RMISocketFactory.setSocketFactory(sf); + try { + TestSF sf = new TestSF(); + RMISocketFactory.setSocketFactory(sf); - /* - * The stub returned by UnicastRemoteObject.exportObject() does - * not participate in DGC, but it does allow us to invoke a method - * on the remote object through RMI. Therefore, we invoke the - * getSelf() method through RMI, which returns an equivalent stub - * that does participate in DGC. - */ - Self stub = (Self) UnicastRemoteObject.exportObject(impl); - Self dgcStub = stub.getSelf(); - stub = null; // in case 4114579 has been fixed + /* + * The stub returned by UnicastRemoteObject.exportObject() does + * not participate in DGC, but it does allow us to invoke a method + * on the remote object through RMI. Therefore, we invoke the + * getSelf() method through RMI, which returns an equivalent stub + * that does participate in DGC. + */ + Self stub = (Self) UnicastRemoteObject.exportObject(impl); + Self dgcStub = stub.getSelf(); + stub = null; // in case 4114579 has been fixed - /* - * Set the socket factory to cause 3 connections attempts in a row - * to fail before allowing a connection to succeed, expecting the - * client-side DGC implementation to make at least four attempts. - */ - final int FLAKE_FACTOR = 3; - sf.setFlakeFactor(FLAKE_FACTOR); + /* + * Set the socket factory to cause 3 connections attempts in a row + * to fail before allowing a connection to succeed, expecting the + * client-side DGC implementation to make at least four attempts. + */ + final int FLAKE_FACTOR = 3; + sf.setFlakeFactor(FLAKE_FACTOR); - long deadline = System.currentTimeMillis() + TIMEOUT; - boolean unreferenced; + long deadline = System.currentTimeMillis() + TIMEOUT; + boolean unreferenced; - synchronized (impl) { - while (!(unreferenced = impl.unreferenced)) { - long timeToWait = deadline - System.currentTimeMillis(); - if (timeToWait > 0) { - impl.wait(timeToWait); - } else { - break; - } - } - } + synchronized (impl) { + while (!(unreferenced = impl.unreferenced)) { + long timeToWait = deadline - System.currentTimeMillis(); + if (timeToWait > 0) { + impl.wait(timeToWait); + } else { + break; + } + } + } - if (unreferenced) { - throw new RuntimeException("remote object unreferenced"); - } + if (unreferenced) { + throw new RuntimeException("remote object unreferenced"); + } - int createCount = sf.getCreateCount(); - if (createCount == 0) { - throw new RuntimeException("test socket factory never used"); - } else if (createCount < (FLAKE_FACTOR + 3)) { - /* - * The unreferenced method was not invoked for some reason, - * but the dirty calls were clearly not retried well enough. - */ - throw new RuntimeException( - "test failed because dirty calls not retried enough, " + - "but remote object not unreferenced"); - } + int createCount = sf.getCreateCount(); + if (createCount == 0) { + throw new RuntimeException("test socket factory never used"); + } else if (createCount < (FLAKE_FACTOR + 3)) { + /* + * The unreferenced method was not invoked for some reason, + * but the dirty calls were clearly not retried well enough. + */ + throw new RuntimeException( + "test failed because dirty calls not retried enough, " + + "but remote object not unreferenced"); + } - System.err.println( - "TEST PASSED: remote object not unreferenced"); + System.err.println( + "TEST PASSED: remote object not unreferenced"); - } catch (Exception e) { - e.printStackTrace(); - throw new RuntimeException("TEST FAILED: " + e.toString()); - } finally { - /* - * When all is said and done, try to unexport the remote object - * so that the VM has a chance to exit. - */ - try { - UnicastRemoteObject.unexportObject(impl, true); - } catch (Exception e) { - } - } + } catch (Exception e) { + e.printStackTrace(); + throw new RuntimeException("TEST FAILED: " + e.toString()); + } finally { + /* + * When all is said and done, try to unexport the remote object + * so that the VM has a chance to exit. + */ + try { + UnicastRemoteObject.unexportObject(impl, true); + } catch (Exception e) { + } + } } } @@ -169,30 +169,30 @@ class TestSF extends RMISocketFactory { private int createCount = 0; public synchronized void setFlakeFactor(int newFlakeFactor) { - flakeFactor = newFlakeFactor; + flakeFactor = newFlakeFactor; } public synchronized int getCreateCount() { - return createCount; + return createCount; } public synchronized Socket createSocket(String host, int port) - throws IOException + throws IOException { - createCount++; + createCount++; - if (++flakeState > flakeFactor) { - flakeState = 0; - } + if (++flakeState > flakeFactor) { + flakeState = 0; + } - if (flakeState == 0) { - return new Socket(host, port); - } else { - throw new IOException("random network failure"); - } + if (flakeState == 0) { + return new Socket(host, port); + } else { + throw new IOException("random network failure"); + } } public ServerSocket createServerSocket(int port) throws IOException { - return new ServerSocket(port); + return new ServerSocket(port); } } diff --git a/jdk/test/java/rmi/dgc/retryDirtyCalls/RetryDirtyCalls_Stub.java b/jdk/test/java/rmi/dgc/retryDirtyCalls/RetryDirtyCalls_Stub.java index 4007980eff6..f35e8dccbef 100644 --- a/jdk/test/java/rmi/dgc/retryDirtyCalls/RetryDirtyCalls_Stub.java +++ b/jdk/test/java/rmi/dgc/retryDirtyCalls/RetryDirtyCalls_Stub.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -29,38 +29,38 @@ public final class RetryDirtyCalls_Stub implements Self { private static final long serialVersionUID = 2; - + private static java.lang.reflect.Method $method_getSelf_0; - + static { - try { - $method_getSelf_0 = Self.class.getMethod("getSelf", new java.lang.Class[] {}); - } catch (java.lang.NoSuchMethodException e) { - throw new java.lang.NoSuchMethodError( - "stub class initialization failed"); - } + try { + $method_getSelf_0 = Self.class.getMethod("getSelf", new java.lang.Class[] {}); + } catch (java.lang.NoSuchMethodException e) { + throw new java.lang.NoSuchMethodError( + "stub class initialization failed"); + } } - + // constructors public RetryDirtyCalls_Stub(java.rmi.server.RemoteRef ref) { - super(ref); + super(ref); } - + // methods from remote interfaces - + // implementation of getSelf() public Self getSelf() - throws java.rmi.RemoteException + throws java.rmi.RemoteException { - try { - Object $result = ref.invoke(this, $method_getSelf_0, null, 2868857108246021904L); - return ((Self) $result); - } catch (java.lang.RuntimeException e) { - throw e; - } catch (java.rmi.RemoteException e) { - throw e; - } catch (java.lang.Exception e) { - throw new java.rmi.UnexpectedException("undeclared checked exception", e); - } + try { + Object $result = ref.invoke(this, $method_getSelf_0, null, 2868857108246021904L); + return ((Self) $result); + } catch (java.lang.RuntimeException e) { + throw e; + } catch (java.rmi.RemoteException e) { + throw e; + } catch (java.lang.Exception e) { + throw new java.rmi.UnexpectedException("undeclared checked exception", e); + } } } diff --git a/jdk/test/java/rmi/registry/altSecurityManager/AltSecurityManager.java b/jdk/test/java/rmi/registry/altSecurityManager/AltSecurityManager.java index 56234cfb3a7..4263351b2fb 100644 --- a/jdk/test/java/rmi/registry/altSecurityManager/AltSecurityManager.java +++ b/jdk/test/java/rmi/registry/altSecurityManager/AltSecurityManager.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1999-2007 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -26,8 +26,8 @@ * @summary rmid and rmiregistry could allow alternate security manager * @author Laird Dornin * - * @library ../../testlibrary - * @build StreamPipe TestParams TestLibrary JavaVM + * @library ../../testlibrary + * @build StreamPipe TestParams TestLibrary JavaVM * @build AltSecurityManager TestSecurityManager * @run main/othervm AltSecurityManager */ @@ -38,7 +38,7 @@ * that throws a runtime exception in its checkListen method, this * will cause rmiregistry and rmid to exit early because those * utilities will be unable to export any remote objects; test fails - * if registry and rmid take too long to exit. + * if registry and rmid take too long to exit. */ public class AltSecurityManager implements Runnable { @@ -54,74 +54,74 @@ public class AltSecurityManager implements Runnable { static long TIME_OUT = 15000; public void run() { - try { - vm = new JavaVM(utilityToStart, - " -Djava.security.manager=TestSecurityManager", - ""); - System.err.println("starting " + utilityToStart); - vm.start(); - vm.getVM().waitFor(); + try { + vm = new JavaVM(utilityToStart, + " -Djava.security.manager=TestSecurityManager", + ""); + System.err.println("starting " + utilityToStart); + vm.start(); + vm.getVM().waitFor(); - } catch (Exception e) { - TestLibrary.bomb(e); - } + } catch (Exception e) { + TestLibrary.bomb(e); + } } - + /** * Wait to make sure that the registry and rmid exit after * their security manager is set. */ public static void ensureExit(String utility) throws Exception { - utilityToStart = utility; - - try { - Thread thread = new Thread(new AltSecurityManager()); - System.err.println("expecting RuntimeException for " + - "checkListen in child process"); - long start = System.currentTimeMillis(); - thread.start(); - thread.join(TIME_OUT); - - long time = System.currentTimeMillis() - start; - System.err.println("waited " + time + " millis for " + - utilityToStart + " to die"); + utilityToStart = utility; - if (time >= TIME_OUT) { - - // dont pollute other tests; increase the likelihood + try { + Thread thread = new Thread(new AltSecurityManager()); + System.err.println("expecting RuntimeException for " + + "checkListen in child process"); + long start = System.currentTimeMillis(); + thread.start(); + thread.join(TIME_OUT); + + long time = System.currentTimeMillis() - start; + System.err.println("waited " + time + " millis for " + + utilityToStart + " to die"); + + if (time >= TIME_OUT) { + + // dont pollute other tests; increase the likelihood // that rmid will go away if it did not exit already. - if (utility.equals(rmid)) { - RMID.shutdown(); - } - - TestLibrary.bomb(utilityToStart + - " took too long to die..."); - } else { - System.err.println(utilityToStart + - " terminated on time"); - } - } finally { - vm.destroy(); - vm = null; - } + if (utility.equals(rmid)) { + RMID.shutdown(); + } + + TestLibrary.bomb(utilityToStart + + " took too long to die..."); + } else { + System.err.println(utilityToStart + + " terminated on time"); + } + } finally { + vm.destroy(); + vm = null; + } } - + public static void main(String[] args) { - try { - System.err.println("\nRegression test for bug 4183202\n"); + try { + System.err.println("\nRegression test for bug 4183202\n"); - // make sure the registry exits early. - ensureExit(registry); + // make sure the registry exits early. + ensureExit(registry); - // make sure rmid exits early - ensureExit(rmid); + // make sure rmid exits early + ensureExit(rmid); - System.err.println("test passed"); + System.err.println("test passed"); - } catch (Exception e) { - TestLibrary.bomb(e); - } finally { - RMID.removeLog(); - } + } catch (Exception e) { + TestLibrary.bomb(e); + } finally { + RMID.removeLog(); + } } } diff --git a/jdk/test/java/rmi/registry/altSecurityManager/TestSecurityManager.java b/jdk/test/java/rmi/registry/altSecurityManager/TestSecurityManager.java index 4619540b0dd..5d9e16253d0 100644 --- a/jdk/test/java/rmi/registry/altSecurityManager/TestSecurityManager.java +++ b/jdk/test/java/rmi/registry/altSecurityManager/TestSecurityManager.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -28,18 +28,18 @@ public class TestSecurityManager extends SecurityManager { } public void checkListen(int port) { - // 4269910: ok, now rmid and the regsitry will *really* go - // away... - // - // rmid and the registry need to listen on sockets so they - // will exit when they try to do so... this is used as a sign - // by the main test process to detect that the proper security - // manager has been installed in the relevant VMs. - // - System.exit(1); + // 4269910: ok, now rmid and the regsitry will *really* go + // away... + // + // rmid and the registry need to listen on sockets so they + // will exit when they try to do so... this is used as a sign + // by the main test process to detect that the proper security + // manager has been installed in the relevant VMs. + // + System.exit(1); } public void checkExit(int status) { - // permit check exit for all code + // permit check exit for all code } } diff --git a/jdk/test/java/rmi/registry/checkusage/CheckUsage.java b/jdk/test/java/rmi/registry/checkusage/CheckUsage.java index dbf9a9517e3..37556efb820 100644 --- a/jdk/test/java/rmi/registry/checkusage/CheckUsage.java +++ b/jdk/test/java/rmi/registry/checkusage/CheckUsage.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -36,48 +36,48 @@ import java.io.ByteArrayOutputStream; /** * Make sure that the rmiregistry prints out a correct usage statement * when run with an incorrect command line; test written to conform to - * new tighter bug fix/regression test guidelines. + * new tighter bug fix/regression test guidelines. */ public class CheckUsage { public static void main(String[] args) { - System.err.println("\nregression test for 4151966\n"); + System.err.println("\nregression test for 4151966\n"); - JavaVM registryVM = null; + JavaVM registryVM = null; - try { - // make sure the registry exits with a proper usage statement - ByteArrayOutputStream berr = new ByteArrayOutputStream(); - - // run a VM to start the registry - registryVM = new JavaVM("sun.rmi.registry.RegistryImpl", - "", "foo", - System.out, berr); - System.err.println("starting registry"); - registryVM.start(); - - // wait for registry exit - System.err.println(" registry exited with status: " + - registryVM.getVM().waitFor()); - try { - Thread.sleep(7000); - } catch (InterruptedException ie) { - } - - String usage = new String(berr.toByteArray()); - - System.err.println("rmiregistry usage: " + usage); - - if (usage.indexOf("-J") < 0) { - TestLibrary.bomb("rmiregistry has incorrect usage statement"); - } else { - System.err.println("test passed"); - } - } catch (Exception e) { - TestLibrary.bomb(e); - } finally { - registryVM.destroy(); - registryVM = null; - } + try { + // make sure the registry exits with a proper usage statement + ByteArrayOutputStream berr = new ByteArrayOutputStream(); + + // run a VM to start the registry + registryVM = new JavaVM("sun.rmi.registry.RegistryImpl", + "", "foo", + System.out, berr); + System.err.println("starting registry"); + registryVM.start(); + + // wait for registry exit + System.err.println(" registry exited with status: " + + registryVM.getVM().waitFor()); + try { + Thread.sleep(7000); + } catch (InterruptedException ie) { + } + + String usage = new String(berr.toByteArray()); + + System.err.println("rmiregistry usage: " + usage); + + if (usage.indexOf("-J") < 0) { + TestLibrary.bomb("rmiregistry has incorrect usage statement"); + } else { + System.err.println("test passed"); + } + } catch (Exception e) { + TestLibrary.bomb(e); + } finally { + registryVM.destroy(); + registryVM = null; + } } } diff --git a/jdk/test/java/rmi/registry/classPathCodebase/ClassPathCodebase.java b/jdk/test/java/rmi/registry/classPathCodebase/ClassPathCodebase.java index f94ff8696a9..ad7ba02d35d 100644 --- a/jdk/test/java/rmi/registry/classPathCodebase/ClassPathCodebase.java +++ b/jdk/test/java/rmi/registry/classPathCodebase/ClassPathCodebase.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1999-2004 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -55,121 +55,121 @@ public class ClassPathCodebase { public static void main(String[] args) { - System.err.println("\nRegression test for bug 4242317\n"); + System.err.println("\nRegression test for bug 4242317\n"); - TestLibrary.suggestSecurityManager("java.lang.SecurityManager"); + TestLibrary.suggestSecurityManager("java.lang.SecurityManager"); - Process rmiregistry = null; + Process rmiregistry = null; - try { - /* - * Install a dummy class in two codebases: one that will be in - * the rmiregistry's CLASSPATH (the "import" codebase) and one - * that will be in the rmiregistry's "java.rmi.server.codebase" - * property (the "export" codebase). - */ - URL importCodebaseURL = TestLibrary.installClassInCodebase( - dummyClassName, importCodebase, false); - URL exportCodebaseURL = TestLibrary.installClassInCodebase( - dummyClassName, exportCodebase, true); + try { + /* + * Install a dummy class in two codebases: one that will be in + * the rmiregistry's CLASSPATH (the "import" codebase) and one + * that will be in the rmiregistry's "java.rmi.server.codebase" + * property (the "export" codebase). + */ + URL importCodebaseURL = TestLibrary.installClassInCodebase( + dummyClassName, importCodebase, false); + URL exportCodebaseURL = TestLibrary.installClassInCodebase( + dummyClassName, exportCodebase, true); - /* - * Spawn an rmiregistry in the "import" codebase directory. - */ - File rmiregistryDir = - new File(System.getProperty("user.dir", "."), importCodebase); + /* + * Spawn an rmiregistry in the "import" codebase directory. + */ + File rmiregistryDir = + new File(System.getProperty("user.dir", "."), importCodebase); - String rmiregistryCommand = - System.getProperty("java.home") + File.separator + - "bin" + File.separator + "rmiregistry"; - - String cmdarray[] = new String[] { - rmiregistryCommand, - "-J-Denv.class.path=.", - "-J-Djava.rmi.server.codebase=" + exportCodebaseURL, - Integer.toString(TestLibrary.REGISTRY_PORT) }; + String rmiregistryCommand = + System.getProperty("java.home") + File.separator + + "bin" + File.separator + "rmiregistry"; - System.err.println("\nCommand used to spawn rmiregistry process:"); - System.err.println("\t" + Arrays.asList(cmdarray).toString()); + String cmdarray[] = new String[] { + rmiregistryCommand, + "-J-Denv.class.path=.", + "-J-Djava.rmi.server.codebase=" + exportCodebaseURL, + Integer.toString(TestLibrary.REGISTRY_PORT) }; - rmiregistry = Runtime.getRuntime().exec(cmdarray, null, rmiregistryDir); + System.err.println("\nCommand used to spawn rmiregistry process:"); + System.err.println("\t" + Arrays.asList(cmdarray).toString()); - // pipe rmiregistry output to our output, for debugging failures - StreamPipe.plugTogether(rmiregistry.getInputStream(), System.err); - StreamPipe.plugTogether(rmiregistry.getErrorStream(), System.err); + rmiregistry = Runtime.getRuntime().exec(cmdarray, null, rmiregistryDir); - /* - * Wait for the registry to initialize and be ready to call. - */ - Thread.sleep(REGISTRY_WAIT); - System.err.println(); + // pipe rmiregistry output to our output, for debugging failures + StreamPipe.plugTogether(rmiregistry.getInputStream(), System.err); + StreamPipe.plugTogether(rmiregistry.getErrorStream(), System.err); - /* - * Create an instance of the dummy class, finding it from the - * "import" codebase. - */ - ClassLoader loader = URLClassLoader.newInstance( - new URL[] { importCodebaseURL }); - Class dummyClass = Class.forName(dummyClassName, false, loader); - Remote dummyObject = (Remote) dummyClass.newInstance(); + /* + * Wait for the registry to initialize and be ready to call. + */ + Thread.sleep(REGISTRY_WAIT); + System.err.println(); - /* - * Find the registry that we created and bind the - * dummy object to it. - */ - Registry registry = LocateRegistry.getRegistry( - "localhost", TestLibrary.REGISTRY_PORT); + /* + * Create an instance of the dummy class, finding it from the + * "import" codebase. + */ + ClassLoader loader = URLClassLoader.newInstance( + new URL[] { importCodebaseURL }); + Class dummyClass = Class.forName(dummyClassName, false, loader); + Remote dummyObject = (Remote) dummyClass.newInstance(); - try { - registry.bind(dummyBinding, dummyObject); - System.err.println("Bound dummy object in registry"); - } catch (java.rmi.ConnectException e) { - System.err.println("Error: rmiregistry not started in time"); - throw e; - } catch (ServerException e) { - if (e.detail instanceof UnmarshalException && - ((UnmarshalException) e.detail).detail instanceof - ClassNotFoundException) - { - System.err.println( - "Error: another registry running on port " + - TestLibrary.REGISTRY_PORT + "?"); - } - throw e; - } + /* + * Find the registry that we created and bind the + * dummy object to it. + */ + Registry registry = LocateRegistry.getRegistry( + "localhost", TestLibrary.REGISTRY_PORT); - /* - * Look up the dummy object from our registry and make sure - * that its class was annotated with the "export" codebase. - */ - Remote dummyLookup = registry.lookup(dummyBinding); - System.err.println( - "Looked up dummy object from registry: " + dummyLookup); - Class dummyLookupClass = dummyLookup.getClass(); - String dummyLookupAnnotation = - RMIClassLoader.getClassAnnotation(dummyLookupClass); - System.err.println( - "Class annotation from registry: " + dummyLookupAnnotation); + try { + registry.bind(dummyBinding, dummyObject); + System.err.println("Bound dummy object in registry"); + } catch (java.rmi.ConnectException e) { + System.err.println("Error: rmiregistry not started in time"); + throw e; + } catch (ServerException e) { + if (e.detail instanceof UnmarshalException && + ((UnmarshalException) e.detail).detail instanceof + ClassNotFoundException) + { + System.err.println( + "Error: another registry running on port " + + TestLibrary.REGISTRY_PORT + "?"); + } + throw e; + } - System.err.println(); - if (dummyLookupAnnotation.indexOf(exportCodebase) >= 0) { - System.err.println("TEST PASSED"); - } else if (dummyLookupAnnotation.indexOf(importCodebase) >= 0) { - throw new RuntimeException( - "rmiregistry annotated with CLASSPATH element URL"); - } else { - throw new RuntimeException( - "rmiregistry used unexpected annotation: \"" + - dummyLookupAnnotation + "\""); - } + /* + * Look up the dummy object from our registry and make sure + * that its class was annotated with the "export" codebase. + */ + Remote dummyLookup = registry.lookup(dummyBinding); + System.err.println( + "Looked up dummy object from registry: " + dummyLookup); + Class dummyLookupClass = dummyLookup.getClass(); + String dummyLookupAnnotation = + RMIClassLoader.getClassAnnotation(dummyLookupClass); + System.err.println( + "Class annotation from registry: " + dummyLookupAnnotation); - } catch (Exception e) { - e.printStackTrace(); - throw new RuntimeException("TEST FAILED: " + e.toString()); - } finally { - if (rmiregistry != null) { - rmiregistry.destroy(); - } - } + System.err.println(); + if (dummyLookupAnnotation.indexOf(exportCodebase) >= 0) { + System.err.println("TEST PASSED"); + } else if (dummyLookupAnnotation.indexOf(importCodebase) >= 0) { + throw new RuntimeException( + "rmiregistry annotated with CLASSPATH element URL"); + } else { + throw new RuntimeException( + "rmiregistry used unexpected annotation: \"" + + dummyLookupAnnotation + "\""); + } + + } catch (Exception e) { + e.printStackTrace(); + throw new RuntimeException("TEST FAILED: " + e.toString()); + } finally { + if (rmiregistry != null) { + rmiregistry.destroy(); + } + } } } diff --git a/jdk/test/java/rmi/registry/classPathCodebase/Dummy.java b/jdk/test/java/rmi/registry/classPathCodebase/Dummy.java index 9b57cf18cf4..ad40244578a 100644 --- a/jdk/test/java/rmi/registry/classPathCodebase/Dummy.java +++ b/jdk/test/java/rmi/registry/classPathCodebase/Dummy.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -36,12 +36,12 @@ public class Dummy } public void writeExternal(java.io.ObjectOutput out) - throws java.io.IOException + throws java.io.IOException { } public void readExternal(java.io.ObjectInput in) - throws java.io.IOException, ClassNotFoundException + throws java.io.IOException, ClassNotFoundException { } } diff --git a/jdk/test/java/rmi/registry/emptyName/EmptyName.java b/jdk/test/java/rmi/registry/emptyName/EmptyName.java index fd6cf64a913..7507dc7fa63 100644 --- a/jdk/test/java/rmi/registry/emptyName/EmptyName.java +++ b/jdk/test/java/rmi/registry/emptyName/EmptyName.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -32,12 +32,12 @@ import java.rmi.server.RemoteObject; public class EmptyName { public static void main(String[] args) throws Exception { - Registry impl = LocateRegistry.createRegistry(0); - Registry stub = (Registry) RemoteObject.toStub(impl); - stub.bind("", stub); - stub.lookup(""); - stub.rebind("", stub); - stub.lookup(""); - stub.unbind(""); + Registry impl = LocateRegistry.createRegistry(0); + Registry stub = (Registry) RemoteObject.toStub(impl); + stub.bind("", stub); + stub.lookup(""); + stub.rebind("", stub); + stub.lookup(""); + stub.unbind(""); } } diff --git a/jdk/test/java/rmi/registry/interfaceHash/InterfaceHash.java b/jdk/test/java/rmi/registry/interfaceHash/InterfaceHash.java index 011022e753f..8ab80dd26f3 100644 --- a/jdk/test/java/rmi/registry/interfaceHash/InterfaceHash.java +++ b/jdk/test/java/rmi/registry/interfaceHash/InterfaceHash.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -62,157 +62,157 @@ public class InterfaceHash { private static final String NAME = "WMM"; public static void main(String[] args) throws Exception { - System.err.println("\nRegression test for bug 4472769"); + System.err.println("\nRegression test for bug 4472769"); - System.err.println( - "\n=== verifying that J2SE registry's skeleton uses" + - "\ncorrect interface hash and operation numbers:"); + System.err.println( + "\n=== verifying that J2SE registry's skeleton uses" + + "\ncorrect interface hash and operation numbers:"); - Registry testImpl = LocateRegistry.createRegistry(PORT); - System.err.println("created test registry on port " + PORT); + Registry testImpl = LocateRegistry.createRegistry(PORT); + System.err.println("created test registry on port " + PORT); - RemoteRef ref = new UnicastRef( - new LiveRef(new ObjID(ObjID.REGISTRY_ID), - new TCPEndpoint("", PORT), false)); - Registry referenceStub = new ReferenceRegistryStub(ref); - System.err.println("created reference registry stub: " + - referenceStub); + RemoteRef ref = new UnicastRef( + new LiveRef(new ObjID(ObjID.REGISTRY_ID), + new TCPEndpoint("", PORT), false)); + Registry referenceStub = new ReferenceRegistryStub(ref); + System.err.println("created reference registry stub: " + + referenceStub); - referenceStub.bind(NAME, referenceStub); - System.err.println("bound name \"" + NAME + "\" in registry"); + referenceStub.bind(NAME, referenceStub); + System.err.println("bound name \"" + NAME + "\" in registry"); - String[] list = referenceStub.list(); - System.err.println("list of registry contents: " + - Arrays.asList(list)); - if (list.length != 1 || !list[0].equals(NAME)) { - throw new RuntimeException( - "TEST FAILED: unexpected list contents"); - } + String[] list = referenceStub.list(); + System.err.println("list of registry contents: " + + Arrays.asList(list)); + if (list.length != 1 || !list[0].equals(NAME)) { + throw new RuntimeException( + "TEST FAILED: unexpected list contents"); + } - Registry result = (Registry) referenceStub.lookup(NAME); - System.err.println("lookup of name \"" + NAME + "\" returned: " + - result); - if (!result.equals(referenceStub)) { - throw new RuntimeException( - "TEST FAILED: unexpected lookup result"); - } + Registry result = (Registry) referenceStub.lookup(NAME); + System.err.println("lookup of name \"" + NAME + "\" returned: " + + result); + if (!result.equals(referenceStub)) { + throw new RuntimeException( + "TEST FAILED: unexpected lookup result"); + } - referenceStub.rebind(NAME, referenceStub); - referenceStub.unbind(NAME); - System.err.println("unbound name \"" + NAME + "\""); + referenceStub.rebind(NAME, referenceStub); + referenceStub.unbind(NAME); + System.err.println("unbound name \"" + NAME + "\""); - list = referenceStub.list(); - System.err.println("list of registry contents: " + - Arrays.asList(list)); - if (list.length != 0) { - throw new RuntimeException("TEST FAILED: list not empty"); - } + list = referenceStub.list(); + System.err.println("list of registry contents: " + + Arrays.asList(list)); + if (list.length != 0) { + throw new RuntimeException("TEST FAILED: list not empty"); + } - System.err.println("\n=== verifying that J2SE registry's stub uses" + - "correct interface hash:"); + System.err.println("\n=== verifying that J2SE registry's stub uses" + + "correct interface hash:"); - class FakeRemoteRef implements RemoteRef { - long hash; - int opnum; - public RemoteCall newCall(RemoteObject obj, Operation[] op, - int opnum, long hash) - { - this.hash = hash; - this.opnum = opnum; - throw new UnsupportedOperationException(); - } - public void invoke(RemoteCall call) { } - public void done(RemoteCall call) { } - public Object invoke(Remote obj, Method method, - Object[] args, long hash) - { - throw new UnsupportedOperationException(); - } - public String getRefClass(java.io.ObjectOutput out) { - return "FakeRemoteRef"; - } - public int remoteHashCode() { return 1013; } - public boolean remoteEquals(RemoteRef obj) { return false; } - public String remoteToString() { return "FakeRemoteRef"; } - public void writeExternal(java.io.ObjectOutput out) { } - public void readExternal(java.io.ObjectInput in) { } - } - FakeRemoteRef f = new FakeRemoteRef(); + class FakeRemoteRef implements RemoteRef { + long hash; + int opnum; + public RemoteCall newCall(RemoteObject obj, Operation[] op, + int opnum, long hash) + { + this.hash = hash; + this.opnum = opnum; + throw new UnsupportedOperationException(); + } + public void invoke(RemoteCall call) { } + public void done(RemoteCall call) { } + public Object invoke(Remote obj, Method method, + Object[] args, long hash) + { + throw new UnsupportedOperationException(); + } + public String getRefClass(java.io.ObjectOutput out) { + return "FakeRemoteRef"; + } + public int remoteHashCode() { return 1013; } + public boolean remoteEquals(RemoteRef obj) { return false; } + public String remoteToString() { return "FakeRemoteRef"; } + public void writeExternal(java.io.ObjectOutput out) { } + public void readExternal(java.io.ObjectInput in) { } + } + FakeRemoteRef f = new FakeRemoteRef(); - Registry testRegistry = LocateRegistry.getRegistry(PORT); - System.err.println("created original test registry stub: " + - testRegistry); + Registry testRegistry = LocateRegistry.getRegistry(PORT); + System.err.println("created original test registry stub: " + + testRegistry); - Class stubClass = testRegistry.getClass(); - System.err.println("test registry stub class: " + stubClass); + Class stubClass = testRegistry.getClass(); + System.err.println("test registry stub class: " + stubClass); - Constructor cons = stubClass.getConstructor( - new Class[] { RemoteRef.class }); - Registry testStub = (Registry) cons.newInstance( - new Object[] { f }); - System.err.println("created new instrumented test registry stub: " + - testStub); + Constructor cons = stubClass.getConstructor( + new Class[] { RemoteRef.class }); + Registry testStub = (Registry) cons.newInstance( + new Object[] { f }); + System.err.println("created new instrumented test registry stub: " + + testStub); - System.err.println("invoking bind:"); - try { - testStub.bind(NAME, referenceStub); - } catch (UnsupportedOperationException e) { - } - System.err.println("hash == " + f.hash + ", opnum == " + f.opnum); - if (f.hash != 4905912898345647071L) { - throw new RuntimeException("TEST FAILED: wrong interface hash"); - } else if (f.opnum != 0) { - throw new RuntimeException("TEST FAILED: wrong operation number"); - } + System.err.println("invoking bind:"); + try { + testStub.bind(NAME, referenceStub); + } catch (UnsupportedOperationException e) { + } + System.err.println("hash == " + f.hash + ", opnum == " + f.opnum); + if (f.hash != 4905912898345647071L) { + throw new RuntimeException("TEST FAILED: wrong interface hash"); + } else if (f.opnum != 0) { + throw new RuntimeException("TEST FAILED: wrong operation number"); + } - System.err.println("invoking list:"); - try { - testStub.list(); - } catch (UnsupportedOperationException e) { - } - System.err.println("hash == " + f.hash + ", opnum == " + f.opnum); - if (f.hash != 4905912898345647071L) { - throw new RuntimeException("TEST FAILED: wrong interface hash"); - } else if (f.opnum != 1) { - throw new RuntimeException("TEST FAILED: wrong operation number"); - } + System.err.println("invoking list:"); + try { + testStub.list(); + } catch (UnsupportedOperationException e) { + } + System.err.println("hash == " + f.hash + ", opnum == " + f.opnum); + if (f.hash != 4905912898345647071L) { + throw new RuntimeException("TEST FAILED: wrong interface hash"); + } else if (f.opnum != 1) { + throw new RuntimeException("TEST FAILED: wrong operation number"); + } - System.err.println("invoking lookup:"); - try { - testStub.lookup(NAME); - } catch (UnsupportedOperationException e) { - } - System.err.println("hash == " + f.hash + ", opnum == " + f.opnum); - if (f.hash != 4905912898345647071L) { - throw new RuntimeException("TEST FAILED: wrong interface hash"); - } else if (f.opnum != 2) { - throw new RuntimeException("TEST FAILED: wrong operation number"); - } + System.err.println("invoking lookup:"); + try { + testStub.lookup(NAME); + } catch (UnsupportedOperationException e) { + } + System.err.println("hash == " + f.hash + ", opnum == " + f.opnum); + if (f.hash != 4905912898345647071L) { + throw new RuntimeException("TEST FAILED: wrong interface hash"); + } else if (f.opnum != 2) { + throw new RuntimeException("TEST FAILED: wrong operation number"); + } - System.err.println("invoking rebind:"); - try { - testStub.rebind(NAME, referenceStub); - } catch (UnsupportedOperationException e) { - } - System.err.println("hash == " + f.hash + ", opnum == " + f.opnum); - if (f.hash != 4905912898345647071L) { - throw new RuntimeException("TEST FAILED: wrong interface hash"); - } else if (f.opnum != 3) { - throw new RuntimeException("TEST FAILED: wrong operation number"); - } + System.err.println("invoking rebind:"); + try { + testStub.rebind(NAME, referenceStub); + } catch (UnsupportedOperationException e) { + } + System.err.println("hash == " + f.hash + ", opnum == " + f.opnum); + if (f.hash != 4905912898345647071L) { + throw new RuntimeException("TEST FAILED: wrong interface hash"); + } else if (f.opnum != 3) { + throw new RuntimeException("TEST FAILED: wrong operation number"); + } - System.err.println("invoking unbind:"); - try { - testStub.unbind(NAME); - } catch (UnsupportedOperationException e) { - } - System.err.println("hash == " + f.hash + ", opnum == " + f.opnum); - if (f.hash != 4905912898345647071L) { - throw new RuntimeException("TEST FAILED: wrong interface hash"); - } else if (f.opnum != 4) { - throw new RuntimeException("TEST FAILED: wrong operation number"); - } + System.err.println("invoking unbind:"); + try { + testStub.unbind(NAME); + } catch (UnsupportedOperationException e) { + } + System.err.println("hash == " + f.hash + ", opnum == " + f.opnum); + if (f.hash != 4905912898345647071L) { + throw new RuntimeException("TEST FAILED: wrong interface hash"); + } else if (f.opnum != 4) { + throw new RuntimeException("TEST FAILED: wrong operation number"); + } - System.err.println("TEST PASSED"); + System.err.println("TEST PASSED"); } } diff --git a/jdk/test/java/rmi/registry/interfaceHash/ReferenceRegistryStub.java b/jdk/test/java/rmi/registry/interfaceHash/ReferenceRegistryStub.java index 2e4a1df143d..9db88da5939 100644 --- a/jdk/test/java/rmi/registry/interfaceHash/ReferenceRegistryStub.java +++ b/jdk/test/java/rmi/registry/interfaceHash/ReferenceRegistryStub.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -26,161 +26,161 @@ public final class ReferenceRegistryStub implements java.rmi.registry.Registry, java.rmi.Remote { private static final java.rmi.server.Operation[] operations = { - new java.rmi.server.Operation("void bind(java.lang.String, java.rmi.Remote)"), - new java.rmi.server.Operation("java.lang.String list()[]"), - new java.rmi.server.Operation("java.rmi.Remote lookup(java.lang.String)"), - new java.rmi.server.Operation("void rebind(java.lang.String, java.rmi.Remote)"), - new java.rmi.server.Operation("void unbind(java.lang.String)") + new java.rmi.server.Operation("void bind(java.lang.String, java.rmi.Remote)"), + new java.rmi.server.Operation("java.lang.String list()[]"), + new java.rmi.server.Operation("java.rmi.Remote lookup(java.lang.String)"), + new java.rmi.server.Operation("void rebind(java.lang.String, java.rmi.Remote)"), + new java.rmi.server.Operation("void unbind(java.lang.String)") }; - + private static final long interfaceHash = 4905912898345647071L; - + // constructors public ReferenceRegistryStub() { - super(); + super(); } public ReferenceRegistryStub(java.rmi.server.RemoteRef ref) { - super(ref); + super(ref); } - + // methods from remote interfaces - + // implementation of bind(String, Remote) public void bind(java.lang.String $param_String_1, java.rmi.Remote $param_Remote_2) - throws java.rmi.AccessException, java.rmi.AlreadyBoundException, java.rmi.RemoteException + throws java.rmi.AccessException, java.rmi.AlreadyBoundException, java.rmi.RemoteException { - try { - java.rmi.server.RemoteCall call = ref.newCall((java.rmi.server.RemoteObject) this, operations, 0, interfaceHash); - try { - java.io.ObjectOutput out = call.getOutputStream(); - out.writeObject($param_String_1); - out.writeObject($param_Remote_2); - } catch (java.io.IOException e) { - throw new java.rmi.MarshalException("error marshalling arguments", e); - } - ref.invoke(call); - ref.done(call); - } catch (java.lang.RuntimeException e) { - throw e; - } catch (java.rmi.RemoteException e) { - throw e; - } catch (java.rmi.AlreadyBoundException e) { - throw e; - } catch (java.lang.Exception e) { - throw new java.rmi.UnexpectedException("undeclared checked exception", e); - } + try { + java.rmi.server.RemoteCall call = ref.newCall((java.rmi.server.RemoteObject) this, operations, 0, interfaceHash); + try { + java.io.ObjectOutput out = call.getOutputStream(); + out.writeObject($param_String_1); + out.writeObject($param_Remote_2); + } catch (java.io.IOException e) { + throw new java.rmi.MarshalException("error marshalling arguments", e); + } + ref.invoke(call); + ref.done(call); + } catch (java.lang.RuntimeException e) { + throw e; + } catch (java.rmi.RemoteException e) { + throw e; + } catch (java.rmi.AlreadyBoundException e) { + throw e; + } catch (java.lang.Exception e) { + throw new java.rmi.UnexpectedException("undeclared checked exception", e); + } } - + // implementation of list() public java.lang.String[] list() - throws java.rmi.AccessException, java.rmi.RemoteException + throws java.rmi.AccessException, java.rmi.RemoteException { - try { - java.rmi.server.RemoteCall call = ref.newCall((java.rmi.server.RemoteObject) this, operations, 1, interfaceHash); - ref.invoke(call); - java.lang.String[] $result; - try { - java.io.ObjectInput in = call.getInputStream(); - $result = (java.lang.String[]) in.readObject(); - } catch (java.io.IOException e) { - throw new java.rmi.UnmarshalException("error unmarshalling return", e); - } catch (java.lang.ClassNotFoundException e) { - throw new java.rmi.UnmarshalException("error unmarshalling return", e); - } finally { - ref.done(call); - } - return $result; - } catch (java.lang.RuntimeException e) { - throw e; - } catch (java.rmi.RemoteException e) { - throw e; - } catch (java.lang.Exception e) { - throw new java.rmi.UnexpectedException("undeclared checked exception", e); - } + try { + java.rmi.server.RemoteCall call = ref.newCall((java.rmi.server.RemoteObject) this, operations, 1, interfaceHash); + ref.invoke(call); + java.lang.String[] $result; + try { + java.io.ObjectInput in = call.getInputStream(); + $result = (java.lang.String[]) in.readObject(); + } catch (java.io.IOException e) { + throw new java.rmi.UnmarshalException("error unmarshalling return", e); + } catch (java.lang.ClassNotFoundException e) { + throw new java.rmi.UnmarshalException("error unmarshalling return", e); + } finally { + ref.done(call); + } + return $result; + } catch (java.lang.RuntimeException e) { + throw e; + } catch (java.rmi.RemoteException e) { + throw e; + } catch (java.lang.Exception e) { + throw new java.rmi.UnexpectedException("undeclared checked exception", e); + } } - + // implementation of lookup(String) public java.rmi.Remote lookup(java.lang.String $param_String_1) - throws java.rmi.AccessException, java.rmi.NotBoundException, java.rmi.RemoteException + throws java.rmi.AccessException, java.rmi.NotBoundException, java.rmi.RemoteException { - try { - java.rmi.server.RemoteCall call = ref.newCall((java.rmi.server.RemoteObject) this, operations, 2, interfaceHash); - try { - java.io.ObjectOutput out = call.getOutputStream(); - out.writeObject($param_String_1); - } catch (java.io.IOException e) { - throw new java.rmi.MarshalException("error marshalling arguments", e); - } - ref.invoke(call); - java.rmi.Remote $result; - try { - java.io.ObjectInput in = call.getInputStream(); - $result = (java.rmi.Remote) in.readObject(); - } catch (java.io.IOException e) { - throw new java.rmi.UnmarshalException("error unmarshalling return", e); - } catch (java.lang.ClassNotFoundException e) { - throw new java.rmi.UnmarshalException("error unmarshalling return", e); - } finally { - ref.done(call); - } - return $result; - } catch (java.lang.RuntimeException e) { - throw e; - } catch (java.rmi.RemoteException e) { - throw e; - } catch (java.rmi.NotBoundException e) { - throw e; - } catch (java.lang.Exception e) { - throw new java.rmi.UnexpectedException("undeclared checked exception", e); - } + try { + java.rmi.server.RemoteCall call = ref.newCall((java.rmi.server.RemoteObject) this, operations, 2, interfaceHash); + try { + java.io.ObjectOutput out = call.getOutputStream(); + out.writeObject($param_String_1); + } catch (java.io.IOException e) { + throw new java.rmi.MarshalException("error marshalling arguments", e); + } + ref.invoke(call); + java.rmi.Remote $result; + try { + java.io.ObjectInput in = call.getInputStream(); + $result = (java.rmi.Remote) in.readObject(); + } catch (java.io.IOException e) { + throw new java.rmi.UnmarshalException("error unmarshalling return", e); + } catch (java.lang.ClassNotFoundException e) { + throw new java.rmi.UnmarshalException("error unmarshalling return", e); + } finally { + ref.done(call); + } + return $result; + } catch (java.lang.RuntimeException e) { + throw e; + } catch (java.rmi.RemoteException e) { + throw e; + } catch (java.rmi.NotBoundException e) { + throw e; + } catch (java.lang.Exception e) { + throw new java.rmi.UnexpectedException("undeclared checked exception", e); + } } - + // implementation of rebind(String, Remote) public void rebind(java.lang.String $param_String_1, java.rmi.Remote $param_Remote_2) - throws java.rmi.AccessException, java.rmi.RemoteException + throws java.rmi.AccessException, java.rmi.RemoteException { - try { - java.rmi.server.RemoteCall call = ref.newCall((java.rmi.server.RemoteObject) this, operations, 3, interfaceHash); - try { - java.io.ObjectOutput out = call.getOutputStream(); - out.writeObject($param_String_1); - out.writeObject($param_Remote_2); - } catch (java.io.IOException e) { - throw new java.rmi.MarshalException("error marshalling arguments", e); - } - ref.invoke(call); - ref.done(call); - } catch (java.lang.RuntimeException e) { - throw e; - } catch (java.rmi.RemoteException e) { - throw e; - } catch (java.lang.Exception e) { - throw new java.rmi.UnexpectedException("undeclared checked exception", e); - } + try { + java.rmi.server.RemoteCall call = ref.newCall((java.rmi.server.RemoteObject) this, operations, 3, interfaceHash); + try { + java.io.ObjectOutput out = call.getOutputStream(); + out.writeObject($param_String_1); + out.writeObject($param_Remote_2); + } catch (java.io.IOException e) { + throw new java.rmi.MarshalException("error marshalling arguments", e); + } + ref.invoke(call); + ref.done(call); + } catch (java.lang.RuntimeException e) { + throw e; + } catch (java.rmi.RemoteException e) { + throw e; + } catch (java.lang.Exception e) { + throw new java.rmi.UnexpectedException("undeclared checked exception", e); + } } - + // implementation of unbind(String) public void unbind(java.lang.String $param_String_1) - throws java.rmi.AccessException, java.rmi.NotBoundException, java.rmi.RemoteException + throws java.rmi.AccessException, java.rmi.NotBoundException, java.rmi.RemoteException { - try { - java.rmi.server.RemoteCall call = ref.newCall((java.rmi.server.RemoteObject) this, operations, 4, interfaceHash); - try { - java.io.ObjectOutput out = call.getOutputStream(); - out.writeObject($param_String_1); - } catch (java.io.IOException e) { - throw new java.rmi.MarshalException("error marshalling arguments", e); - } - ref.invoke(call); - ref.done(call); - } catch (java.lang.RuntimeException e) { - throw e; - } catch (java.rmi.RemoteException e) { - throw e; - } catch (java.rmi.NotBoundException e) { - throw e; - } catch (java.lang.Exception e) { - throw new java.rmi.UnexpectedException("undeclared checked exception", e); - } + try { + java.rmi.server.RemoteCall call = ref.newCall((java.rmi.server.RemoteObject) this, operations, 4, interfaceHash); + try { + java.io.ObjectOutput out = call.getOutputStream(); + out.writeObject($param_String_1); + } catch (java.io.IOException e) { + throw new java.rmi.MarshalException("error marshalling arguments", e); + } + ref.invoke(call); + ref.done(call); + } catch (java.lang.RuntimeException e) { + throw e; + } catch (java.rmi.RemoteException e) { + throw e; + } catch (java.rmi.NotBoundException e) { + throw e; + } catch (java.lang.Exception e) { + throw new java.rmi.UnexpectedException("undeclared checked exception", e); + } } } diff --git a/jdk/test/java/rmi/registry/multipleRegistries/MultipleRegistries.java b/jdk/test/java/rmi/registry/multipleRegistries/MultipleRegistries.java index bdfb87c87ed..8bca932dda3 100644 --- a/jdk/test/java/rmi/registry/multipleRegistries/MultipleRegistries.java +++ b/jdk/test/java/rmi/registry/multipleRegistries/MultipleRegistries.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 2003 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -41,49 +41,49 @@ public class MultipleRegistries implements RemoteInterface { private static final String NAME = "MultipleRegistries"; public Object passObject(Object obj) { - return obj; + return obj; } - + public static void main(String[] args) throws Exception { - - RemoteInterface server = null; - RemoteInterface proxy = null; - - try { - System.err.println("export object"); - server = new MultipleRegistries(); - proxy = - (RemoteInterface) UnicastRemoteObject.exportObject(server, 0); - System.err.println("proxy = " + proxy); + RemoteInterface server = null; + RemoteInterface proxy = null; - System.err.println("export registries"); - Registry registryImpl1 = LocateRegistry.createRegistry(2030); - Registry registryImpl2 = LocateRegistry.createRegistry(2040); + try { + System.err.println("export object"); + server = new MultipleRegistries(); + proxy = + (RemoteInterface) UnicastRemoteObject.exportObject(server, 0); - System.err.println("bind remote object in registries"); - Registry registry1 = LocateRegistry.getRegistry(2030); - Registry registry2 = LocateRegistry.getRegistry(2040); + System.err.println("proxy = " + proxy); - registry1.bind(NAME, proxy); - registry2.bind(NAME, proxy); + System.err.println("export registries"); + Registry registryImpl1 = LocateRegistry.createRegistry(2030); + Registry registryImpl2 = LocateRegistry.createRegistry(2040); - System.err.println("lookup remote object in registries"); + System.err.println("bind remote object in registries"); + Registry registry1 = LocateRegistry.getRegistry(2030); + Registry registry2 = LocateRegistry.getRegistry(2040); - RemoteInterface remote1 = (RemoteInterface) registry1.lookup(NAME); - RemoteInterface remote2 = (RemoteInterface) registry2.lookup(NAME); + registry1.bind(NAME, proxy); + registry2.bind(NAME, proxy); - System.err.println("invoke methods on remote objects"); - remote1.passObject(remote1); - remote2.passObject(remote2); + System.err.println("lookup remote object in registries"); - System.err.println("TEST PASSED"); - - } finally { - if (proxy != null) { - UnicastRemoteObject.unexportObject(server, true); - } - } + RemoteInterface remote1 = (RemoteInterface) registry1.lookup(NAME); + RemoteInterface remote2 = (RemoteInterface) registry2.lookup(NAME); + + System.err.println("invoke methods on remote objects"); + remote1.passObject(remote1); + remote2.passObject(remote2); + + System.err.println("TEST PASSED"); + + } finally { + if (proxy != null) { + UnicastRemoteObject.unexportObject(server, true); + } + } } } diff --git a/jdk/test/java/rmi/registry/reexport/Reexport.java b/jdk/test/java/rmi/registry/reexport/Reexport.java index 23f10e890a4..5c88736d4f0 100644 --- a/jdk/test/java/rmi/registry/reexport/Reexport.java +++ b/jdk/test/java/rmi/registry/reexport/Reexport.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1999-2004 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -25,13 +25,13 @@ * @bug 4120329 * @summary RMI registry creation is impossible if first attempt fails. * @library ../../testlibrary - * @build StreamPipe TestParams TestLibrary JavaVM + * @build StreamPipe TestParams TestLibrary JavaVM * @build RegistryRunner RegistryRunner_Stub * @build Reexport * @run main/othervm Reexport */ -/* +/* * If a VM could not create an RMI registry because another registry * usually in another process, was using the registry port, the next * time the VM tried to create a registry (after the other registry @@ -40,7 +40,7 @@ * use when it should never have been allocated. * * The test creates this conflict using Runtime.exec and ensures that - * a registry can still be created after the conflict is resolved. + * a registry can still be created after the conflict is resolved. */ import java.io.*; @@ -50,106 +50,106 @@ import java.rmi.server.*; public class Reexport { static public final int regport = TestLibrary.REGISTRY_PORT; - + static public void main(String[] argv) { - Registry reg = null; + Registry reg = null; - try { - System.err.println("\nregression test for 4120329\n"); - - // establish the registry (we hope) - System.err.println("Starting registry on port " + regport); - Reexport.makeRegistry(regport); - - // Get a handle to the registry - System.err.println("Creating duplicate registry, this should fail..."); - reg = createReg(true); - - if (reg != null) { - TestLibrary.bomb("failed was able to duplicate the registry?!?"); - } - - // Kill the first registry. - System.err.println("Bringing down the first registry"); - try { - Reexport.killRegistry(); - } catch (Exception foo) { - } - - // start another registry now that the first is gone; this should work - System.err.println("Trying again to start our own " + - "registry... this should work"); - - reg = createReg(false); - - if (reg == null) { - TestLibrary.bomb("Could not create registry on second try"); - } - - System.err.println("Test passed"); - - } catch (Exception e) { - TestLibrary.bomb(e); - } finally { - // dont leave the registry around to affect other tests. - killRegistry(); + try { + System.err.println("\nregression test for 4120329\n"); - reg = null; - } + // establish the registry (we hope) + System.err.println("Starting registry on port " + regport); + Reexport.makeRegistry(regport); + + // Get a handle to the registry + System.err.println("Creating duplicate registry, this should fail..."); + reg = createReg(true); + + if (reg != null) { + TestLibrary.bomb("failed was able to duplicate the registry?!?"); + } + + // Kill the first registry. + System.err.println("Bringing down the first registry"); + try { + Reexport.killRegistry(); + } catch (Exception foo) { + } + + // start another registry now that the first is gone; this should work + System.err.println("Trying again to start our own " + + "registry... this should work"); + + reg = createReg(false); + + if (reg == null) { + TestLibrary.bomb("Could not create registry on second try"); + } + + System.err.println("Test passed"); + + } catch (Exception e) { + TestLibrary.bomb(e); + } finally { + // dont leave the registry around to affect other tests. + killRegistry(); + + reg = null; + } } - + static Registry createReg(boolean remoteOk) { - Registry reg = null; + Registry reg = null; - try { - reg = LocateRegistry.createRegistry(regport); - } catch (Throwable e) { - if (remoteOk) { - System.err.println("EXPECTING PORT IN USE EXCEPTION:"); - System.err.println(e.getMessage()); - e.printStackTrace(); - } else { - TestLibrary.bomb((Exception) e); - } - } + try { + reg = LocateRegistry.createRegistry(regport); + } catch (Throwable e) { + if (remoteOk) { + System.err.println("EXPECTING PORT IN USE EXCEPTION:"); + System.err.println(e.getMessage()); + e.printStackTrace(); + } else { + TestLibrary.bomb((Exception) e); + } + } - return reg; + return reg; } public static void makeRegistry(int p) { - // sadly, we can't kill a registry if we have too-close control - // over it. We must make it in a subprocess, and then kill the - // subprocess when it has served our needs. + // sadly, we can't kill a registry if we have too-close control + // over it. We must make it in a subprocess, and then kill the + // subprocess when it has served our needs. - try { - JavaVM jvm = new JavaVM("RegistryRunner", "", Integer.toString(p)); - jvm.start(); - Reexport.subreg = jvm.getVM(); + try { + JavaVM jvm = new JavaVM("RegistryRunner", "", Integer.toString(p)); + jvm.start(); + Reexport.subreg = jvm.getVM(); - } catch (IOException e) { - // one of these is summarily dropped, can't remember which one - System.out.println ("Test setup failed - cannot run rmiregistry"); - TestLibrary.bomb("Test setup failed - cannot run test", e); - } - // Slop - wait for registry to come up. This is stupid. - try { - Thread.sleep (5000); - } catch (Exception whatever) { - } + } catch (IOException e) { + // one of these is summarily dropped, can't remember which one + System.out.println ("Test setup failed - cannot run rmiregistry"); + TestLibrary.bomb("Test setup failed - cannot run test", e); + } + // Slop - wait for registry to come up. This is stupid. + try { + Thread.sleep (5000); + } catch (Exception whatever) { + } } private static Process subreg = null; - + public static void killRegistry() { - if (Reexport.subreg != null) { + if (Reexport.subreg != null) { - RegistryRunner.requestExit(); + RegistryRunner.requestExit(); - try { - Reexport.subreg.waitFor(); - } catch (InterruptedException ie) { - } - } - Reexport.subreg = null; - } + try { + Reexport.subreg.waitFor(); + } catch (InterruptedException ie) { + } + } + Reexport.subreg = null; + } } diff --git a/jdk/test/java/rmi/reliability/benchmark/bench/rmi/BenchServer.java b/jdk/test/java/rmi/reliability/benchmark/bench/rmi/BenchServer.java index 167a3515684..a57d614e94a 100644 --- a/jdk/test/java/rmi/reliability/benchmark/bench/rmi/BenchServer.java +++ b/jdk/test/java/rmi/reliability/benchmark/bench/rmi/BenchServer.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 2000-2005 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -33,7 +33,7 @@ import java.rmi.RemoteException; /** * The RMI benchmark server is a simple compute-engine-like server which allows - * client benchmarks to create/export and unexport objects off of the server, + * client benchmarks to create/export and unexport objects off of the server, * or run arbitrary tasks. */ public interface BenchServer extends Remote { @@ -41,41 +41,40 @@ public interface BenchServer extends Remote { * Interface used for creating server-side remote objects. */ public interface RemoteObjectFactory extends Serializable { - Remote create() throws RemoteException; + Remote create() throws RemoteException; } - + /** * Interface used for server-side tasks. */ public interface Task extends Serializable { - Object execute() throws Exception; + Object execute() throws Exception; } /** - * Uses the given remote object factory to create a new remote object on + * Uses the given remote object factory to create a new remote object on * the server side. */ Remote create(RemoteObjectFactory factory) throws RemoteException; - + /** - * Unexports the specified remote object. Returns true if successful, + * Unexports the specified remote object. Returns true if successful, * false otherwise. */ boolean unexport(Remote obj, boolean force) throws RemoteException; - + /** * Execute given task. */ Object execute(Task task) throws Exception; - + /** * Invoke the garbage collector. */ void gc() throws RemoteException; - + /** * Terminate the server. */ void terminate(int delay) throws RemoteException; } - diff --git a/jdk/test/java/rmi/reliability/benchmark/bench/rmi/BenchServerImpl.java b/jdk/test/java/rmi/reliability/benchmark/bench/rmi/BenchServerImpl.java index 099e13d35ef..a0133f523d9 100644 --- a/jdk/test/java/rmi/reliability/benchmark/bench/rmi/BenchServerImpl.java +++ b/jdk/test/java/rmi/reliability/benchmark/bench/rmi/BenchServerImpl.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 2000-2005 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -37,8 +37,8 @@ import java.util.HashMap; /** * Benchmark server implementation. */ -public class BenchServerImpl - extends UnicastRemoteObject implements BenchServer +public class BenchServerImpl + extends UnicastRemoteObject implements BenchServer { HashMap implTable = new HashMap(); @@ -47,52 +47,51 @@ public class BenchServerImpl */ public BenchServerImpl() throws RemoteException { } - + /** - * Uses the given remote object factory to create a new remote object on + * Uses the given remote object factory to create a new remote object on * the server side. */ - public Remote create(BenchServer.RemoteObjectFactory factory) - throws RemoteException + public Remote create(BenchServer.RemoteObjectFactory factory) + throws RemoteException { - Remote impl = factory.create(); - implTable.put(RemoteObject.toStub(impl), new WeakReference(impl)); - return impl; + Remote impl = factory.create(); + implTable.put(RemoteObject.toStub(impl), new WeakReference(impl)); + return impl; } - + /** - * Unexports the specified remote object. Returns true if successful, + * Unexports the specified remote object. Returns true if successful, * false otherwise. */ public boolean unexport(Remote obj, boolean force) throws RemoteException { - WeakReference iref = (WeakReference) implTable.get(obj); - if (iref == null) - return false; - Remote impl = (Remote) iref.get(); - if (impl == null) - return false; - return UnicastRemoteObject.unexportObject(impl, force); + WeakReference iref = (WeakReference) implTable.get(obj); + if (iref == null) + return false; + Remote impl = (Remote) iref.get(); + if (impl == null) + return false; + return UnicastRemoteObject.unexportObject(impl, force); } - + /** * Execute given task. */ public Object execute(BenchServer.Task task) throws Exception { - return task.execute(); + return task.execute(); } - + /** * Invoke the garbage collector. */ public void gc() throws RemoteException { - System.gc(); + System.gc(); } - + /** * Terminate the server. */ public void terminate(int delay) throws RemoteException { - System.exit(0); + System.exit(0); } } - diff --git a/jdk/test/java/rmi/reliability/benchmark/bench/rmi/BooleanArrayCalls.java b/jdk/test/java/rmi/reliability/benchmark/bench/rmi/BooleanArrayCalls.java index cf444f6a57c..a9005d980e0 100644 --- a/jdk/test/java/rmi/reliability/benchmark/bench/rmi/BooleanArrayCalls.java +++ b/jdk/test/java/rmi/reliability/benchmark/bench/rmi/BooleanArrayCalls.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -39,42 +39,41 @@ import java.rmi.server.UnicastRemoteObject; public class BooleanArrayCalls implements Benchmark { interface Server extends Remote { - public boolean[] call(boolean[] a) throws RemoteException; + public boolean[] call(boolean[] a) throws RemoteException; } static class ServerImpl extends UnicastRemoteObject implements Server { - public ServerImpl() throws RemoteException { - } - - public boolean[] call(boolean[] a) throws RemoteException { - return a; - } + public ServerImpl() throws RemoteException { + } + + public boolean[] call(boolean[] a) throws RemoteException { + return a; + } } - + static class ServerFactory implements BenchServer.RemoteObjectFactory { - public Remote create() throws RemoteException { - return new ServerImpl(); - } + public Remote create() throws RemoteException { + return new ServerImpl(); + } } - + /** * Issue boolean array calls. * Arguments: <# calls> */ public long run(String[] args) throws Exception { - int size = Integer.parseInt(args[0]); - int reps = Integer.parseInt(args[1]); - BenchServer bsrv = Main.getBenchServer(); - Server stub = (Server) bsrv.create(new ServerFactory()); - boolean[] array = new boolean[size]; + int size = Integer.parseInt(args[0]); + int reps = Integer.parseInt(args[1]); + BenchServer bsrv = Main.getBenchServer(); + Server stub = (Server) bsrv.create(new ServerFactory()); + boolean[] array = new boolean[size]; - long start = System.currentTimeMillis(); - for (int i = 0; i < reps; i++) - stub.call(array); - long time = System.currentTimeMillis() - start; - - bsrv.unexport(stub, true); - return time; + long start = System.currentTimeMillis(); + for (int i = 0; i < reps; i++) + stub.call(array); + long time = System.currentTimeMillis() - start; + + bsrv.unexport(stub, true); + return time; } } - diff --git a/jdk/test/java/rmi/reliability/benchmark/bench/rmi/BooleanCalls.java b/jdk/test/java/rmi/reliability/benchmark/bench/rmi/BooleanCalls.java index 20eef614505..52d2810b79e 100644 --- a/jdk/test/java/rmi/reliability/benchmark/bench/rmi/BooleanCalls.java +++ b/jdk/test/java/rmi/reliability/benchmark/bench/rmi/BooleanCalls.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -38,40 +38,39 @@ import java.rmi.server.UnicastRemoteObject; public class BooleanCalls implements Benchmark { interface Server extends Remote { - public boolean call(boolean val) throws RemoteException; + public boolean call(boolean val) throws RemoteException; } static class ServerImpl extends UnicastRemoteObject implements Server { - public ServerImpl() throws RemoteException { - } - - public boolean call(boolean val) throws RemoteException { - return val; - } + public ServerImpl() throws RemoteException { + } + + public boolean call(boolean val) throws RemoteException { + return val; + } } - + static class ServerFactory implements BenchServer.RemoteObjectFactory { - public Remote create() throws RemoteException { - return new ServerImpl(); - } + public Remote create() throws RemoteException { + return new ServerImpl(); + } } - + /** * Issue boolean calls. * Arguments: <# calls> */ public long run(String[] args) throws Exception { - int cycles = Integer.parseInt(args[0]); - BenchServer bsrv = Main.getBenchServer(); - Server stub = (Server) bsrv.create(new ServerFactory()); + int cycles = Integer.parseInt(args[0]); + BenchServer bsrv = Main.getBenchServer(); + Server stub = (Server) bsrv.create(new ServerFactory()); - long start = System.currentTimeMillis(); - for (int i = 0; i < cycles; i++) - stub.call(true); - long time = System.currentTimeMillis() - start; - - bsrv.unexport(stub, true); - return time; + long start = System.currentTimeMillis(); + for (int i = 0; i < cycles; i++) + stub.call(true); + long time = System.currentTimeMillis() - start; + + bsrv.unexport(stub, true); + return time; } } - diff --git a/jdk/test/java/rmi/reliability/benchmark/bench/rmi/ByteArrayCalls.java b/jdk/test/java/rmi/reliability/benchmark/bench/rmi/ByteArrayCalls.java index 26d2dc342c1..d0401315c48 100644 --- a/jdk/test/java/rmi/reliability/benchmark/bench/rmi/ByteArrayCalls.java +++ b/jdk/test/java/rmi/reliability/benchmark/bench/rmi/ByteArrayCalls.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -39,42 +39,41 @@ import java.rmi.server.UnicastRemoteObject; public class ByteArrayCalls implements Benchmark { interface Server extends Remote { - public byte[] call(byte[] a) throws RemoteException; + public byte[] call(byte[] a) throws RemoteException; } static class ServerImpl extends UnicastRemoteObject implements Server { - public ServerImpl() throws RemoteException { - } - - public byte[] call(byte[] a) throws RemoteException { - return a; - } + public ServerImpl() throws RemoteException { + } + + public byte[] call(byte[] a) throws RemoteException { + return a; + } } - + static class ServerFactory implements BenchServer.RemoteObjectFactory { - public Remote create() throws RemoteException { - return new ServerImpl(); - } + public Remote create() throws RemoteException { + return new ServerImpl(); + } } - + /** * Issue byte array calls. * Arguments: <# calls> */ public long run(String[] args) throws Exception { - int size = Integer.parseInt(args[0]); - int reps = Integer.parseInt(args[1]); - BenchServer bsrv = Main.getBenchServer(); - Server stub = (Server) bsrv.create(new ServerFactory()); - byte[] array = new byte[size]; + int size = Integer.parseInt(args[0]); + int reps = Integer.parseInt(args[1]); + BenchServer bsrv = Main.getBenchServer(); + Server stub = (Server) bsrv.create(new ServerFactory()); + byte[] array = new byte[size]; - long start = System.currentTimeMillis(); - for (int i = 0; i < reps; i++) - stub.call(array); - long time = System.currentTimeMillis() - start; - - bsrv.unexport(stub, true); - return time; + long start = System.currentTimeMillis(); + for (int i = 0; i < reps; i++) + stub.call(array); + long time = System.currentTimeMillis() - start; + + bsrv.unexport(stub, true); + return time; } } - diff --git a/jdk/test/java/rmi/reliability/benchmark/bench/rmi/ByteCalls.java b/jdk/test/java/rmi/reliability/benchmark/bench/rmi/ByteCalls.java index e8ef1186792..8368c2ea0ee 100644 --- a/jdk/test/java/rmi/reliability/benchmark/bench/rmi/ByteCalls.java +++ b/jdk/test/java/rmi/reliability/benchmark/bench/rmi/ByteCalls.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -38,40 +38,39 @@ import java.rmi.server.UnicastRemoteObject; public class ByteCalls implements Benchmark { interface Server extends Remote { - public byte call(byte val) throws RemoteException; + public byte call(byte val) throws RemoteException; } static class ServerImpl extends UnicastRemoteObject implements Server { - public ServerImpl() throws RemoteException { - } - - public byte call(byte val) throws RemoteException { - return val; - } + public ServerImpl() throws RemoteException { + } + + public byte call(byte val) throws RemoteException { + return val; + } } - + static class ServerFactory implements BenchServer.RemoteObjectFactory { - public Remote create() throws RemoteException { - return new ServerImpl(); - } + public Remote create() throws RemoteException { + return new ServerImpl(); + } } - + /** * Issue byte calls. * Arguments: <# calls> */ public long run(String[] args) throws Exception { - int cycles = Integer.parseInt(args[0]); - BenchServer bsrv = Main.getBenchServer(); - Server stub = (Server) bsrv.create(new ServerFactory()); + int cycles = Integer.parseInt(args[0]); + BenchServer bsrv = Main.getBenchServer(); + Server stub = (Server) bsrv.create(new ServerFactory()); - long start = System.currentTimeMillis(); - for (int i = 0; i < cycles; i++) - stub.call((byte) 0); - long time = System.currentTimeMillis() - start; - - bsrv.unexport(stub, true); - return time; + long start = System.currentTimeMillis(); + for (int i = 0; i < cycles; i++) + stub.call((byte) 0); + long time = System.currentTimeMillis() - start; + + bsrv.unexport(stub, true); + return time; } } - diff --git a/jdk/test/java/rmi/reliability/benchmark/bench/rmi/CharArrayCalls.java b/jdk/test/java/rmi/reliability/benchmark/bench/rmi/CharArrayCalls.java index 15c3e3b897e..65903070436 100644 --- a/jdk/test/java/rmi/reliability/benchmark/bench/rmi/CharArrayCalls.java +++ b/jdk/test/java/rmi/reliability/benchmark/bench/rmi/CharArrayCalls.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -39,42 +39,41 @@ import java.rmi.server.UnicastRemoteObject; public class CharArrayCalls implements Benchmark { interface Server extends Remote { - public char[] call(char[] a) throws RemoteException; + public char[] call(char[] a) throws RemoteException; } static class ServerImpl extends UnicastRemoteObject implements Server { - public ServerImpl() throws RemoteException { - } - - public char[] call(char[] a) throws RemoteException { - return a; - } + public ServerImpl() throws RemoteException { + } + + public char[] call(char[] a) throws RemoteException { + return a; + } } - + static class ServerFactory implements BenchServer.RemoteObjectFactory { - public Remote create() throws RemoteException { - return new ServerImpl(); - } + public Remote create() throws RemoteException { + return new ServerImpl(); + } } - + /** * Issue char array calls. * Arguments: <# calls> */ public long run(String[] args) throws Exception { - int size = Integer.parseInt(args[0]); - int reps = Integer.parseInt(args[1]); - BenchServer bsrv = Main.getBenchServer(); - Server stub = (Server) bsrv.create(new ServerFactory()); - char[] array = new char[size]; + int size = Integer.parseInt(args[0]); + int reps = Integer.parseInt(args[1]); + BenchServer bsrv = Main.getBenchServer(); + Server stub = (Server) bsrv.create(new ServerFactory()); + char[] array = new char[size]; - long start = System.currentTimeMillis(); - for (int i = 0; i < reps; i++) - stub.call(array); - long time = System.currentTimeMillis() - start; - - bsrv.unexport(stub, true); - return time; + long start = System.currentTimeMillis(); + for (int i = 0; i < reps; i++) + stub.call(array); + long time = System.currentTimeMillis() - start; + + bsrv.unexport(stub, true); + return time; } } - diff --git a/jdk/test/java/rmi/reliability/benchmark/bench/rmi/CharCalls.java b/jdk/test/java/rmi/reliability/benchmark/bench/rmi/CharCalls.java index eaea4164d85..eeeb836be4a 100644 --- a/jdk/test/java/rmi/reliability/benchmark/bench/rmi/CharCalls.java +++ b/jdk/test/java/rmi/reliability/benchmark/bench/rmi/CharCalls.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -38,40 +38,39 @@ import java.rmi.server.UnicastRemoteObject; public class CharCalls implements Benchmark { interface Server extends Remote { - public char call(char val) throws RemoteException; + public char call(char val) throws RemoteException; } static class ServerImpl extends UnicastRemoteObject implements Server { - public ServerImpl() throws RemoteException { - } - - public char call(char val) throws RemoteException { - return val; - } + public ServerImpl() throws RemoteException { + } + + public char call(char val) throws RemoteException { + return val; + } } - + static class ServerFactory implements BenchServer.RemoteObjectFactory { - public Remote create() throws RemoteException { - return new ServerImpl(); - } + public Remote create() throws RemoteException { + return new ServerImpl(); + } } - + /** * Issue char calls. * Arguments: <# calls> */ public long run(String[] args) throws Exception { - int cycles = Integer.parseInt(args[0]); - BenchServer bsrv = Main.getBenchServer(); - Server stub = (Server) bsrv.create(new ServerFactory()); + int cycles = Integer.parseInt(args[0]); + BenchServer bsrv = Main.getBenchServer(); + Server stub = (Server) bsrv.create(new ServerFactory()); - long start = System.currentTimeMillis(); - for (int i = 0; i < cycles; i++) - stub.call('0'); - long time = System.currentTimeMillis() - start; - - bsrv.unexport(stub, true); - return time; + long start = System.currentTimeMillis(); + for (int i = 0; i < cycles; i++) + stub.call('0'); + long time = System.currentTimeMillis() - start; + + bsrv.unexport(stub, true); + return time; } } - diff --git a/jdk/test/java/rmi/reliability/benchmark/bench/rmi/ClassLoading.java b/jdk/test/java/rmi/reliability/benchmark/bench/rmi/ClassLoading.java index 303fe00502d..e6451c36ef3 100644 --- a/jdk/test/java/rmi/reliability/benchmark/bench/rmi/ClassLoading.java +++ b/jdk/test/java/rmi/reliability/benchmark/bench/rmi/ClassLoading.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -45,16 +45,15 @@ public class ClassLoading implements Benchmark { * Arguments: <# reps> */ public long run(String[] args) throws Exception { - int reps = Integer.parseInt(args[0]); - CodeSource csrc = getClass().getProtectionDomain().getCodeSource(); - String url = "jar:" + csrc.getLocation().toString() + ALTROOT; - - long start = System.currentTimeMillis(); - for (int i = 0; i < reps; i++) - RMIClassLoader.loadClass(url, CLASSNAME); - long time = System.currentTimeMillis() - start; - - return time; + int reps = Integer.parseInt(args[0]); + CodeSource csrc = getClass().getProtectionDomain().getCodeSource(); + String url = "jar:" + csrc.getLocation().toString() + ALTROOT; + + long start = System.currentTimeMillis(); + for (int i = 0; i < reps; i++) + RMIClassLoader.loadClass(url, CLASSNAME); + long time = System.currentTimeMillis() - start; + + return time; } } - diff --git a/jdk/test/java/rmi/reliability/benchmark/bench/rmi/DoubleArrayCalls.java b/jdk/test/java/rmi/reliability/benchmark/bench/rmi/DoubleArrayCalls.java index 6aef1593858..44f12010e94 100644 --- a/jdk/test/java/rmi/reliability/benchmark/bench/rmi/DoubleArrayCalls.java +++ b/jdk/test/java/rmi/reliability/benchmark/bench/rmi/DoubleArrayCalls.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -39,42 +39,41 @@ import java.rmi.server.UnicastRemoteObject; public class DoubleArrayCalls implements Benchmark { interface Server extends Remote { - public double[] call(double[] a) throws RemoteException; + public double[] call(double[] a) throws RemoteException; } static class ServerImpl extends UnicastRemoteObject implements Server { - public ServerImpl() throws RemoteException { - } - - public double[] call(double[] a) throws RemoteException { - return a; - } + public ServerImpl() throws RemoteException { + } + + public double[] call(double[] a) throws RemoteException { + return a; + } } - + static class ServerFactory implements BenchServer.RemoteObjectFactory { - public Remote create() throws RemoteException { - return new ServerImpl(); - } + public Remote create() throws RemoteException { + return new ServerImpl(); + } } - + /** * Issue double array calls. * Arguments: <# calls> */ public long run(String[] args) throws Exception { - int size = Integer.parseInt(args[0]); - int reps = Integer.parseInt(args[1]); - BenchServer bsrv = Main.getBenchServer(); - Server stub = (Server) bsrv.create(new ServerFactory()); - double[] array = new double[size]; + int size = Integer.parseInt(args[0]); + int reps = Integer.parseInt(args[1]); + BenchServer bsrv = Main.getBenchServer(); + Server stub = (Server) bsrv.create(new ServerFactory()); + double[] array = new double[size]; - long start = System.currentTimeMillis(); - for (int i = 0; i < reps; i++) - stub.call(array); - long time = System.currentTimeMillis() - start; - - bsrv.unexport(stub, true); - return time; + long start = System.currentTimeMillis(); + for (int i = 0; i < reps; i++) + stub.call(array); + long time = System.currentTimeMillis() - start; + + bsrv.unexport(stub, true); + return time; } } - diff --git a/jdk/test/java/rmi/reliability/benchmark/bench/rmi/DoubleCalls.java b/jdk/test/java/rmi/reliability/benchmark/bench/rmi/DoubleCalls.java index 4bde6166ae4..c847391f666 100644 --- a/jdk/test/java/rmi/reliability/benchmark/bench/rmi/DoubleCalls.java +++ b/jdk/test/java/rmi/reliability/benchmark/bench/rmi/DoubleCalls.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -38,40 +38,39 @@ import java.rmi.server.UnicastRemoteObject; public class DoubleCalls implements Benchmark { interface Server extends Remote { - public double call(double val) throws RemoteException; + public double call(double val) throws RemoteException; } static class ServerImpl extends UnicastRemoteObject implements Server { - public ServerImpl() throws RemoteException { - } - - public double call(double val) throws RemoteException { - return val; - } + public ServerImpl() throws RemoteException { + } + + public double call(double val) throws RemoteException { + return val; + } } - + static class ServerFactory implements BenchServer.RemoteObjectFactory { - public Remote create() throws RemoteException { - return new ServerImpl(); - } + public Remote create() throws RemoteException { + return new ServerImpl(); + } } - + /** * Issue double calls. * Arguments: <# calls> */ public long run(String[] args) throws Exception { - int cycles = Integer.parseInt(args[0]); - BenchServer bsrv = Main.getBenchServer(); - Server stub = (Server) bsrv.create(new ServerFactory()); + int cycles = Integer.parseInt(args[0]); + BenchServer bsrv = Main.getBenchServer(); + Server stub = (Server) bsrv.create(new ServerFactory()); - long start = System.currentTimeMillis(); - for (int i = 0; i < cycles; i++) - stub.call(0.0); - long time = System.currentTimeMillis() - start; - - bsrv.unexport(stub, true); - return time; + long start = System.currentTimeMillis(); + for (int i = 0; i < cycles; i++) + stub.call(0.0); + long time = System.currentTimeMillis() - start; + + bsrv.unexport(stub, true); + return time; } } - diff --git a/jdk/test/java/rmi/reliability/benchmark/bench/rmi/ExceptionCalls.java b/jdk/test/java/rmi/reliability/benchmark/bench/rmi/ExceptionCalls.java index 7664fe647bc..f7f521ae357 100644 --- a/jdk/test/java/rmi/reliability/benchmark/bench/rmi/ExceptionCalls.java +++ b/jdk/test/java/rmi/reliability/benchmark/bench/rmi/ExceptionCalls.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -41,43 +41,42 @@ public class ExceptionCalls implements Benchmark { } interface Server extends Remote { - public void call() throws RemoteException, FooException; + public void call() throws RemoteException, FooException; } static class ServerImpl extends UnicastRemoteObject implements Server { - public ServerImpl() throws RemoteException { - } - - public void call() throws RemoteException, FooException { - throw new FooException(); - } + public ServerImpl() throws RemoteException { + } + + public void call() throws RemoteException, FooException { + throw new FooException(); + } } - + static class ServerFactory implements BenchServer.RemoteObjectFactory { - public Remote create() throws RemoteException { - return new ServerImpl(); - } + public Remote create() throws RemoteException { + return new ServerImpl(); + } } - + /** * Issue calls which throw exceptions. * Arguments: <# calls> */ public long run(String[] args) throws Exception { - int reps = Integer.parseInt(args[0]); - BenchServer bsrv = Main.getBenchServer(); - Server stub = (Server) bsrv.create(new ServerFactory()); + int reps = Integer.parseInt(args[0]); + BenchServer bsrv = Main.getBenchServer(); + Server stub = (Server) bsrv.create(new ServerFactory()); - long start = System.currentTimeMillis(); - for (int i = 0; i < reps; i++) { - try { - stub.call(); - } catch (FooException e) {} - } - long time = System.currentTimeMillis() - start; - - bsrv.unexport(stub, true); - return time; + long start = System.currentTimeMillis(); + for (int i = 0; i < reps; i++) { + try { + stub.call(); + } catch (FooException e) {} + } + long time = System.currentTimeMillis() - start; + + bsrv.unexport(stub, true); + return time; } } - diff --git a/jdk/test/java/rmi/reliability/benchmark/bench/rmi/ExportObjs.java b/jdk/test/java/rmi/reliability/benchmark/bench/rmi/ExportObjs.java index a3e8c8b03a5..72071177abf 100644 --- a/jdk/test/java/rmi/reliability/benchmark/bench/rmi/ExportObjs.java +++ b/jdk/test/java/rmi/reliability/benchmark/bench/rmi/ExportObjs.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 2000-2003 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -35,7 +35,7 @@ import java.rmi.server.UnicastRemoteObject; * Benchmark for testing speed of UnicastRemoteObject.exportObject(). */ public class ExportObjs implements Benchmark { - + static class RemoteObj implements Remote { } @@ -44,19 +44,18 @@ public class ExportObjs implements Benchmark { * Arguments: <# objects> */ public long run(String[] args) throws Exception { - int size = Integer.parseInt(args[0]); - Remote[] objs = new Remote[size]; - for (int i = 0; i < size; i++) - objs[i] = new RemoteObj(); - - long start = System.currentTimeMillis(); - for (int i = 0; i < size; i++) - UnicastRemoteObject.exportObject(objs[i],0); - long time = System.currentTimeMillis() - start; - - for (int i = 0; i < size; i++) - UnicastRemoteObject.unexportObject(objs[i], true); - return time; + int size = Integer.parseInt(args[0]); + Remote[] objs = new Remote[size]; + for (int i = 0; i < size; i++) + objs[i] = new RemoteObj(); + + long start = System.currentTimeMillis(); + for (int i = 0; i < size; i++) + UnicastRemoteObject.exportObject(objs[i],0); + long time = System.currentTimeMillis() - start; + + for (int i = 0; i < size; i++) + UnicastRemoteObject.unexportObject(objs[i], true); + return time; } } - diff --git a/jdk/test/java/rmi/reliability/benchmark/bench/rmi/FloatArrayCalls.java b/jdk/test/java/rmi/reliability/benchmark/bench/rmi/FloatArrayCalls.java index 5905b11e9d4..d044f06ebbe 100644 --- a/jdk/test/java/rmi/reliability/benchmark/bench/rmi/FloatArrayCalls.java +++ b/jdk/test/java/rmi/reliability/benchmark/bench/rmi/FloatArrayCalls.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -39,42 +39,41 @@ import java.rmi.server.UnicastRemoteObject; public class FloatArrayCalls implements Benchmark { interface Server extends Remote { - public float[] call(float[] a) throws RemoteException; + public float[] call(float[] a) throws RemoteException; } static class ServerImpl extends UnicastRemoteObject implements Server { - public ServerImpl() throws RemoteException { - } - - public float[] call(float[] a) throws RemoteException { - return a; - } + public ServerImpl() throws RemoteException { + } + + public float[] call(float[] a) throws RemoteException { + return a; + } } - + static class ServerFactory implements BenchServer.RemoteObjectFactory { - public Remote create() throws RemoteException { - return new ServerImpl(); - } + public Remote create() throws RemoteException { + return new ServerImpl(); + } } - + /** * Issue float array calls. * Arguments: <# calls> */ public long run(String[] args) throws Exception { - int size = Integer.parseInt(args[0]); - int reps = Integer.parseInt(args[1]); - BenchServer bsrv = Main.getBenchServer(); - Server stub = (Server) bsrv.create(new ServerFactory()); - float[] array = new float[size]; + int size = Integer.parseInt(args[0]); + int reps = Integer.parseInt(args[1]); + BenchServer bsrv = Main.getBenchServer(); + Server stub = (Server) bsrv.create(new ServerFactory()); + float[] array = new float[size]; - long start = System.currentTimeMillis(); - for (int i = 0; i < reps; i++) - stub.call(array); - long time = System.currentTimeMillis() - start; - - bsrv.unexport(stub, true); - return time; + long start = System.currentTimeMillis(); + for (int i = 0; i < reps; i++) + stub.call(array); + long time = System.currentTimeMillis() - start; + + bsrv.unexport(stub, true); + return time; } } - diff --git a/jdk/test/java/rmi/reliability/benchmark/bench/rmi/FloatCalls.java b/jdk/test/java/rmi/reliability/benchmark/bench/rmi/FloatCalls.java index 5ff7bcebff7..564a81c1c6b 100644 --- a/jdk/test/java/rmi/reliability/benchmark/bench/rmi/FloatCalls.java +++ b/jdk/test/java/rmi/reliability/benchmark/bench/rmi/FloatCalls.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -38,40 +38,39 @@ import java.rmi.server.UnicastRemoteObject; public class FloatCalls implements Benchmark { interface Server extends Remote { - public float call(float val) throws RemoteException; + public float call(float val) throws RemoteException; } static class ServerImpl extends UnicastRemoteObject implements Server { - public ServerImpl() throws RemoteException { - } - - public float call(float val) throws RemoteException { - return val; - } + public ServerImpl() throws RemoteException { + } + + public float call(float val) throws RemoteException { + return val; + } } - + static class ServerFactory implements BenchServer.RemoteObjectFactory { - public Remote create() throws RemoteException { - return new ServerImpl(); - } + public Remote create() throws RemoteException { + return new ServerImpl(); + } } - + /** * Issue float calls. * Arguments: <# calls> */ public long run(String[] args) throws Exception { - int cycles = Integer.parseInt(args[0]); - BenchServer bsrv = Main.getBenchServer(); - Server stub = (Server) bsrv.create(new ServerFactory()); + int cycles = Integer.parseInt(args[0]); + BenchServer bsrv = Main.getBenchServer(); + Server stub = (Server) bsrv.create(new ServerFactory()); - long start = System.currentTimeMillis(); - for (int i = 0; i < cycles; i++) - stub.call((float) 0.0); - long time = System.currentTimeMillis() - start; - - bsrv.unexport(stub, true); - return time; + long start = System.currentTimeMillis(); + for (int i = 0; i < cycles; i++) + stub.call((float) 0.0); + long time = System.currentTimeMillis() - start; + + bsrv.unexport(stub, true); + return time; } } - diff --git a/jdk/test/java/rmi/reliability/benchmark/bench/rmi/IntArrayCalls.java b/jdk/test/java/rmi/reliability/benchmark/bench/rmi/IntArrayCalls.java index ebd2668e095..f8897639ea9 100644 --- a/jdk/test/java/rmi/reliability/benchmark/bench/rmi/IntArrayCalls.java +++ b/jdk/test/java/rmi/reliability/benchmark/bench/rmi/IntArrayCalls.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -39,42 +39,41 @@ import java.rmi.server.UnicastRemoteObject; public class IntArrayCalls implements Benchmark { interface Server extends Remote { - public int[] call(int[] a) throws RemoteException; + public int[] call(int[] a) throws RemoteException; } static class ServerImpl extends UnicastRemoteObject implements Server { - public ServerImpl() throws RemoteException { - } - - public int[] call(int[] a) throws RemoteException { - return a; - } + public ServerImpl() throws RemoteException { + } + + public int[] call(int[] a) throws RemoteException { + return a; + } } - + static class ServerFactory implements BenchServer.RemoteObjectFactory { - public Remote create() throws RemoteException { - return new ServerImpl(); - } + public Remote create() throws RemoteException { + return new ServerImpl(); + } } - + /** * Issue int array calls. * Arguments: <# calls> */ public long run(String[] args) throws Exception { - int size = Integer.parseInt(args[0]); - int reps = Integer.parseInt(args[1]); - BenchServer bsrv = Main.getBenchServer(); - Server stub = (Server) bsrv.create(new ServerFactory()); - int[] array = new int[size]; + int size = Integer.parseInt(args[0]); + int reps = Integer.parseInt(args[1]); + BenchServer bsrv = Main.getBenchServer(); + Server stub = (Server) bsrv.create(new ServerFactory()); + int[] array = new int[size]; - long start = System.currentTimeMillis(); - for (int i = 0; i < reps; i++) - stub.call(array); - long time = System.currentTimeMillis() - start; - - bsrv.unexport(stub, true); - return time; + long start = System.currentTimeMillis(); + for (int i = 0; i < reps; i++) + stub.call(array); + long time = System.currentTimeMillis() - start; + + bsrv.unexport(stub, true); + return time; } } - diff --git a/jdk/test/java/rmi/reliability/benchmark/bench/rmi/IntCalls.java b/jdk/test/java/rmi/reliability/benchmark/bench/rmi/IntCalls.java index fb85488083f..e1777c3ac24 100644 --- a/jdk/test/java/rmi/reliability/benchmark/bench/rmi/IntCalls.java +++ b/jdk/test/java/rmi/reliability/benchmark/bench/rmi/IntCalls.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -38,40 +38,39 @@ import java.rmi.server.UnicastRemoteObject; public class IntCalls implements Benchmark { interface Server extends Remote { - public int call(int val) throws RemoteException; + public int call(int val) throws RemoteException; } static class ServerImpl extends UnicastRemoteObject implements Server { - public ServerImpl() throws RemoteException { - } - - public int call(int val) throws RemoteException { - return val; - } + public ServerImpl() throws RemoteException { + } + + public int call(int val) throws RemoteException { + return val; + } } - + static class ServerFactory implements BenchServer.RemoteObjectFactory { - public Remote create() throws RemoteException { - return new ServerImpl(); - } + public Remote create() throws RemoteException { + return new ServerImpl(); + } } - + /** * Issue int calls. * Arguments: <# calls> */ public long run(String[] args) throws Exception { - int cycles = Integer.parseInt(args[0]); - BenchServer bsrv = Main.getBenchServer(); - Server stub = (Server) bsrv.create(new ServerFactory()); + int cycles = Integer.parseInt(args[0]); + BenchServer bsrv = Main.getBenchServer(); + Server stub = (Server) bsrv.create(new ServerFactory()); - long start = System.currentTimeMillis(); - for (int i = 0; i < cycles; i++) - stub.call(0); - long time = System.currentTimeMillis() - start; - - bsrv.unexport(stub, true); - return time; + long start = System.currentTimeMillis(); + for (int i = 0; i < cycles; i++) + stub.call(0); + long time = System.currentTimeMillis() - start; + + bsrv.unexport(stub, true); + return time; } } - diff --git a/jdk/test/java/rmi/reliability/benchmark/bench/rmi/LongArrayCalls.java b/jdk/test/java/rmi/reliability/benchmark/bench/rmi/LongArrayCalls.java index 1f86e5b4a1e..15cbeb799f5 100644 --- a/jdk/test/java/rmi/reliability/benchmark/bench/rmi/LongArrayCalls.java +++ b/jdk/test/java/rmi/reliability/benchmark/bench/rmi/LongArrayCalls.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -39,42 +39,41 @@ import java.rmi.server.UnicastRemoteObject; public class LongArrayCalls implements Benchmark { interface Server extends Remote { - public long[] call(long[] a) throws RemoteException; + public long[] call(long[] a) throws RemoteException; } static class ServerImpl extends UnicastRemoteObject implements Server { - public ServerImpl() throws RemoteException { - } - - public long[] call(long[] a) throws RemoteException { - return a; - } + public ServerImpl() throws RemoteException { + } + + public long[] call(long[] a) throws RemoteException { + return a; + } } - + static class ServerFactory implements BenchServer.RemoteObjectFactory { - public Remote create() throws RemoteException { - return new ServerImpl(); - } + public Remote create() throws RemoteException { + return new ServerImpl(); + } } - + /** * Issue long array calls. * Arguments: <# calls> */ public long run(String[] args) throws Exception { - int size = Integer.parseInt(args[0]); - int reps = Integer.parseInt(args[1]); - BenchServer bsrv = Main.getBenchServer(); - Server stub = (Server) bsrv.create(new ServerFactory()); - long[] array = new long[size]; + int size = Integer.parseInt(args[0]); + int reps = Integer.parseInt(args[1]); + BenchServer bsrv = Main.getBenchServer(); + Server stub = (Server) bsrv.create(new ServerFactory()); + long[] array = new long[size]; - long start = System.currentTimeMillis(); - for (int i = 0; i < reps; i++) - stub.call(array); - long time = System.currentTimeMillis() - start; - - bsrv.unexport(stub, true); - return time; + long start = System.currentTimeMillis(); + for (int i = 0; i < reps; i++) + stub.call(array); + long time = System.currentTimeMillis() - start; + + bsrv.unexport(stub, true); + return time; } } - diff --git a/jdk/test/java/rmi/reliability/benchmark/bench/rmi/LongCalls.java b/jdk/test/java/rmi/reliability/benchmark/bench/rmi/LongCalls.java index 864349c9f68..109ec952609 100644 --- a/jdk/test/java/rmi/reliability/benchmark/bench/rmi/LongCalls.java +++ b/jdk/test/java/rmi/reliability/benchmark/bench/rmi/LongCalls.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -38,40 +38,39 @@ import java.rmi.server.UnicastRemoteObject; public class LongCalls implements Benchmark { interface Server extends Remote { - public long call(long val) throws RemoteException; + public long call(long val) throws RemoteException; } static class ServerImpl extends UnicastRemoteObject implements Server { - public ServerImpl() throws RemoteException { - } - - public long call(long val) throws RemoteException { - return val; - } + public ServerImpl() throws RemoteException { + } + + public long call(long val) throws RemoteException { + return val; + } } - + static class ServerFactory implements BenchServer.RemoteObjectFactory { - public Remote create() throws RemoteException { - return new ServerImpl(); - } + public Remote create() throws RemoteException { + return new ServerImpl(); + } } - + /** * Issue long calls. * Arguments: <# calls> */ public long run(String[] args) throws Exception { - int cycles = Integer.parseInt(args[0]); - BenchServer bsrv = Main.getBenchServer(); - Server stub = (Server) bsrv.create(new ServerFactory()); + int cycles = Integer.parseInt(args[0]); + BenchServer bsrv = Main.getBenchServer(); + Server stub = (Server) bsrv.create(new ServerFactory()); - long start = System.currentTimeMillis(); - for (int i = 0; i < cycles; i++) - stub.call(0L); - long time = System.currentTimeMillis() - start; - - bsrv.unexport(stub, true); - return time; + long start = System.currentTimeMillis(); + for (int i = 0; i < cycles; i++) + stub.call(0L); + long time = System.currentTimeMillis() - start; + + bsrv.unexport(stub, true); + return time; } } - diff --git a/jdk/test/java/rmi/reliability/benchmark/bench/rmi/Main.java b/jdk/test/java/rmi/reliability/benchmark/bench/rmi/Main.java index de81a09f2b5..3e06a8887d3 100644 --- a/jdk/test/java/rmi/reliability/benchmark/bench/rmi/Main.java +++ b/jdk/test/java/rmi/reliability/benchmark/bench/rmi/Main.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 2000-2005 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -47,35 +47,35 @@ import java.rmi.server.RemoteObject; import java.util.Timer; import java.util.TimerTask; -/* +/* * RMI/Serialization benchmark tests. */ public class Main { - + /** * RMI-specific benchmark harness. */ static class RMIHarness extends Harness { - /** - * Construct new RMI benchmark harness. - */ - RMIHarness(InputStream in) throws IOException, ConfigFormatException { - super(in); - } - - /** - * Cleanup both client and server side in between each benchmark. - */ - protected void cleanup() { - System.gc(); - if (Main.runmode == CLIENT) { - try { - Main.server.gc(); - } catch (Exception e) { - System.err.println("Warning: server gc failed: " + e); - } - } - } + /** + * Construct new RMI benchmark harness. + */ + RMIHarness(InputStream in) throws IOException, ConfigFormatException { + super(in); + } + + /** + * Cleanup both client and server side in between each benchmark. + */ + protected void cleanup() { + System.gc(); + if (Main.runmode == CLIENT) { + try { + Main.server.gc(); + } catch (Exception e) { + System.err.println("Warning: server gc failed: " + e); + } + } + } } static final String CONFFILE = "/bench/rmi/config"; @@ -85,7 +85,7 @@ public class Main { static final int SAMEVM = 0; static final int CLIENT = 1; static final int SERVER = 2; - + static final int TEXT = 0; static final int HTML = 1; static final int XML = 2; @@ -111,7 +111,7 @@ public class Main { * Returns reference to benchmark server. */ public static BenchServer getBenchServer() { - return server; + return server; } /** @@ -127,252 +127,252 @@ public class Main { p.println(" -t repeat benchmarks for specified number of hours"); p.println(" -o specify output file"); p.println(" -c specify (non-default) " + - "configuration file"); + "configuration file"); p.println(" -html format output as html " + - "(default is text)"); + "(default is text)"); p.println(" -xml format output as xml"); - p.println(" -client run benchmark client using server " + - "on specified host/port"); - p.println(" -server run benchmark server on given port"); + p.println(" -client run benchmark client using server " + + "on specified host/port"); + p.println(" -server run benchmark server on given port"); } - + /** * Print error message and exit. */ static void die(String mesg) { - System.err.println(mesg); - System.exit(1); + System.err.println(mesg); + System.exit(1); } /** * Stop server and exit. */ public static void exit() { - switch (runmode) { - case CLIENT: - if (server != null) { - try { - server.terminate(0); - } catch (RemoteException re) { - // ignore - } - } - default: - System.exit(0); - } + switch (runmode) { + case CLIENT: + if (server != null) { + try { + server.terminate(0); + } catch (RemoteException re) { + // ignore + } + } + default: + System.exit(0); + } } /** * Benchmark mainline. */ public static void main(String[] args) { - setupSecurity(); - parseArgs(args); - setupStreams(); - if (list) { - listConfig(); - } else { - setupServer(); - if (runmode != SERVER) { - setupHarness(); - setupReporter(); - if (exitOnTimer) { - setupTimer(testDurationSeconds); - while (true) { - runBenchmarks(); - if (exitRequested) { - exit(); - } - } - } else { - runBenchmarks(); - exit(); - } - } - } + setupSecurity(); + parseArgs(args); + setupStreams(); + if (list) { + listConfig(); + } else { + setupServer(); + if (runmode != SERVER) { + setupHarness(); + setupReporter(); + if (exitOnTimer) { + setupTimer(testDurationSeconds); + while (true) { + runBenchmarks(); + if (exitRequested) { + exit(); + } + } + } else { + runBenchmarks(); + exit(); + } + } + } } - + /** * Parse command-line arguments. */ static void parseArgs(String[] args) { - for (int i = 0; i < args.length; i++) { - if (args[i].equals("-h")) { - usage(); - System.exit(0); - } else if (args[i].equals("-v")) { - verbose = true; - } else if (args[i].equals("-l")) { - list = true; - } else if (args[i].equals("-t")) { - if (++i >= args.length) - die("Error: no timeout value specified"); - try { - exitOnTimer = true; - testDurationSeconds = Integer.parseInt(args[i]) * 3600; - } catch (Exception e) { - die("Error: unable to determine timeout value"); - } - } else if (args[i].equals("-o")) { - if (++i >= args.length) - die("Error: no output file specified"); - try { - repstr = new FileOutputStream(args[i]); - } catch (IOException e) { - die("Error: unable to open \"" + args[i] + "\""); - } - } else if (args[i].equals("-c")) { - if (++i >= args.length) - die("Error: no config file specified"); - try { - confstr = new FileInputStream(args[i]); - } catch (IOException e) { - die("Error: unable to open \"" + args[i] + "\""); - } - } else if (args[i].equals("-html")) { - if (format != TEXT) - die("Error: conflicting formats"); - format = HTML; - } else if (args[i].equals("-xml")) { - if (format != TEXT) - die("Error: conflicting formats"); - format = XML; - } else if (args[i].equals("-client")) { - if (runmode == CLIENT) - die("Error: multiple -client options"); - if (runmode == SERVER) - die("Error: -client and -server options conflict"); - if (++i >= args.length) - die("Error: -client missing host/port"); - try { - int sepi = args[i].indexOf(':'); - host = args[i].substring(0, sepi); - port = Integer.parseInt(args[i].substring(sepi + 1)); - } catch (Exception e) { - die("Error: illegal host/port specified for -client"); - } - runmode = CLIENT; - } else if (args[i].equals("-server")) { - if (runmode == CLIENT) - die("Error: -client and -server options conflict"); - if (runmode == SERVER) - die("Error: multiple -server options"); - if (++i >= args.length) - die("Error: -server missing port"); - try { - port = Integer.parseInt(args[i]); - } catch (Exception e) { - die("Error: illegal port specified for -server"); - } - runmode = SERVER; - } else { - System.err.println("Illegal option: \"" + args[i] + "\""); - usage(); - System.exit(1); - } - } + for (int i = 0; i < args.length; i++) { + if (args[i].equals("-h")) { + usage(); + System.exit(0); + } else if (args[i].equals("-v")) { + verbose = true; + } else if (args[i].equals("-l")) { + list = true; + } else if (args[i].equals("-t")) { + if (++i >= args.length) + die("Error: no timeout value specified"); + try { + exitOnTimer = true; + testDurationSeconds = Integer.parseInt(args[i]) * 3600; + } catch (Exception e) { + die("Error: unable to determine timeout value"); + } + } else if (args[i].equals("-o")) { + if (++i >= args.length) + die("Error: no output file specified"); + try { + repstr = new FileOutputStream(args[i]); + } catch (IOException e) { + die("Error: unable to open \"" + args[i] + "\""); + } + } else if (args[i].equals("-c")) { + if (++i >= args.length) + die("Error: no config file specified"); + try { + confstr = new FileInputStream(args[i]); + } catch (IOException e) { + die("Error: unable to open \"" + args[i] + "\""); + } + } else if (args[i].equals("-html")) { + if (format != TEXT) + die("Error: conflicting formats"); + format = HTML; + } else if (args[i].equals("-xml")) { + if (format != TEXT) + die("Error: conflicting formats"); + format = XML; + } else if (args[i].equals("-client")) { + if (runmode == CLIENT) + die("Error: multiple -client options"); + if (runmode == SERVER) + die("Error: -client and -server options conflict"); + if (++i >= args.length) + die("Error: -client missing host/port"); + try { + int sepi = args[i].indexOf(':'); + host = args[i].substring(0, sepi); + port = Integer.parseInt(args[i].substring(sepi + 1)); + } catch (Exception e) { + die("Error: illegal host/port specified for -client"); + } + runmode = CLIENT; + } else if (args[i].equals("-server")) { + if (runmode == CLIENT) + die("Error: -client and -server options conflict"); + if (runmode == SERVER) + die("Error: multiple -server options"); + if (++i >= args.length) + die("Error: -server missing port"); + try { + port = Integer.parseInt(args[i]); + } catch (Exception e) { + die("Error: illegal port specified for -server"); + } + runmode = SERVER; + } else { + System.err.println("Illegal option: \"" + args[i] + "\""); + usage(); + System.exit(1); + } + } } - + /** * Set up security manager and policy, if not set already. */ static void setupSecurity() { - if (System.getSecurityManager() != null) - return; - - /* As of 1.4, it is too late to set the security policy - * file at this point so these line have been commented out. - */ - //System.setProperty("java.security.policy", - // Main.class.getResource("/bench/rmi/policy.all").toString()); - System.setSecurityManager(new RMISecurityManager()); + if (System.getSecurityManager() != null) + return; + + /* As of 1.4, it is too late to set the security policy + * file at this point so these line have been commented out. + */ + //System.setProperty("java.security.policy", + // Main.class.getResource("/bench/rmi/policy.all").toString()); + System.setSecurityManager(new RMISecurityManager()); } /** * Set up configuration file and report streams, if not set already. */ static void setupStreams() { - if (repstr == null) - repstr = System.out; - if (confstr == null) - confstr = (new Main()).getClass().getResourceAsStream(CONFFILE); - if (confstr == null) - die("Error: unable to find default config file"); + if (repstr == null) + repstr = System.out; + if (confstr == null) + confstr = (new Main()).getClass().getResourceAsStream(CONFFILE); + if (confstr == null) + die("Error: unable to find default config file"); } - + /** * Print contents of configuration file to selected output stream. */ static void listConfig() { - try { - byte[] buf = new byte[256]; - int len; - while ((len = confstr.read(buf)) != -1) - repstr.write(buf, 0, len); - } catch (IOException e) { - die("Error: failed to list config file"); - } + try { + byte[] buf = new byte[256]; + int len; + while ((len = confstr.read(buf)) != -1) + repstr.write(buf, 0, len); + } catch (IOException e) { + die("Error: failed to list config file"); + } } - + /** * Setup benchmark server. */ static void setupServer() { - switch (runmode) { - case SAMEVM: - try { - serverImpl = new BenchServerImpl(); - server = (BenchServer) RemoteObject.toStub(serverImpl); - } catch (Exception e) { - die("Error: failed to create local server: " + e); - } - if (verbose) - System.out.println("Benchmark server created locally"); - break; - - case CLIENT: - try { - Registry reg = LocateRegistry.getRegistry(host, port); - server = (BenchServer) reg.lookup(REGNAME); - } catch (Exception e) { - die("Error: failed to connect to server: " + e); - } - if (server == null) { - die("Error: server not found"); - } - if (verbose) { - System.out.println("Connected to benchmark server on " + - host + ":" + port); - } - break; - - case SERVER: - try { - Registry reg = LocateRegistry.createRegistry(port); - serverImpl = new BenchServerImpl(); - reg.bind(REGNAME, serverImpl); - } catch (Exception e) { - die("Error: failed to initialize server: " + e); - } - if (verbose) { - System.out.println("Benchmark server started on port " + - port); - } - break; - - default: - throw new InternalError("illegal runmode"); - } + switch (runmode) { + case SAMEVM: + try { + serverImpl = new BenchServerImpl(); + server = (BenchServer) RemoteObject.toStub(serverImpl); + } catch (Exception e) { + die("Error: failed to create local server: " + e); + } + if (verbose) + System.out.println("Benchmark server created locally"); + break; + + case CLIENT: + try { + Registry reg = LocateRegistry.getRegistry(host, port); + server = (BenchServer) reg.lookup(REGNAME); + } catch (Exception e) { + die("Error: failed to connect to server: " + e); + } + if (server == null) { + die("Error: server not found"); + } + if (verbose) { + System.out.println("Connected to benchmark server on " + + host + ":" + port); + } + break; + + case SERVER: + try { + Registry reg = LocateRegistry.createRegistry(port); + serverImpl = new BenchServerImpl(); + reg.bind(REGNAME, serverImpl); + } catch (Exception e) { + die("Error: failed to initialize server: " + e); + } + if (verbose) { + System.out.println("Benchmark server started on port " + + port); + } + break; + + default: + throw new InternalError("illegal runmode"); + } } /** * Set up the timer to end the test. * - * @param delay the amount of delay, in seconds, before requesting + * @param delay the amount of delay, in seconds, before requesting * the process exit */ static void setupTimer(int delay) { - timer = new Timer(true); + timer = new Timer(true); timer.schedule( new TimerTask() { public void run() { @@ -391,12 +391,12 @@ public class Main { } catch (ConfigFormatException e) { String errmsg = e.getMessage(); if (errmsg != null) { - die("Error parsing config file: " + errmsg); - } else { + die("Error parsing config file: " + errmsg); + } else { die("Error: illegal config file syntax"); - } + } } catch (IOException e) { - die("Error: failed to read config file"); + die("Error: failed to read config file"); } } @@ -405,24 +405,24 @@ public class Main { */ static void setupReporter() { String title = "RMI Benchmark, v" + VERSION; - switch (format) { - case TEXT: - reporter = new TextReporter(repstr, title); - break; - - case HTML: - reporter = new HtmlReporter(repstr, title); - break; + switch (format) { + case TEXT: + reporter = new TextReporter(repstr, title); + break; - case XML: - reporter = new XmlReporter(repstr, title); - break; - - default: - die("Error: unrecognized format type"); - } + case HTML: + reporter = new HtmlReporter(repstr, title); + break; + + case XML: + reporter = new XmlReporter(repstr, title); + break; + + default: + die("Error: unrecognized format type"); + } } - + /** * Run benchmarks. */ @@ -430,4 +430,3 @@ public class Main { harness.runBenchmarks(reporter, verbose); } } - diff --git a/jdk/test/java/rmi/reliability/benchmark/bench/rmi/NullCalls.java b/jdk/test/java/rmi/reliability/benchmark/bench/rmi/NullCalls.java index 7cd6a1c4313..0616f2e97f3 100644 --- a/jdk/test/java/rmi/reliability/benchmark/bench/rmi/NullCalls.java +++ b/jdk/test/java/rmi/reliability/benchmark/bench/rmi/NullCalls.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -38,39 +38,38 @@ import java.rmi.server.UnicastRemoteObject; public class NullCalls implements Benchmark { interface Server extends Remote { - public void call() throws RemoteException; + public void call() throws RemoteException; } static class ServerImpl extends UnicastRemoteObject implements Server { - public ServerImpl() throws RemoteException { - } - - public void call() throws RemoteException { - } + public ServerImpl() throws RemoteException { + } + + public void call() throws RemoteException { + } } - + static class ServerFactory implements BenchServer.RemoteObjectFactory { - public Remote create() throws RemoteException { - return new ServerImpl(); - } + public Remote create() throws RemoteException { + return new ServerImpl(); + } } - + /** * Issue null calls. * Arguments: <# calls> */ public long run(String[] args) throws Exception { - int reps = Integer.parseInt(args[0]); - BenchServer bsrv = Main.getBenchServer(); - Server stub = (Server) bsrv.create(new ServerFactory()); + int reps = Integer.parseInt(args[0]); + BenchServer bsrv = Main.getBenchServer(); + Server stub = (Server) bsrv.create(new ServerFactory()); - long start = System.currentTimeMillis(); - for (int i = 0; i < reps; i++) - stub.call(); - long time = System.currentTimeMillis() - start; - - bsrv.unexport(stub, true); - return time; + long start = System.currentTimeMillis(); + for (int i = 0; i < reps; i++) + stub.call(); + long time = System.currentTimeMillis() - start; + + bsrv.unexport(stub, true); + return time; } } - diff --git a/jdk/test/java/rmi/reliability/benchmark/bench/rmi/ObjArrayCalls.java b/jdk/test/java/rmi/reliability/benchmark/bench/rmi/ObjArrayCalls.java index a3835daad25..3fa66cdbc1c 100644 --- a/jdk/test/java/rmi/reliability/benchmark/bench/rmi/ObjArrayCalls.java +++ b/jdk/test/java/rmi/reliability/benchmark/bench/rmi/ObjArrayCalls.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -41,16 +41,16 @@ public class ObjArrayCalls implements Benchmark { static class Node implements Serializable { boolean z; - byte b; - char c; - short s; - int i; - float f; - long j; - double d; - String str = "bodega"; + byte b; + char c; + short s; + int i; + float f; + long j; + double d; + String str = "bodega"; Object parent, left, right; - + Node(Object parent, int depth) { this.parent = parent; if (depth > 0) { @@ -61,44 +61,43 @@ public class ObjArrayCalls implements Benchmark { } interface Server extends Remote { - public Node[] call(Node[] a) throws RemoteException; + public Node[] call(Node[] a) throws RemoteException; } static class ServerImpl extends UnicastRemoteObject implements Server { - public ServerImpl() throws RemoteException { - } + public ServerImpl() throws RemoteException { + } - public Node[] call(Node[] a) throws RemoteException { - return a; - } + public Node[] call(Node[] a) throws RemoteException { + return a; + } } - + static class ServerFactory implements BenchServer.RemoteObjectFactory { - public Remote create() throws RemoteException { - return new ServerImpl(); - } + public Remote create() throws RemoteException { + return new ServerImpl(); + } } - + /** * Issue calls using arrays of objects as parameters/return values. * Arguments: <# calls> */ public long run(String[] args) throws Exception { - int size = Integer.parseInt(args[0]); - int reps = Integer.parseInt(args[1]); - BenchServer bsrv = Main.getBenchServer(); - Server stub = (Server) bsrv.create(new ServerFactory()); - Node[] nodes = new Node[size]; - for (int i = 0; i < size; i++) - nodes[i] = new Node(null, 0); + int size = Integer.parseInt(args[0]); + int reps = Integer.parseInt(args[1]); + BenchServer bsrv = Main.getBenchServer(); + Server stub = (Server) bsrv.create(new ServerFactory()); + Node[] nodes = new Node[size]; + for (int i = 0; i < size; i++) + nodes[i] = new Node(null, 0); - long start = System.currentTimeMillis(); - for (int i = 0; i < reps; i++) - stub.call(nodes); - long time = System.currentTimeMillis() - start; - - bsrv.unexport(stub, true); - return time; + long start = System.currentTimeMillis(); + for (int i = 0; i < reps; i++) + stub.call(nodes); + long time = System.currentTimeMillis() - start; + + bsrv.unexport(stub, true); + return time; } } - diff --git a/jdk/test/java/rmi/reliability/benchmark/bench/rmi/ObjTreeCalls.java b/jdk/test/java/rmi/reliability/benchmark/bench/rmi/ObjTreeCalls.java index bcf9fad7f2e..02a9f066f80 100644 --- a/jdk/test/java/rmi/reliability/benchmark/bench/rmi/ObjTreeCalls.java +++ b/jdk/test/java/rmi/reliability/benchmark/bench/rmi/ObjTreeCalls.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -41,16 +41,16 @@ public class ObjTreeCalls implements Benchmark { static class Node implements Serializable { boolean z; - byte b; - char c; - short s; - int i; - float f; - long j; - double d; - String str = "bodega"; + byte b; + char c; + short s; + int i; + float f; + long j; + double d; + String str = "bodega"; Object parent, left, right; - + Node(Object parent, int depth) { this.parent = parent; if (depth > 0) { @@ -61,42 +61,41 @@ public class ObjTreeCalls implements Benchmark { } interface Server extends Remote { - public Node call(Node val) throws RemoteException; + public Node call(Node val) throws RemoteException; } static class ServerImpl extends UnicastRemoteObject implements Server { - public ServerImpl() throws RemoteException { - } + public ServerImpl() throws RemoteException { + } - public Node call(Node val) throws RemoteException { - return val; - } + public Node call(Node val) throws RemoteException { + return val; + } } - + static class ServerFactory implements BenchServer.RemoteObjectFactory { - public Remote create() throws RemoteException { - return new ServerImpl(); - } + public Remote create() throws RemoteException { + return new ServerImpl(); + } } - + /** * Issue calls using trees of objects as parameters/return values. * Arguments: <# calls> */ public long run(String[] args) throws Exception { - int depth = Integer.parseInt(args[0]); - int reps = Integer.parseInt(args[1]); - BenchServer bsrv = Main.getBenchServer(); - Server stub = (Server) bsrv.create(new ServerFactory()); - Node node = new Node(null, depth); + int depth = Integer.parseInt(args[0]); + int reps = Integer.parseInt(args[1]); + BenchServer bsrv = Main.getBenchServer(); + Server stub = (Server) bsrv.create(new ServerFactory()); + Node node = new Node(null, depth); - long start = System.currentTimeMillis(); - for (int i = 0; i < reps; i++) - stub.call(node); - long time = System.currentTimeMillis() - start; - - bsrv.unexport(stub, true); - return time; + long start = System.currentTimeMillis(); + for (int i = 0; i < reps; i++) + stub.call(node); + long time = System.currentTimeMillis() - start; + + bsrv.unexport(stub, true); + return time; } } - diff --git a/jdk/test/java/rmi/reliability/benchmark/bench/rmi/ProxyArrayCalls.java b/jdk/test/java/rmi/reliability/benchmark/bench/rmi/ProxyArrayCalls.java index 0ab713af6ea..7242a4f31a8 100644 --- a/jdk/test/java/rmi/reliability/benchmark/bench/rmi/ProxyArrayCalls.java +++ b/jdk/test/java/rmi/reliability/benchmark/bench/rmi/ProxyArrayCalls.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -44,52 +44,52 @@ import java.rmi.server.UnicastRemoteObject; public class ProxyArrayCalls implements Benchmark { static class DummyHandler implements InvocationHandler, Serializable { - public Object invoke(Object proxy, Method method, Object[] args) - throws Throwable - { - return null; - } + public Object invoke(Object proxy, Method method, Object[] args) + throws Throwable + { + return null; + } } - + public static interface DummyInterface { - public void foo(); + public void foo(); } interface Server extends Remote { - public Proxy[] call(Proxy[] a) throws RemoteException; + public Proxy[] call(Proxy[] a) throws RemoteException; } static class ServerImpl extends UnicastRemoteObject implements Server { - public ServerImpl() throws RemoteException { - } + public ServerImpl() throws RemoteException { + } - public Proxy[] call(Proxy[] a) throws RemoteException { - return a; - } + public Proxy[] call(Proxy[] a) throws RemoteException { + return a; + } } - + static class ServerFactory implements BenchServer.RemoteObjectFactory { - public Remote create() throws RemoteException { - return new ServerImpl(); - } + public Remote create() throws RemoteException { + return new ServerImpl(); + } } - + /** * Generate proxy object array of the given size. */ Proxy[] genProxies(int size) throws Exception { - Class proxyClass = - Proxy.getProxyClass(DummyInterface.class.getClassLoader(), - new Class[] { DummyInterface.class }); - Constructor proxyCons = - proxyClass.getConstructor(new Class[] { InvocationHandler.class }); - Object[] consArgs = new Object[] { new DummyHandler() }; - Proxy[] proxies = new Proxy[size]; + Class proxyClass = + Proxy.getProxyClass(DummyInterface.class.getClassLoader(), + new Class[] { DummyInterface.class }); + Constructor proxyCons = + proxyClass.getConstructor(new Class[] { InvocationHandler.class }); + Object[] consArgs = new Object[] { new DummyHandler() }; + Proxy[] proxies = new Proxy[size]; - for (int i = 0; i < size; i++) - proxies[i] = (Proxy) proxyCons.newInstance(consArgs); + for (int i = 0; i < size; i++) + proxies[i] = (Proxy) proxyCons.newInstance(consArgs); - return proxies; + return proxies; } /** @@ -97,19 +97,18 @@ public class ProxyArrayCalls implements Benchmark { * Arguments: <# calls> */ public long run(String[] args) throws Exception { - int size = Integer.parseInt(args[0]); - int reps = Integer.parseInt(args[1]); - BenchServer bsrv = Main.getBenchServer(); - Server stub = (Server) bsrv.create(new ServerFactory()); - Proxy[] proxies = genProxies(size); + int size = Integer.parseInt(args[0]); + int reps = Integer.parseInt(args[1]); + BenchServer bsrv = Main.getBenchServer(); + Server stub = (Server) bsrv.create(new ServerFactory()); + Proxy[] proxies = genProxies(size); - long start = System.currentTimeMillis(); - for (int i = 0; i < reps; i++) - stub.call(proxies); - long time = System.currentTimeMillis() - start; - - bsrv.unexport(stub, true); - return time; + long start = System.currentTimeMillis(); + for (int i = 0; i < reps; i++) + stub.call(proxies); + long time = System.currentTimeMillis() - start; + + bsrv.unexport(stub, true); + return time; } } - diff --git a/jdk/test/java/rmi/reliability/benchmark/bench/rmi/RemoteObjArrayCalls.java b/jdk/test/java/rmi/reliability/benchmark/bench/rmi/RemoteObjArrayCalls.java index d8a6ec8905d..5bf6a3b929a 100644 --- a/jdk/test/java/rmi/reliability/benchmark/bench/rmi/RemoteObjArrayCalls.java +++ b/jdk/test/java/rmi/reliability/benchmark/bench/rmi/RemoteObjArrayCalls.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -39,49 +39,48 @@ import java.rmi.server.UnicastRemoteObject; public class RemoteObjArrayCalls implements Benchmark { static class RemoteObj extends UnicastRemoteObject implements Remote { - RemoteObj() throws RemoteException { - } + RemoteObj() throws RemoteException { + } } interface Server extends Remote { - public Remote[] call(Remote[] a) throws RemoteException; + public Remote[] call(Remote[] a) throws RemoteException; } static class ServerImpl extends UnicastRemoteObject implements Server { - public ServerImpl() throws RemoteException { - } + public ServerImpl() throws RemoteException { + } - public Remote[] call(Remote[] a) throws RemoteException { - return a; - } + public Remote[] call(Remote[] a) throws RemoteException { + return a; + } } - + static class ServerFactory implements BenchServer.RemoteObjectFactory { - public Remote create() throws RemoteException { - return new ServerImpl(); - } + public Remote create() throws RemoteException { + return new ServerImpl(); + } } - + /** * Issue calls using arrays of remote objects as parameters/return values. * Arguments: <# calls> */ public long run(String[] args) throws Exception { - int size = Integer.parseInt(args[0]); - int reps = Integer.parseInt(args[1]); - BenchServer bsrv = Main.getBenchServer(); - Server stub = (Server) bsrv.create(new ServerFactory()); - Remote[] objs = new Remote[size]; - for (int i = 0; i < size; i++) - objs[i] = new RemoteObj(); + int size = Integer.parseInt(args[0]); + int reps = Integer.parseInt(args[1]); + BenchServer bsrv = Main.getBenchServer(); + Server stub = (Server) bsrv.create(new ServerFactory()); + Remote[] objs = new Remote[size]; + for (int i = 0; i < size; i++) + objs[i] = new RemoteObj(); - long start = System.currentTimeMillis(); - for (int i = 0; i < reps; i++) - stub.call(objs); - long time = System.currentTimeMillis() - start; - - bsrv.unexport(stub, true); - return time; + long start = System.currentTimeMillis(); + for (int i = 0; i < reps; i++) + stub.call(objs); + long time = System.currentTimeMillis() - start; + + bsrv.unexport(stub, true); + return time; } } - diff --git a/jdk/test/java/rmi/reliability/benchmark/bench/rmi/ShortArrayCalls.java b/jdk/test/java/rmi/reliability/benchmark/bench/rmi/ShortArrayCalls.java index 76432712caa..91589b8d401 100644 --- a/jdk/test/java/rmi/reliability/benchmark/bench/rmi/ShortArrayCalls.java +++ b/jdk/test/java/rmi/reliability/benchmark/bench/rmi/ShortArrayCalls.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -20,7 +20,7 @@ * CA 95054 USA or visit www.sun.com if you need additional information or * have any questions. */ - + /* * */ @@ -39,42 +39,41 @@ import java.rmi.server.UnicastRemoteObject; public class ShortArrayCalls implements Benchmark { interface Server extends Remote { - public short[] call(short[] a) throws RemoteException; + public short[] call(short[] a) throws RemoteException; } static class ServerImpl extends UnicastRemoteObject implements Server { - public ServerImpl() throws RemoteException { - } - - public short[] call(short[] a) throws RemoteException { - return a; - } + public ServerImpl() throws RemoteException { + } + + public short[] call(short[] a) throws RemoteException { + return a; + } } - + static class ServerFactory implements BenchServer.RemoteObjectFactory { - public Remote create() throws RemoteException { - return new ServerImpl(); - } + public Remote create() throws RemoteException { + return new ServerImpl(); + } } - + /** * Issue short array calls. * Arguments: <# calls> */ public long run(String[] args) throws Exception { - int size = Integer.parseInt(args[0]); - int reps = Integer.parseInt(args[1]); - BenchServer bsrv = Main.getBenchServer(); - Server stub = (Server) bsrv.create(new ServerFactory()); - short[] array = new short[size]; + int size = Integer.parseInt(args[0]); + int reps = Integer.parseInt(args[1]); + BenchServer bsrv = Main.getBenchServer(); + Server stub = (Server) bsrv.create(new ServerFactory()); + short[] array = new short[size]; - long start = System.currentTimeMillis(); - for (int i = 0; i < reps; i++) - stub.call(array); - long time = System.currentTimeMillis() - start; - - bsrv.unexport(stub, true); - return time; + long start = System.currentTimeMillis(); + for (int i = 0; i < reps; i++) + stub.call(array); + long time = System.currentTimeMillis() - start; + + bsrv.unexport(stub, true); + return time; } } - diff --git a/jdk/test/java/rmi/reliability/benchmark/bench/rmi/ShortCalls.java b/jdk/test/java/rmi/reliability/benchmark/bench/rmi/ShortCalls.java index 867ebef8530..2ba8e0f3acc 100644 --- a/jdk/test/java/rmi/reliability/benchmark/bench/rmi/ShortCalls.java +++ b/jdk/test/java/rmi/reliability/benchmark/bench/rmi/ShortCalls.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -38,40 +38,39 @@ import java.rmi.server.UnicastRemoteObject; public class ShortCalls implements Benchmark { interface Server extends Remote { - public short call(short val) throws RemoteException; + public short call(short val) throws RemoteException; } static class ServerImpl extends UnicastRemoteObject implements Server { - public ServerImpl() throws RemoteException { - } - - public short call(short val) throws RemoteException { - return val; - } + public ServerImpl() throws RemoteException { + } + + public short call(short val) throws RemoteException { + return val; + } } - + static class ServerFactory implements BenchServer.RemoteObjectFactory { - public Remote create() throws RemoteException { - return new ServerImpl(); - } + public Remote create() throws RemoteException { + return new ServerImpl(); + } } - + /** * Issue short calls. * Arguments: <# calls> */ public long run(String[] args) throws Exception { - int cycles = Integer.parseInt(args[0]); - BenchServer bsrv = Main.getBenchServer(); - Server stub = (Server) bsrv.create(new ServerFactory()); + int cycles = Integer.parseInt(args[0]); + BenchServer bsrv = Main.getBenchServer(); + Server stub = (Server) bsrv.create(new ServerFactory()); - long start = System.currentTimeMillis(); - for (int i = 0; i < cycles; i++) - stub.call((short) 0); - long time = System.currentTimeMillis() - start; - - bsrv.unexport(stub, true); - return time; + long start = System.currentTimeMillis(); + for (int i = 0; i < cycles; i++) + stub.call((short) 0); + long time = System.currentTimeMillis() - start; + + bsrv.unexport(stub, true); + return time; } } - diff --git a/jdk/test/java/rmi/reliability/benchmark/bench/rmi/SmallObjTreeCalls.java b/jdk/test/java/rmi/reliability/benchmark/bench/rmi/SmallObjTreeCalls.java index 29829d6ec91..a43defb5234 100644 --- a/jdk/test/java/rmi/reliability/benchmark/bench/rmi/SmallObjTreeCalls.java +++ b/jdk/test/java/rmi/reliability/benchmark/bench/rmi/SmallObjTreeCalls.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -41,7 +41,7 @@ public class SmallObjTreeCalls implements Benchmark { static class Node implements Serializable { Object parent, left, right; - + Node(Object parent, int depth) { this.parent = parent; if (depth > 0) { @@ -52,42 +52,41 @@ public class SmallObjTreeCalls implements Benchmark { } interface Server extends Remote { - public Node call(Node val) throws RemoteException; + public Node call(Node val) throws RemoteException; } static class ServerImpl extends UnicastRemoteObject implements Server { - public ServerImpl() throws RemoteException { - } + public ServerImpl() throws RemoteException { + } - public Node call(Node val) throws RemoteException { - return val; - } + public Node call(Node val) throws RemoteException { + return val; + } } - + static class ServerFactory implements BenchServer.RemoteObjectFactory { - public Remote create() throws RemoteException { - return new ServerImpl(); - } + public Remote create() throws RemoteException { + return new ServerImpl(); + } } - + /** * Issue calls using trees of small objects as parameters/return values. * Arguments: <# calls> */ public long run(String[] args) throws Exception { - int depth = Integer.parseInt(args[0]); - int reps = Integer.parseInt(args[1]); - BenchServer bsrv = Main.getBenchServer(); - Server stub = (Server) bsrv.create(new ServerFactory()); - Node node = new Node(null, depth); + int depth = Integer.parseInt(args[0]); + int reps = Integer.parseInt(args[1]); + BenchServer bsrv = Main.getBenchServer(); + Server stub = (Server) bsrv.create(new ServerFactory()); + Node node = new Node(null, depth); - long start = System.currentTimeMillis(); - for (int i = 0; i < reps; i++) - stub.call(node); - long time = System.currentTimeMillis() - start; - - bsrv.unexport(stub, true); - return time; + long start = System.currentTimeMillis(); + for (int i = 0; i < reps; i++) + stub.call(node); + long time = System.currentTimeMillis() - start; + + bsrv.unexport(stub, true); + return time; } } - diff --git a/jdk/test/java/rmi/reliability/benchmark/bench/serial/BooleanArrays.java b/jdk/test/java/rmi/reliability/benchmark/bench/serial/BooleanArrays.java index d52fdcf2052..5e6ff7656aa 100644 --- a/jdk/test/java/rmi/reliability/benchmark/bench/serial/BooleanArrays.java +++ b/jdk/test/java/rmi/reliability/benchmark/bench/serial/BooleanArrays.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -35,7 +35,7 @@ import java.io.ObjectOutputStream; * Benchmark for testing speed of boolean array reads/writes. */ public class BooleanArrays implements Benchmark { - + /** * Write and read boolean arrays to/from a stream. The benchmark is run in * batches, with each batch consisting of a fixed number of read/write @@ -44,44 +44,42 @@ public class BooleanArrays implements Benchmark { * Arguments: <# batches> <# cycles per batch> */ public long run(String[] args) throws Exception { - int size = Integer.parseInt(args[0]); - int nbatches = Integer.parseInt(args[1]); - int ncycles = Integer.parseInt(args[2]); - boolean[][] arrays = new boolean[ncycles][size]; - StreamBuffer sbuf = new StreamBuffer(); - ObjectOutputStream oout = - new ObjectOutputStream(sbuf.getOutputStream()); - ObjectInputStream oin = - new ObjectInputStream(sbuf.getInputStream()); + int size = Integer.parseInt(args[0]); + int nbatches = Integer.parseInt(args[1]); + int ncycles = Integer.parseInt(args[2]); + boolean[][] arrays = new boolean[ncycles][size]; + StreamBuffer sbuf = new StreamBuffer(); + ObjectOutputStream oout = + new ObjectOutputStream(sbuf.getOutputStream()); + ObjectInputStream oin = + new ObjectInputStream(sbuf.getInputStream()); - doReps(oout, oin, sbuf, arrays, 1); // warmup + doReps(oout, oin, sbuf, arrays, 1); // warmup - long start = System.currentTimeMillis(); - doReps(oout, oin, sbuf, arrays, nbatches); + long start = System.currentTimeMillis(); + doReps(oout, oin, sbuf, arrays, nbatches); return System.currentTimeMillis() - start; } - + /** * Run benchmark for given number of batches, with given number of cycles * for each batch. */ void doReps(ObjectOutputStream oout, ObjectInputStream oin, - StreamBuffer sbuf, boolean[][] arrays, int nbatches) - throws Exception + StreamBuffer sbuf, boolean[][] arrays, int nbatches) + throws Exception { - int ncycles = arrays.length; - for (int i = 0; i < nbatches; i++) { - sbuf.reset(); - oout.reset(); - for (int j = 0; j < ncycles; j++) { - oout.writeObject(arrays[j]); - } - oout.flush(); - for (int j = 0; j < ncycles; j++) { - oin.readObject(); - } - } + int ncycles = arrays.length; + for (int i = 0; i < nbatches; i++) { + sbuf.reset(); + oout.reset(); + for (int j = 0; j < ncycles; j++) { + oout.writeObject(arrays[j]); + } + oout.flush(); + for (int j = 0; j < ncycles; j++) { + oin.readObject(); + } + } } } - - diff --git a/jdk/test/java/rmi/reliability/benchmark/bench/serial/Booleans.java b/jdk/test/java/rmi/reliability/benchmark/bench/serial/Booleans.java index 690d4ac190d..abf8ef8c5e8 100644 --- a/jdk/test/java/rmi/reliability/benchmark/bench/serial/Booleans.java +++ b/jdk/test/java/rmi/reliability/benchmark/bench/serial/Booleans.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -35,7 +35,7 @@ import java.io.ObjectOutputStream; * Benchmark for testing speed of boolean reads/writes. */ public class Booleans implements Benchmark { - + /** * Write and read boolean values to/from a stream. The benchmark is run in * batches: each "batch" consists of a fixed number of read/write cycles, @@ -44,40 +44,38 @@ public class Booleans implements Benchmark { * Arguments: <# batches> <# cycles per batch> */ public long run(String[] args) throws Exception { - int nbatches = Integer.parseInt(args[0]); - int ncycles = Integer.parseInt(args[1]); - StreamBuffer sbuf = new StreamBuffer(); - ObjectOutputStream oout = - new ObjectOutputStream(sbuf.getOutputStream()); - ObjectInputStream oin = - new ObjectInputStream(sbuf.getInputStream()); - - doReps(oout, oin, sbuf, 1, ncycles); // warmup + int nbatches = Integer.parseInt(args[0]); + int ncycles = Integer.parseInt(args[1]); + StreamBuffer sbuf = new StreamBuffer(); + ObjectOutputStream oout = + new ObjectOutputStream(sbuf.getOutputStream()); + ObjectInputStream oin = + new ObjectInputStream(sbuf.getInputStream()); - long start = System.currentTimeMillis(); - doReps(oout, oin, sbuf, nbatches, ncycles); + doReps(oout, oin, sbuf, 1, ncycles); // warmup + + long start = System.currentTimeMillis(); + doReps(oout, oin, sbuf, nbatches, ncycles); return System.currentTimeMillis() - start; } - + /** * Run benchmark for given number of batches, with given number of cycles * for each batch. */ void doReps(ObjectOutputStream oout, ObjectInputStream oin, - StreamBuffer sbuf, int nbatches, int ncycles) - throws Exception + StreamBuffer sbuf, int nbatches, int ncycles) + throws Exception { - for (int i = 0; i < nbatches; i++) { - sbuf.reset(); - for (int j = 0; j < ncycles; j++) { - oout.writeBoolean(false); - } - oout.flush(); - for (int j = 0; j < ncycles; j++) { - oin.readBoolean(); - } - } + for (int i = 0; i < nbatches; i++) { + sbuf.reset(); + for (int j = 0; j < ncycles; j++) { + oout.writeBoolean(false); + } + oout.flush(); + for (int j = 0; j < ncycles; j++) { + oin.readBoolean(); + } + } } } - - diff --git a/jdk/test/java/rmi/reliability/benchmark/bench/serial/ByteArrays.java b/jdk/test/java/rmi/reliability/benchmark/bench/serial/ByteArrays.java index 5c21de5b14a..b300e8af79b 100644 --- a/jdk/test/java/rmi/reliability/benchmark/bench/serial/ByteArrays.java +++ b/jdk/test/java/rmi/reliability/benchmark/bench/serial/ByteArrays.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -35,7 +35,7 @@ import java.io.ObjectOutputStream; * Benchmark for testing speed of byte array reads/writes. */ public class ByteArrays implements Benchmark { - + /** * Write and read byte arrays to/from a stream. The benchmark is run in * batches, with each batch consisting of a fixed number of read/write @@ -44,44 +44,42 @@ public class ByteArrays implements Benchmark { * Arguments: <# batches> <# cycles per batch> */ public long run(String[] args) throws Exception { - int size = Integer.parseInt(args[0]); - int nbatches = Integer.parseInt(args[1]); - int ncycles = Integer.parseInt(args[2]); - byte[][] arrays = new byte[ncycles][size]; - StreamBuffer sbuf = new StreamBuffer(); - ObjectOutputStream oout = - new ObjectOutputStream(sbuf.getOutputStream()); - ObjectInputStream oin = - new ObjectInputStream(sbuf.getInputStream()); + int size = Integer.parseInt(args[0]); + int nbatches = Integer.parseInt(args[1]); + int ncycles = Integer.parseInt(args[2]); + byte[][] arrays = new byte[ncycles][size]; + StreamBuffer sbuf = new StreamBuffer(); + ObjectOutputStream oout = + new ObjectOutputStream(sbuf.getOutputStream()); + ObjectInputStream oin = + new ObjectInputStream(sbuf.getInputStream()); - doReps(oout, oin, sbuf, arrays, 1); // warmup + doReps(oout, oin, sbuf, arrays, 1); // warmup - long start = System.currentTimeMillis(); - doReps(oout, oin, sbuf, arrays, nbatches); + long start = System.currentTimeMillis(); + doReps(oout, oin, sbuf, arrays, nbatches); return System.currentTimeMillis() - start; } - + /** * Run benchmark for given number of batches, with given number of cycles * for each batch. */ void doReps(ObjectOutputStream oout, ObjectInputStream oin, - StreamBuffer sbuf, byte[][] arrays, int nbatches) - throws Exception + StreamBuffer sbuf, byte[][] arrays, int nbatches) + throws Exception { - int ncycles = arrays.length; - for (int i = 0; i < nbatches; i++) { - sbuf.reset(); - oout.reset(); - for (int j = 0; j < ncycles; j++) { - oout.writeObject(arrays[j]); - } - oout.flush(); - for (int j = 0; j < ncycles; j++) { - oin.readObject(); - } - } + int ncycles = arrays.length; + for (int i = 0; i < nbatches; i++) { + sbuf.reset(); + oout.reset(); + for (int j = 0; j < ncycles; j++) { + oout.writeObject(arrays[j]); + } + oout.flush(); + for (int j = 0; j < ncycles; j++) { + oin.readObject(); + } + } } } - - diff --git a/jdk/test/java/rmi/reliability/benchmark/bench/serial/Bytes.java b/jdk/test/java/rmi/reliability/benchmark/bench/serial/Bytes.java index 585f6b18208..31d6465c30c 100644 --- a/jdk/test/java/rmi/reliability/benchmark/bench/serial/Bytes.java +++ b/jdk/test/java/rmi/reliability/benchmark/bench/serial/Bytes.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -35,7 +35,7 @@ import java.io.ObjectOutputStream; * Benchmark for testing speed of byte reads/writes. */ public class Bytes implements Benchmark { - + /** * Write and read byte values to/from a stream. The benchmark is run in * batches: each "batch" consists of a fixed number of read/write cycles, @@ -44,39 +44,38 @@ public class Bytes implements Benchmark { * Arguments: <# batches> <# cycles per batch> */ public long run(String[] args) throws Exception { - int nbatches = Integer.parseInt(args[0]); - int ncycles = Integer.parseInt(args[1]); - StreamBuffer sbuf = new StreamBuffer(); - ObjectOutputStream oout = - new ObjectOutputStream(sbuf.getOutputStream()); - ObjectInputStream oin = - new ObjectInputStream(sbuf.getInputStream()); - - doReps(oout, oin, sbuf, 1, ncycles); // warmup + int nbatches = Integer.parseInt(args[0]); + int ncycles = Integer.parseInt(args[1]); + StreamBuffer sbuf = new StreamBuffer(); + ObjectOutputStream oout = + new ObjectOutputStream(sbuf.getOutputStream()); + ObjectInputStream oin = + new ObjectInputStream(sbuf.getInputStream()); - long start = System.currentTimeMillis(); - doReps(oout, oin, sbuf, nbatches, ncycles); + doReps(oout, oin, sbuf, 1, ncycles); // warmup + + long start = System.currentTimeMillis(); + doReps(oout, oin, sbuf, nbatches, ncycles); return System.currentTimeMillis() - start; } - + /** * Run benchmark for given number of batches, with given number of cycles * for each batch. */ void doReps(ObjectOutputStream oout, ObjectInputStream oin, - StreamBuffer sbuf, int nbatches, int ncycles) - throws Exception + StreamBuffer sbuf, int nbatches, int ncycles) + throws Exception { - for (int i = 0; i < nbatches; i++) { - sbuf.reset(); - for (int j = 0; j < ncycles; j++) { - oout.writeByte(0); - } - oout.flush(); - for (int j = 0; j < ncycles; j++) { - oin.readByte(); - } - } + for (int i = 0; i < nbatches; i++) { + sbuf.reset(); + for (int j = 0; j < ncycles; j++) { + oout.writeByte(0); + } + oout.flush(); + for (int j = 0; j < ncycles; j++) { + oin.readByte(); + } + } } } - diff --git a/jdk/test/java/rmi/reliability/benchmark/bench/serial/CharArrays.java b/jdk/test/java/rmi/reliability/benchmark/bench/serial/CharArrays.java index e1cec28e566..a9b1353b06f 100644 --- a/jdk/test/java/rmi/reliability/benchmark/bench/serial/CharArrays.java +++ b/jdk/test/java/rmi/reliability/benchmark/bench/serial/CharArrays.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -35,7 +35,7 @@ import java.io.ObjectOutputStream; * Benchmark for testing speed of char array reads/writes. */ public class CharArrays implements Benchmark { - + /** * Write and read char arrays to/from a stream. The benchmark is run in * batches, with each batch consisting of a fixed number of read/write @@ -44,44 +44,42 @@ public class CharArrays implements Benchmark { * Arguments: <# batches> <# cycles per batch> */ public long run(String[] args) throws Exception { - int size = Integer.parseInt(args[0]); - int nbatches = Integer.parseInt(args[1]); - int ncycles = Integer.parseInt(args[2]); - char[][] arrays = new char[ncycles][size]; - StreamBuffer sbuf = new StreamBuffer(); - ObjectOutputStream oout = - new ObjectOutputStream(sbuf.getOutputStream()); - ObjectInputStream oin = - new ObjectInputStream(sbuf.getInputStream()); + int size = Integer.parseInt(args[0]); + int nbatches = Integer.parseInt(args[1]); + int ncycles = Integer.parseInt(args[2]); + char[][] arrays = new char[ncycles][size]; + StreamBuffer sbuf = new StreamBuffer(); + ObjectOutputStream oout = + new ObjectOutputStream(sbuf.getOutputStream()); + ObjectInputStream oin = + new ObjectInputStream(sbuf.getInputStream()); - doReps(oout, oin, sbuf, arrays, 1); // warmup + doReps(oout, oin, sbuf, arrays, 1); // warmup - long start = System.currentTimeMillis(); - doReps(oout, oin, sbuf, arrays, nbatches); + long start = System.currentTimeMillis(); + doReps(oout, oin, sbuf, arrays, nbatches); return System.currentTimeMillis() - start; } - + /** * Run benchmark for given number of batches, with given number of cycles * for each batch. */ void doReps(ObjectOutputStream oout, ObjectInputStream oin, - StreamBuffer sbuf, char[][] arrays, int nbatches) - throws Exception + StreamBuffer sbuf, char[][] arrays, int nbatches) + throws Exception { - int ncycles = arrays.length; - for (int i = 0; i < nbatches; i++) { - sbuf.reset(); - oout.reset(); - for (int j = 0; j < ncycles; j++) { - oout.writeObject(arrays[j]); - } - oout.flush(); - for (int j = 0; j < ncycles; j++) { - oin.readObject(); - } - } + int ncycles = arrays.length; + for (int i = 0; i < nbatches; i++) { + sbuf.reset(); + oout.reset(); + for (int j = 0; j < ncycles; j++) { + oout.writeObject(arrays[j]); + } + oout.flush(); + for (int j = 0; j < ncycles; j++) { + oin.readObject(); + } + } } } - - diff --git a/jdk/test/java/rmi/reliability/benchmark/bench/serial/Chars.java b/jdk/test/java/rmi/reliability/benchmark/bench/serial/Chars.java index 835bb6dc010..1ee2c88ed6e 100644 --- a/jdk/test/java/rmi/reliability/benchmark/bench/serial/Chars.java +++ b/jdk/test/java/rmi/reliability/benchmark/bench/serial/Chars.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -35,7 +35,7 @@ import java.io.ObjectOutputStream; * Benchmark for testing speed of char reads/writes. */ public class Chars implements Benchmark { - + /** * Write and read char values to/from a stream. The benchmark is run in * batches: each "batch" consists of a fixed number of read/write cycles, @@ -44,39 +44,38 @@ public class Chars implements Benchmark { * Arguments: <# batches> <# cycles per batch> */ public long run(String[] args) throws Exception { - int nbatches = Integer.parseInt(args[0]); - int ncycles = Integer.parseInt(args[1]); - StreamBuffer sbuf = new StreamBuffer(); - ObjectOutputStream oout = - new ObjectOutputStream(sbuf.getOutputStream()); - ObjectInputStream oin = - new ObjectInputStream(sbuf.getInputStream()); - - doReps(oout, oin, sbuf, 1, ncycles); // warmup + int nbatches = Integer.parseInt(args[0]); + int ncycles = Integer.parseInt(args[1]); + StreamBuffer sbuf = new StreamBuffer(); + ObjectOutputStream oout = + new ObjectOutputStream(sbuf.getOutputStream()); + ObjectInputStream oin = + new ObjectInputStream(sbuf.getInputStream()); - long start = System.currentTimeMillis(); - doReps(oout, oin, sbuf, nbatches, ncycles); + doReps(oout, oin, sbuf, 1, ncycles); // warmup + + long start = System.currentTimeMillis(); + doReps(oout, oin, sbuf, nbatches, ncycles); return System.currentTimeMillis() - start; } - + /** * Run benchmark for given number of batches, with given number of cycles * for each batch. */ void doReps(ObjectOutputStream oout, ObjectInputStream oin, - StreamBuffer sbuf, int nbatches, int ncycles) - throws Exception + StreamBuffer sbuf, int nbatches, int ncycles) + throws Exception { - for (int i = 0; i < nbatches; i++) { - sbuf.reset(); - for (int j = 0; j < ncycles; j++) { - oout.writeChar('0'); - } - oout.flush(); - for (int j = 0; j < ncycles; j++) { - oin.readChar(); - } - } + for (int i = 0; i < nbatches; i++) { + sbuf.reset(); + for (int j = 0; j < ncycles; j++) { + oout.writeChar('0'); + } + oout.flush(); + for (int j = 0; j < ncycles; j++) { + oin.readChar(); + } + } } } - diff --git a/jdk/test/java/rmi/reliability/benchmark/bench/serial/ClassDesc.java b/jdk/test/java/rmi/reliability/benchmark/bench/serial/ClassDesc.java index 47895b560c6..a7ad155ceb0 100644 --- a/jdk/test/java/rmi/reliability/benchmark/bench/serial/ClassDesc.java +++ b/jdk/test/java/rmi/reliability/benchmark/bench/serial/ClassDesc.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -89,41 +89,40 @@ public class ClassDesc implements Benchmark { static class Dummy48 extends Dummy47 { Dummy48 i48; } static class Dummy49 extends Dummy48 { Dummy49 i49; } static class Dummy50 extends Dummy49 { Dummy50 i50; } - + /** * Write and read class descriptors to/from a stream. * Arguments: <# cycles> */ public long run(String[] args) throws Exception { - int ncycles = Integer.parseInt(args[0]); - StreamBuffer sbuf = new StreamBuffer(); - ObjectOutputStream oout = - new ObjectOutputStream(sbuf.getOutputStream()); - ObjectInputStream oin = - new ObjectInputStream(sbuf.getInputStream()); - ObjectStreamClass desc = ObjectStreamClass.lookup(Dummy50.class); - - doReps(oout, oin, sbuf, desc, 1); // warmup + int ncycles = Integer.parseInt(args[0]); + StreamBuffer sbuf = new StreamBuffer(); + ObjectOutputStream oout = + new ObjectOutputStream(sbuf.getOutputStream()); + ObjectInputStream oin = + new ObjectInputStream(sbuf.getInputStream()); + ObjectStreamClass desc = ObjectStreamClass.lookup(Dummy50.class); - long start = System.currentTimeMillis(); - doReps(oout, oin, sbuf, desc, ncycles); + doReps(oout, oin, sbuf, desc, 1); // warmup + + long start = System.currentTimeMillis(); + doReps(oout, oin, sbuf, desc, ncycles); return System.currentTimeMillis() - start; } - + /** * Run benchmark for given number of cycles. */ void doReps(ObjectOutputStream oout, ObjectInputStream oin, - StreamBuffer sbuf, ObjectStreamClass desc, int ncycles) - throws Exception + StreamBuffer sbuf, ObjectStreamClass desc, int ncycles) + throws Exception { - for (int i = 0; i < ncycles; i++) { - sbuf.reset(); - oout.reset(); - oout.writeObject(desc); - oout.flush(); - oin.readObject(); - } + for (int i = 0; i < ncycles; i++) { + sbuf.reset(); + oout.reset(); + oout.writeObject(desc); + oout.flush(); + oin.readObject(); + } } } - diff --git a/jdk/test/java/rmi/reliability/benchmark/bench/serial/Cons.java b/jdk/test/java/rmi/reliability/benchmark/bench/serial/Cons.java index 7d6bb08ceb1..99d58c05472 100644 --- a/jdk/test/java/rmi/reliability/benchmark/bench/serial/Cons.java +++ b/jdk/test/java/rmi/reliability/benchmark/bench/serial/Cons.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -53,29 +53,28 @@ public class Cons implements Benchmark { public long run(String[] args) throws Exception { int reps = Integer.parseInt(args[0]); Dummy dummy = new Dummy(); - StreamBuffer sbuf = new StreamBuffer(); - - doReps(sbuf, dummy, 1); // warmup + StreamBuffer sbuf = new StreamBuffer(); - long start = System.currentTimeMillis(); - doReps(sbuf, dummy, reps); + doReps(sbuf, dummy, 1); // warmup + + long start = System.currentTimeMillis(); + doReps(sbuf, dummy, reps); return System.currentTimeMillis() - start; } - + /** * Run benchmark for given number of cycles. */ void doReps(StreamBuffer sbuf, Dummy dummy, int reps) throws Exception { - OutputStream out = sbuf.getOutputStream(); - InputStream in = sbuf.getInputStream(); - for (int i = 0; i < reps; i++) { - sbuf.reset(); - ObjectOutputStream oout = new ObjectOutputStream(out); - oout.writeObject(dummy); - oout.flush(); - ObjectInputStream oin = new ObjectInputStream(in); - oin.readObject(); - } + OutputStream out = sbuf.getOutputStream(); + InputStream in = sbuf.getInputStream(); + for (int i = 0; i < reps; i++) { + sbuf.reset(); + ObjectOutputStream oout = new ObjectOutputStream(out); + oout.writeObject(dummy); + oout.flush(); + ObjectInputStream oin = new ObjectInputStream(in); + oin.readObject(); + } } } - diff --git a/jdk/test/java/rmi/reliability/benchmark/bench/serial/CustomDefaultObjTrees.java b/jdk/test/java/rmi/reliability/benchmark/bench/serial/CustomDefaultObjTrees.java index 01d60c54a15..14ddbee4f82 100644 --- a/jdk/test/java/rmi/reliability/benchmark/bench/serial/CustomDefaultObjTrees.java +++ b/jdk/test/java/rmi/reliability/benchmark/bench/serial/CustomDefaultObjTrees.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -39,19 +39,19 @@ import java.io.Serializable; * defaultWriteObject() and defaultReadObject(). */ public class CustomDefaultObjTrees implements Benchmark { - + static class Node implements Serializable { boolean z; - byte b; - char c; - short s; - int i; - float f; - long j; - double d; - String str = "bodega"; + byte b; + char c; + short s; + int i; + float f; + long j; + double d; + String str = "bodega"; Object parent, left, right; - + Node(Object parent, int depth) { this.parent = parent; if (depth > 0) { @@ -61,13 +61,13 @@ public class CustomDefaultObjTrees implements Benchmark { } private void writeObject(ObjectOutputStream out) throws IOException { - out.defaultWriteObject(); + out.defaultWriteObject(); } - - private void readObject(ObjectInputStream in) + + private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { - in.defaultReadObject(); + in.defaultReadObject(); } } @@ -79,20 +79,20 @@ public class CustomDefaultObjTrees implements Benchmark { * Arguments: <# batches> <# cycles per batch> */ public long run(String[] args) throws Exception { - int depth = Integer.parseInt(args[0]); - int nbatches = Integer.parseInt(args[1]); - int ncycles = Integer.parseInt(args[2]); - Node[] trees = genTrees(depth, ncycles); - StreamBuffer sbuf = new StreamBuffer(); - ObjectOutputStream oout = - new ObjectOutputStream(sbuf.getOutputStream()); - ObjectInputStream oin = - new ObjectInputStream(sbuf.getInputStream()); - - doReps(oout, oin, sbuf, trees, 1); // warmup + int depth = Integer.parseInt(args[0]); + int nbatches = Integer.parseInt(args[1]); + int ncycles = Integer.parseInt(args[2]); + Node[] trees = genTrees(depth, ncycles); + StreamBuffer sbuf = new StreamBuffer(); + ObjectOutputStream oout = + new ObjectOutputStream(sbuf.getOutputStream()); + ObjectInputStream oin = + new ObjectInputStream(sbuf.getInputStream()); - long start = System.currentTimeMillis(); - doReps(oout, oin, sbuf, trees, nbatches); + doReps(oout, oin, sbuf, trees, 1); // warmup + + long start = System.currentTimeMillis(); + doReps(oout, oin, sbuf, trees, nbatches); return System.currentTimeMillis() - start; } @@ -100,33 +100,32 @@ public class CustomDefaultObjTrees implements Benchmark { * Generate object trees. */ Node[] genTrees(int depth, int ntrees) { - Node[] trees = new Node[ntrees]; - for (int i = 0; i < ntrees; i++) { - trees[i] = new Node(null, depth); - } - return trees; + Node[] trees = new Node[ntrees]; + for (int i = 0; i < ntrees; i++) { + trees[i] = new Node(null, depth); + } + return trees; } /** - * Run benchmark for given number of batches, with each batch containing + * Run benchmark for given number of batches, with each batch containing * the given number of cycles. */ void doReps(ObjectOutputStream oout, ObjectInputStream oin, - StreamBuffer sbuf, Node[] trees, int nbatches) - throws Exception + StreamBuffer sbuf, Node[] trees, int nbatches) + throws Exception { - int ncycles = trees.length; - for (int i = 0; i < nbatches; i++) { - sbuf.reset(); - oout.reset(); - for (int j = 0; j < ncycles; j++) { - oout.writeObject(trees[j]); - } - oout.flush(); - for (int j = 0; j < ncycles; j++) { - oin.readObject(); - } - } + int ncycles = trees.length; + for (int i = 0; i < nbatches; i++) { + sbuf.reset(); + oout.reset(); + for (int j = 0; j < ncycles; j++) { + oout.writeObject(trees[j]); + } + oout.flush(); + for (int j = 0; j < ncycles; j++) { + oin.readObject(); + } + } } } - diff --git a/jdk/test/java/rmi/reliability/benchmark/bench/serial/CustomObjTrees.java b/jdk/test/java/rmi/reliability/benchmark/bench/serial/CustomObjTrees.java index b87cc3673f3..d5f10a8738c 100644 --- a/jdk/test/java/rmi/reliability/benchmark/bench/serial/CustomObjTrees.java +++ b/jdk/test/java/rmi/reliability/benchmark/bench/serial/CustomObjTrees.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -38,19 +38,19 @@ import java.io.Serializable; * nodes contain custom writeObject() and readObject() methods. */ public class CustomObjTrees implements Benchmark { - + static class Node implements Serializable { boolean z; - byte b; - char c; - short s; - int i; - float f; - long j; - double d; - String str = "bodega"; + byte b; + char c; + short s; + int i; + float f; + long j; + double d; + String str = "bodega"; Object parent, left, right; - + Node(Object parent, int depth) { this.parent = parent; if (depth > 0) { @@ -60,35 +60,35 @@ public class CustomObjTrees implements Benchmark { } private void writeObject(ObjectOutputStream out) throws IOException { - out.writeBoolean(z); - out.writeByte(b); - out.writeChar(c); - out.writeShort(s); - out.writeInt(i); - out.writeFloat(f); - out.writeLong(j); - out.writeDouble(d); - out.writeObject(str); - out.writeObject(parent); - out.writeObject(left); - out.writeObject(right); + out.writeBoolean(z); + out.writeByte(b); + out.writeChar(c); + out.writeShort(s); + out.writeInt(i); + out.writeFloat(f); + out.writeLong(j); + out.writeDouble(d); + out.writeObject(str); + out.writeObject(parent); + out.writeObject(left); + out.writeObject(right); } - - private void readObject(ObjectInputStream in) + + private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { - z = in.readBoolean(); - b = in.readByte(); - c = in.readChar(); - s = in.readShort(); - i = in.readInt(); - f = in.readFloat(); - j = in.readLong(); - d = in.readDouble(); - str = (String) in.readObject(); - parent = in.readObject(); - left = in.readObject(); - right = in.readObject(); + z = in.readBoolean(); + b = in.readByte(); + c = in.readChar(); + s = in.readShort(); + i = in.readInt(); + f = in.readFloat(); + j = in.readLong(); + d = in.readDouble(); + str = (String) in.readObject(); + parent = in.readObject(); + left = in.readObject(); + right = in.readObject(); } } @@ -100,20 +100,20 @@ public class CustomObjTrees implements Benchmark { * Arguments: <# batches> <# cycles per batch> */ public long run(String[] args) throws Exception { - int depth = Integer.parseInt(args[0]); - int nbatches = Integer.parseInt(args[1]); - int ncycles = Integer.parseInt(args[2]); - Node[] trees = genTrees(depth, ncycles); - StreamBuffer sbuf = new StreamBuffer(); - ObjectOutputStream oout = - new ObjectOutputStream(sbuf.getOutputStream()); - ObjectInputStream oin = - new ObjectInputStream(sbuf.getInputStream()); - - doReps(oout, oin, sbuf, trees, 1); // warmup + int depth = Integer.parseInt(args[0]); + int nbatches = Integer.parseInt(args[1]); + int ncycles = Integer.parseInt(args[2]); + Node[] trees = genTrees(depth, ncycles); + StreamBuffer sbuf = new StreamBuffer(); + ObjectOutputStream oout = + new ObjectOutputStream(sbuf.getOutputStream()); + ObjectInputStream oin = + new ObjectInputStream(sbuf.getInputStream()); - long start = System.currentTimeMillis(); - doReps(oout, oin, sbuf, trees, nbatches); + doReps(oout, oin, sbuf, trees, 1); // warmup + + long start = System.currentTimeMillis(); + doReps(oout, oin, sbuf, trees, nbatches); return System.currentTimeMillis() - start; } @@ -121,33 +121,32 @@ public class CustomObjTrees implements Benchmark { * Generate object trees. */ Node[] genTrees(int depth, int ntrees) { - Node[] trees = new Node[ntrees]; - for (int i = 0; i < ntrees; i++) { - trees[i] = new Node(null, depth); - } - return trees; + Node[] trees = new Node[ntrees]; + for (int i = 0; i < ntrees; i++) { + trees[i] = new Node(null, depth); + } + return trees; } /** - * Run benchmark for given number of batches, with each batch containing + * Run benchmark for given number of batches, with each batch containing * the given number of cycles. */ void doReps(ObjectOutputStream oout, ObjectInputStream oin, - StreamBuffer sbuf, Node[] trees, int nbatches) - throws Exception + StreamBuffer sbuf, Node[] trees, int nbatches) + throws Exception { - int ncycles = trees.length; - for (int i = 0; i < nbatches; i++) { - sbuf.reset(); - oout.reset(); - for (int j = 0; j < ncycles; j++) { - oout.writeObject(trees[j]); - } - oout.flush(); - for (int j = 0; j < ncycles; j++) { - oin.readObject(); - } - } + int ncycles = trees.length; + for (int i = 0; i < nbatches; i++) { + sbuf.reset(); + oout.reset(); + for (int j = 0; j < ncycles; j++) { + oout.writeObject(trees[j]); + } + oout.flush(); + for (int j = 0; j < ncycles; j++) { + oin.readObject(); + } + } } } - diff --git a/jdk/test/java/rmi/reliability/benchmark/bench/serial/DoubleArrays.java b/jdk/test/java/rmi/reliability/benchmark/bench/serial/DoubleArrays.java index 205bc173b8e..f216ebab694 100644 --- a/jdk/test/java/rmi/reliability/benchmark/bench/serial/DoubleArrays.java +++ b/jdk/test/java/rmi/reliability/benchmark/bench/serial/DoubleArrays.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -35,7 +35,7 @@ import java.io.ObjectOutputStream; * Benchmark for testing speed of double array reads/writes. */ public class DoubleArrays implements Benchmark { - + /** * Write and read double arrays to/from a stream. The benchmark is run in * batches, with each batch consisting of a fixed number of read/write @@ -44,44 +44,42 @@ public class DoubleArrays implements Benchmark { * Arguments: <# batches> <# cycles per batch> */ public long run(String[] args) throws Exception { - int size = Integer.parseInt(args[0]); - int nbatches = Integer.parseInt(args[1]); - int ncycles = Integer.parseInt(args[2]); - double[][] arrays = new double[ncycles][size]; - StreamBuffer sbuf = new StreamBuffer(); - ObjectOutputStream oout = - new ObjectOutputStream(sbuf.getOutputStream()); - ObjectInputStream oin = - new ObjectInputStream(sbuf.getInputStream()); + int size = Integer.parseInt(args[0]); + int nbatches = Integer.parseInt(args[1]); + int ncycles = Integer.parseInt(args[2]); + double[][] arrays = new double[ncycles][size]; + StreamBuffer sbuf = new StreamBuffer(); + ObjectOutputStream oout = + new ObjectOutputStream(sbuf.getOutputStream()); + ObjectInputStream oin = + new ObjectInputStream(sbuf.getInputStream()); - doReps(oout, oin, sbuf, arrays, 1); // warmup + doReps(oout, oin, sbuf, arrays, 1); // warmup - long start = System.currentTimeMillis(); - doReps(oout, oin, sbuf, arrays, nbatches); + long start = System.currentTimeMillis(); + doReps(oout, oin, sbuf, arrays, nbatches); return System.currentTimeMillis() - start; } - + /** * Run benchmark for given number of batches, with given number of cycles * for each batch. */ void doReps(ObjectOutputStream oout, ObjectInputStream oin, - StreamBuffer sbuf, double[][] arrays, int nbatches) - throws Exception + StreamBuffer sbuf, double[][] arrays, int nbatches) + throws Exception { - int ncycles = arrays.length; - for (int i = 0; i < nbatches; i++) { - sbuf.reset(); - oout.reset(); - for (int j = 0; j < ncycles; j++) { - oout.writeObject(arrays[j]); - } - oout.flush(); - for (int j = 0; j < ncycles; j++) { - oin.readObject(); - } - } + int ncycles = arrays.length; + for (int i = 0; i < nbatches; i++) { + sbuf.reset(); + oout.reset(); + for (int j = 0; j < ncycles; j++) { + oout.writeObject(arrays[j]); + } + oout.flush(); + for (int j = 0; j < ncycles; j++) { + oin.readObject(); + } + } } } - - diff --git a/jdk/test/java/rmi/reliability/benchmark/bench/serial/Doubles.java b/jdk/test/java/rmi/reliability/benchmark/bench/serial/Doubles.java index 231fd0ee86c..e43df322c27 100644 --- a/jdk/test/java/rmi/reliability/benchmark/bench/serial/Doubles.java +++ b/jdk/test/java/rmi/reliability/benchmark/bench/serial/Doubles.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -35,7 +35,7 @@ import java.io.ObjectOutputStream; * Benchmark for testing speed of double reads/writes. */ public class Doubles implements Benchmark { - + /** * Write and read double values to/from a stream. The benchmark is run in * batches: each "batch" consists of a fixed number of read/write cycles, @@ -44,39 +44,38 @@ public class Doubles implements Benchmark { * Arguments: <# batches> <# cycles per batch> */ public long run(String[] args) throws Exception { - int nbatches = Integer.parseInt(args[0]); - int ncycles = Integer.parseInt(args[1]); - StreamBuffer sbuf = new StreamBuffer(); - ObjectOutputStream oout = - new ObjectOutputStream(sbuf.getOutputStream()); - ObjectInputStream oin = - new ObjectInputStream(sbuf.getInputStream()); - - doReps(oout, oin, sbuf, 1, ncycles); // warmup + int nbatches = Integer.parseInt(args[0]); + int ncycles = Integer.parseInt(args[1]); + StreamBuffer sbuf = new StreamBuffer(); + ObjectOutputStream oout = + new ObjectOutputStream(sbuf.getOutputStream()); + ObjectInputStream oin = + new ObjectInputStream(sbuf.getInputStream()); - long start = System.currentTimeMillis(); - doReps(oout, oin, sbuf, nbatches, ncycles); + doReps(oout, oin, sbuf, 1, ncycles); // warmup + + long start = System.currentTimeMillis(); + doReps(oout, oin, sbuf, nbatches, ncycles); return System.currentTimeMillis() - start; } - + /** * Run benchmark for given number of batches, with given number of cycles * for each batch. */ void doReps(ObjectOutputStream oout, ObjectInputStream oin, - StreamBuffer sbuf, int nbatches, int ncycles) - throws Exception + StreamBuffer sbuf, int nbatches, int ncycles) + throws Exception { - for (int i = 0; i < nbatches; i++) { - sbuf.reset(); - for (int j = 0; j < ncycles; j++) { - oout.writeDouble(0.0); - } - oout.flush(); - for (int j = 0; j < ncycles; j++) { - oin.readDouble(); - } - } + for (int i = 0; i < nbatches; i++) { + sbuf.reset(); + for (int j = 0; j < ncycles; j++) { + oout.writeDouble(0.0); + } + oout.flush(); + for (int j = 0; j < ncycles; j++) { + oin.readDouble(); + } + } } } - diff --git a/jdk/test/java/rmi/reliability/benchmark/bench/serial/ExternObjTrees.java b/jdk/test/java/rmi/reliability/benchmark/bench/serial/ExternObjTrees.java index 15a490080d2..bb9053a787d 100644 --- a/jdk/test/java/rmi/reliability/benchmark/bench/serial/ExternObjTrees.java +++ b/jdk/test/java/rmi/reliability/benchmark/bench/serial/ExternObjTrees.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -40,19 +40,19 @@ import java.io.ObjectOutputStream; * objects. */ public class ExternObjTrees implements Benchmark { - + static class Node implements Externalizable { boolean z; - byte b; - char c; - short s; - int i; - float f; - long j; - double d; - String str = "bodega"; + byte b; + char c; + short s; + int i; + float f; + long j; + double d; + String str = "bodega"; Object parent, left, right; - + Node(Object parent, int depth) { this.parent = parent; if (depth > 0) { @@ -61,40 +61,40 @@ public class ExternObjTrees implements Benchmark { } } - public Node() { - } - - public void writeExternal(ObjectOutput out) throws IOException { - out.writeBoolean(z); - out.writeByte(b); - out.writeChar(c); - out.writeShort(s); - out.writeInt(i); - out.writeFloat(f); - out.writeLong(j); - out.writeDouble(d); - out.writeObject(str); - out.writeObject(parent); - out.writeObject(left); - out.writeObject(right); - } - - public void readExternal(ObjectInput in) - throws IOException, ClassNotFoundException - { - z = in.readBoolean(); - b = in.readByte(); - c = in.readChar(); - s = in.readShort(); - i = in.readInt(); - f = in.readFloat(); - j = in.readLong(); - d = in.readDouble(); - str = (String) in.readObject(); - parent = in.readObject(); - left = in.readObject(); - right = in.readObject(); - } + public Node() { + } + + public void writeExternal(ObjectOutput out) throws IOException { + out.writeBoolean(z); + out.writeByte(b); + out.writeChar(c); + out.writeShort(s); + out.writeInt(i); + out.writeFloat(f); + out.writeLong(j); + out.writeDouble(d); + out.writeObject(str); + out.writeObject(parent); + out.writeObject(left); + out.writeObject(right); + } + + public void readExternal(ObjectInput in) + throws IOException, ClassNotFoundException + { + z = in.readBoolean(); + b = in.readByte(); + c = in.readChar(); + s = in.readShort(); + i = in.readInt(); + f = in.readFloat(); + j = in.readLong(); + d = in.readDouble(); + str = (String) in.readObject(); + parent = in.readObject(); + left = in.readObject(); + right = in.readObject(); + } } /** @@ -105,20 +105,20 @@ public class ExternObjTrees implements Benchmark { * Arguments: <# batches> <# cycles per batch> */ public long run(String[] args) throws Exception { - int depth = Integer.parseInt(args[0]); - int nbatches = Integer.parseInt(args[1]); - int ncycles = Integer.parseInt(args[2]); - Node[] trees = genTrees(depth, ncycles); - StreamBuffer sbuf = new StreamBuffer(); - ObjectOutputStream oout = - new ObjectOutputStream(sbuf.getOutputStream()); - ObjectInputStream oin = - new ObjectInputStream(sbuf.getInputStream()); - - doReps(oout, oin, sbuf, trees, 1); // warmup + int depth = Integer.parseInt(args[0]); + int nbatches = Integer.parseInt(args[1]); + int ncycles = Integer.parseInt(args[2]); + Node[] trees = genTrees(depth, ncycles); + StreamBuffer sbuf = new StreamBuffer(); + ObjectOutputStream oout = + new ObjectOutputStream(sbuf.getOutputStream()); + ObjectInputStream oin = + new ObjectInputStream(sbuf.getInputStream()); - long start = System.currentTimeMillis(); - doReps(oout, oin, sbuf, trees, nbatches); + doReps(oout, oin, sbuf, trees, 1); // warmup + + long start = System.currentTimeMillis(); + doReps(oout, oin, sbuf, trees, nbatches); return System.currentTimeMillis() - start; } @@ -126,33 +126,32 @@ public class ExternObjTrees implements Benchmark { * Generate object trees. */ Node[] genTrees(int depth, int ntrees) { - Node[] trees = new Node[ntrees]; - for (int i = 0; i < ntrees; i++) { - trees[i] = new Node(null, depth); - } - return trees; + Node[] trees = new Node[ntrees]; + for (int i = 0; i < ntrees; i++) { + trees[i] = new Node(null, depth); + } + return trees; } /** - * Run benchmark for given number of batches, with each batch containing + * Run benchmark for given number of batches, with each batch containing * the given number of cycles. */ void doReps(ObjectOutputStream oout, ObjectInputStream oin, - StreamBuffer sbuf, Node[] trees, int nbatches) - throws Exception + StreamBuffer sbuf, Node[] trees, int nbatches) + throws Exception { - int ncycles = trees.length; - for (int i = 0; i < nbatches; i++) { - sbuf.reset(); - oout.reset(); - for (int j = 0; j < ncycles; j++) { - oout.writeObject(trees[j]); - } - oout.flush(); - for (int j = 0; j < ncycles; j++) { - oin.readObject(); - } - } + int ncycles = trees.length; + for (int i = 0; i < nbatches; i++) { + sbuf.reset(); + oout.reset(); + for (int j = 0; j < ncycles; j++) { + oout.writeObject(trees[j]); + } + oout.flush(); + for (int j = 0; j < ncycles; j++) { + oin.readObject(); + } + } } } - diff --git a/jdk/test/java/rmi/reliability/benchmark/bench/serial/FloatArrays.java b/jdk/test/java/rmi/reliability/benchmark/bench/serial/FloatArrays.java index 686fd1974f0..8feae044d55 100644 --- a/jdk/test/java/rmi/reliability/benchmark/bench/serial/FloatArrays.java +++ b/jdk/test/java/rmi/reliability/benchmark/bench/serial/FloatArrays.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -35,7 +35,7 @@ import java.io.ObjectOutputStream; * Benchmark for testing speed of float array reads/writes. */ public class FloatArrays implements Benchmark { - + /** * Write and read float arrays to/from a stream. The benchmark is run in * batches, with each batch consisting of a fixed number of read/write @@ -44,44 +44,42 @@ public class FloatArrays implements Benchmark { * Arguments: <# batches> <# cycles per batch> */ public long run(String[] args) throws Exception { - int size = Integer.parseInt(args[0]); - int nbatches = Integer.parseInt(args[1]); - int ncycles = Integer.parseInt(args[2]); - float[][] arrays = new float[ncycles][size]; - StreamBuffer sbuf = new StreamBuffer(); - ObjectOutputStream oout = - new ObjectOutputStream(sbuf.getOutputStream()); - ObjectInputStream oin = - new ObjectInputStream(sbuf.getInputStream()); + int size = Integer.parseInt(args[0]); + int nbatches = Integer.parseInt(args[1]); + int ncycles = Integer.parseInt(args[2]); + float[][] arrays = new float[ncycles][size]; + StreamBuffer sbuf = new StreamBuffer(); + ObjectOutputStream oout = + new ObjectOutputStream(sbuf.getOutputStream()); + ObjectInputStream oin = + new ObjectInputStream(sbuf.getInputStream()); - doReps(oout, oin, sbuf, arrays, 1); // warmup + doReps(oout, oin, sbuf, arrays, 1); // warmup - long start = System.currentTimeMillis(); - doReps(oout, oin, sbuf, arrays, nbatches); + long start = System.currentTimeMillis(); + doReps(oout, oin, sbuf, arrays, nbatches); return System.currentTimeMillis() - start; } - + /** * Run benchmark for given number of batches, with given number of cycles * for each batch. */ void doReps(ObjectOutputStream oout, ObjectInputStream oin, - StreamBuffer sbuf, float[][] arrays, int nbatches) - throws Exception + StreamBuffer sbuf, float[][] arrays, int nbatches) + throws Exception { - int ncycles = arrays.length; - for (int i = 0; i < nbatches; i++) { - sbuf.reset(); - oout.reset(); - for (int j = 0; j < ncycles; j++) { - oout.writeObject(arrays[j]); - } - oout.flush(); - for (int j = 0; j < ncycles; j++) { - oin.readObject(); - } - } + int ncycles = arrays.length; + for (int i = 0; i < nbatches; i++) { + sbuf.reset(); + oout.reset(); + for (int j = 0; j < ncycles; j++) { + oout.writeObject(arrays[j]); + } + oout.flush(); + for (int j = 0; j < ncycles; j++) { + oin.readObject(); + } + } } } - - diff --git a/jdk/test/java/rmi/reliability/benchmark/bench/serial/Floats.java b/jdk/test/java/rmi/reliability/benchmark/bench/serial/Floats.java index d84bf5f969f..1dca696a6a4 100644 --- a/jdk/test/java/rmi/reliability/benchmark/bench/serial/Floats.java +++ b/jdk/test/java/rmi/reliability/benchmark/bench/serial/Floats.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -35,7 +35,7 @@ import java.io.ObjectOutputStream; * Benchmark for testing speed of float reads/writes. */ public class Floats implements Benchmark { - + /** * Write and read float values to/from a stream. The benchmark is run in * batches: each "batch" consists of a fixed number of read/write cycles, @@ -44,39 +44,38 @@ public class Floats implements Benchmark { * Arguments: <# batches> <# cycles per batch> */ public long run(String[] args) throws Exception { - int nbatches = Integer.parseInt(args[0]); - int ncycles = Integer.parseInt(args[1]); - StreamBuffer sbuf = new StreamBuffer(); - ObjectOutputStream oout = - new ObjectOutputStream(sbuf.getOutputStream()); - ObjectInputStream oin = - new ObjectInputStream(sbuf.getInputStream()); - - doReps(oout, oin, sbuf, 1, ncycles); // warmup + int nbatches = Integer.parseInt(args[0]); + int ncycles = Integer.parseInt(args[1]); + StreamBuffer sbuf = new StreamBuffer(); + ObjectOutputStream oout = + new ObjectOutputStream(sbuf.getOutputStream()); + ObjectInputStream oin = + new ObjectInputStream(sbuf.getInputStream()); - long start = System.currentTimeMillis(); - doReps(oout, oin, sbuf, nbatches, ncycles); + doReps(oout, oin, sbuf, 1, ncycles); // warmup + + long start = System.currentTimeMillis(); + doReps(oout, oin, sbuf, nbatches, ncycles); return System.currentTimeMillis() - start; } - + /** * Run benchmark for given number of batches, with given number of cycles * for each batch. */ void doReps(ObjectOutputStream oout, ObjectInputStream oin, - StreamBuffer sbuf, int nbatches, int ncycles) - throws Exception + StreamBuffer sbuf, int nbatches, int ncycles) + throws Exception { - for (int i = 0; i < nbatches; i++) { - sbuf.reset(); - for (int j = 0; j < ncycles; j++) { - oout.writeFloat((float) 0.0); - } - oout.flush(); - for (int j = 0; j < ncycles; j++) { - oin.readFloat(); - } - } + for (int i = 0; i < nbatches; i++) { + sbuf.reset(); + for (int j = 0; j < ncycles; j++) { + oout.writeFloat((float) 0.0); + } + oout.flush(); + for (int j = 0; j < ncycles; j++) { + oin.readFloat(); + } + } } } - diff --git a/jdk/test/java/rmi/reliability/benchmark/bench/serial/GetPutFieldTrees.java b/jdk/test/java/rmi/reliability/benchmark/bench/serial/GetPutFieldTrees.java index 95a475c2d72..c5794f05bad 100644 --- a/jdk/test/java/rmi/reliability/benchmark/bench/serial/GetPutFieldTrees.java +++ b/jdk/test/java/rmi/reliability/benchmark/bench/serial/GetPutFieldTrees.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -39,19 +39,19 @@ import java.io.Serializable; * GetField()/PutField() API. */ public class GetPutFieldTrees implements Benchmark { - + static class Node implements Serializable { boolean z; - byte b; - char c; - short s; - int i; - float f; - long j; - double d; - String str = "bodega"; + byte b; + char c; + short s; + int i; + float f; + long j; + double d; + String str = "bodega"; Object parent, left, right; - + Node(Object parent, int depth) { this.parent = parent; if (depth > 0) { @@ -76,19 +76,19 @@ public class GetPutFieldTrees implements Benchmark { fields.put("right", right); out.writeFields(); } - - private void readObject(ObjectInputStream in) + + private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { ObjectInputStream.GetField fields = in.readFields(); - z = fields.get("z", false); - b = fields.get("b", (byte) 0); - c = fields.get("c", (char) 0); - s = fields.get("s", (short) 0); - i = fields.get("i", (int) 0); - f = fields.get("f", (float) 0.0); - j = fields.get("j", (long) 0); - d = fields.get("d", (double) 0.0); + z = fields.get("z", false); + b = fields.get("b", (byte) 0); + c = fields.get("c", (char) 0); + s = fields.get("s", (short) 0); + i = fields.get("i", (int) 0); + f = fields.get("f", (float) 0.0); + j = fields.get("j", (long) 0); + d = fields.get("d", (double) 0.0); str = (String) fields.get("str", null); parent = fields.get("parent", null); left = fields.get("left", null); @@ -104,20 +104,20 @@ public class GetPutFieldTrees implements Benchmark { * Arguments: <# batches> <# cycles per batch> */ public long run(String[] args) throws Exception { - int depth = Integer.parseInt(args[0]); - int nbatches = Integer.parseInt(args[1]); - int ncycles = Integer.parseInt(args[2]); - Node[] trees = genTrees(depth, ncycles); - StreamBuffer sbuf = new StreamBuffer(); - ObjectOutputStream oout = - new ObjectOutputStream(sbuf.getOutputStream()); - ObjectInputStream oin = - new ObjectInputStream(sbuf.getInputStream()); - - doReps(oout, oin, sbuf, trees, 1); // warmup + int depth = Integer.parseInt(args[0]); + int nbatches = Integer.parseInt(args[1]); + int ncycles = Integer.parseInt(args[2]); + Node[] trees = genTrees(depth, ncycles); + StreamBuffer sbuf = new StreamBuffer(); + ObjectOutputStream oout = + new ObjectOutputStream(sbuf.getOutputStream()); + ObjectInputStream oin = + new ObjectInputStream(sbuf.getInputStream()); - long start = System.currentTimeMillis(); - doReps(oout, oin, sbuf, trees, nbatches); + doReps(oout, oin, sbuf, trees, 1); // warmup + + long start = System.currentTimeMillis(); + doReps(oout, oin, sbuf, trees, nbatches); return System.currentTimeMillis() - start; } @@ -125,33 +125,32 @@ public class GetPutFieldTrees implements Benchmark { * Generate object trees. */ Node[] genTrees(int depth, int ntrees) { - Node[] trees = new Node[ntrees]; - for (int i = 0; i < ntrees; i++) { - trees[i] = new Node(null, depth); - } - return trees; + Node[] trees = new Node[ntrees]; + for (int i = 0; i < ntrees; i++) { + trees[i] = new Node(null, depth); + } + return trees; } /** - * Run benchmark for given number of batches, with each batch containing + * Run benchmark for given number of batches, with each batch containing * the given number of cycles. */ void doReps(ObjectOutputStream oout, ObjectInputStream oin, - StreamBuffer sbuf, Node[] trees, int nbatches) - throws Exception + StreamBuffer sbuf, Node[] trees, int nbatches) + throws Exception { - int ncycles = trees.length; - for (int i = 0; i < nbatches; i++) { - sbuf.reset(); - oout.reset(); - for (int j = 0; j < ncycles; j++) { - oout.writeObject(trees[j]); - } - oout.flush(); - for (int j = 0; j < ncycles; j++) { - oin.readObject(); - } - } + int ncycles = trees.length; + for (int i = 0; i < nbatches; i++) { + sbuf.reset(); + oout.reset(); + for (int j = 0; j < ncycles; j++) { + oout.writeObject(trees[j]); + } + oout.flush(); + for (int j = 0; j < ncycles; j++) { + oin.readObject(); + } + } } } - diff --git a/jdk/test/java/rmi/reliability/benchmark/bench/serial/IntArrays.java b/jdk/test/java/rmi/reliability/benchmark/bench/serial/IntArrays.java index 2bc445373c0..c50059bb6c3 100644 --- a/jdk/test/java/rmi/reliability/benchmark/bench/serial/IntArrays.java +++ b/jdk/test/java/rmi/reliability/benchmark/bench/serial/IntArrays.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -35,7 +35,7 @@ import java.io.ObjectOutputStream; * Benchmark for testing speed of int array reads/writes. */ public class IntArrays implements Benchmark { - + /** * Write and read int arrays to/from a stream. The benchmark is run in * batches, with each batch consisting of a fixed number of read/write @@ -44,44 +44,42 @@ public class IntArrays implements Benchmark { * Arguments: <# batches> <# cycles per batch> */ public long run(String[] args) throws Exception { - int size = Integer.parseInt(args[0]); - int nbatches = Integer.parseInt(args[1]); - int ncycles = Integer.parseInt(args[2]); - int[][] arrays = new int[ncycles][size]; - StreamBuffer sbuf = new StreamBuffer(); - ObjectOutputStream oout = - new ObjectOutputStream(sbuf.getOutputStream()); - ObjectInputStream oin = - new ObjectInputStream(sbuf.getInputStream()); + int size = Integer.parseInt(args[0]); + int nbatches = Integer.parseInt(args[1]); + int ncycles = Integer.parseInt(args[2]); + int[][] arrays = new int[ncycles][size]; + StreamBuffer sbuf = new StreamBuffer(); + ObjectOutputStream oout = + new ObjectOutputStream(sbuf.getOutputStream()); + ObjectInputStream oin = + new ObjectInputStream(sbuf.getInputStream()); - doReps(oout, oin, sbuf, arrays, 1); // warmup + doReps(oout, oin, sbuf, arrays, 1); // warmup - long start = System.currentTimeMillis(); - doReps(oout, oin, sbuf, arrays, nbatches); + long start = System.currentTimeMillis(); + doReps(oout, oin, sbuf, arrays, nbatches); return System.currentTimeMillis() - start; } - + /** * Run benchmark for given number of batches, with given number of cycles * for each batch. */ void doReps(ObjectOutputStream oout, ObjectInputStream oin, - StreamBuffer sbuf, int[][] arrays, int nbatches) - throws Exception + StreamBuffer sbuf, int[][] arrays, int nbatches) + throws Exception { - int ncycles = arrays.length; - for (int i = 0; i < nbatches; i++) { - sbuf.reset(); - oout.reset(); - for (int j = 0; j < ncycles; j++) { - oout.writeObject(arrays[j]); - } - oout.flush(); - for (int j = 0; j < ncycles; j++) { - oin.readObject(); - } - } + int ncycles = arrays.length; + for (int i = 0; i < nbatches; i++) { + sbuf.reset(); + oout.reset(); + for (int j = 0; j < ncycles; j++) { + oout.writeObject(arrays[j]); + } + oout.flush(); + for (int j = 0; j < ncycles; j++) { + oin.readObject(); + } + } } } - - diff --git a/jdk/test/java/rmi/reliability/benchmark/bench/serial/Ints.java b/jdk/test/java/rmi/reliability/benchmark/bench/serial/Ints.java index 152b048e9b5..90cfb30216f 100644 --- a/jdk/test/java/rmi/reliability/benchmark/bench/serial/Ints.java +++ b/jdk/test/java/rmi/reliability/benchmark/bench/serial/Ints.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -35,7 +35,7 @@ import java.io.ObjectOutputStream; * Benchmark for testing speed of int reads/writes. */ public class Ints implements Benchmark { - + /** * Write and read int values to/from a stream. The benchmark is run in * batches: each "batch" consists of a fixed number of read/write cycles, @@ -44,39 +44,38 @@ public class Ints implements Benchmark { * Arguments: <# batches> <# cycles per batch> */ public long run(String[] args) throws Exception { - int nbatches = Integer.parseInt(args[0]); - int ncycles = Integer.parseInt(args[1]); - StreamBuffer sbuf = new StreamBuffer(); - ObjectOutputStream oout = - new ObjectOutputStream(sbuf.getOutputStream()); - ObjectInputStream oin = - new ObjectInputStream(sbuf.getInputStream()); - - doReps(oout, oin, sbuf, 1, ncycles); // warmup + int nbatches = Integer.parseInt(args[0]); + int ncycles = Integer.parseInt(args[1]); + StreamBuffer sbuf = new StreamBuffer(); + ObjectOutputStream oout = + new ObjectOutputStream(sbuf.getOutputStream()); + ObjectInputStream oin = + new ObjectInputStream(sbuf.getInputStream()); - long start = System.currentTimeMillis(); - doReps(oout, oin, sbuf, nbatches, ncycles); + doReps(oout, oin, sbuf, 1, ncycles); // warmup + + long start = System.currentTimeMillis(); + doReps(oout, oin, sbuf, nbatches, ncycles); return System.currentTimeMillis() - start; } - + /** * Run benchmark for given number of batches, with given number of cycles * for each batch. */ void doReps(ObjectOutputStream oout, ObjectInputStream oin, - StreamBuffer sbuf, int nbatches, int ncycles) - throws Exception + StreamBuffer sbuf, int nbatches, int ncycles) + throws Exception { - for (int i = 0; i < nbatches; i++) { - sbuf.reset(); - for (int j = 0; j < ncycles; j++) { - oout.writeInt(0); - } - oout.flush(); - for (int j = 0; j < ncycles; j++) { - oin.readInt(); - } - } + for (int i = 0; i < nbatches; i++) { + sbuf.reset(); + for (int j = 0; j < ncycles; j++) { + oout.writeInt(0); + } + oout.flush(); + for (int j = 0; j < ncycles; j++) { + oin.readInt(); + } + } } } - diff --git a/jdk/test/java/rmi/reliability/benchmark/bench/serial/LongArrays.java b/jdk/test/java/rmi/reliability/benchmark/bench/serial/LongArrays.java index 21b48e98cb6..802bb82cf9a 100644 --- a/jdk/test/java/rmi/reliability/benchmark/bench/serial/LongArrays.java +++ b/jdk/test/java/rmi/reliability/benchmark/bench/serial/LongArrays.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -35,7 +35,7 @@ import java.io.ObjectOutputStream; * Benchmark for testing speed of long array reads/writes. */ public class LongArrays implements Benchmark { - + /** * Write and read long arrays to/from a stream. The benchmark is run in * batches, with each batch consisting of a fixed number of read/write @@ -44,44 +44,42 @@ public class LongArrays implements Benchmark { * Arguments: <# batches> <# cycles per batch> */ public long run(String[] args) throws Exception { - int size = Integer.parseInt(args[0]); - int nbatches = Integer.parseInt(args[1]); - int ncycles = Integer.parseInt(args[2]); - long[][] arrays = new long[ncycles][size]; - StreamBuffer sbuf = new StreamBuffer(); - ObjectOutputStream oout = - new ObjectOutputStream(sbuf.getOutputStream()); - ObjectInputStream oin = - new ObjectInputStream(sbuf.getInputStream()); + int size = Integer.parseInt(args[0]); + int nbatches = Integer.parseInt(args[1]); + int ncycles = Integer.parseInt(args[2]); + long[][] arrays = new long[ncycles][size]; + StreamBuffer sbuf = new StreamBuffer(); + ObjectOutputStream oout = + new ObjectOutputStream(sbuf.getOutputStream()); + ObjectInputStream oin = + new ObjectInputStream(sbuf.getInputStream()); - doReps(oout, oin, sbuf, arrays, 1); // warmup + doReps(oout, oin, sbuf, arrays, 1); // warmup - long start = System.currentTimeMillis(); - doReps(oout, oin, sbuf, arrays, nbatches); + long start = System.currentTimeMillis(); + doReps(oout, oin, sbuf, arrays, nbatches); return System.currentTimeMillis() - start; } - + /** * Run benchmark for given number of batches, with given number of cycles * for each batch. */ void doReps(ObjectOutputStream oout, ObjectInputStream oin, - StreamBuffer sbuf, long[][] arrays, int nbatches) - throws Exception + StreamBuffer sbuf, long[][] arrays, int nbatches) + throws Exception { - int ncycles = arrays.length; - for (int i = 0; i < nbatches; i++) { - sbuf.reset(); - oout.reset(); - for (int j = 0; j < ncycles; j++) { - oout.writeObject(arrays[j]); - } - oout.flush(); - for (int j = 0; j < ncycles; j++) { - oin.readObject(); - } - } + int ncycles = arrays.length; + for (int i = 0; i < nbatches; i++) { + sbuf.reset(); + oout.reset(); + for (int j = 0; j < ncycles; j++) { + oout.writeObject(arrays[j]); + } + oout.flush(); + for (int j = 0; j < ncycles; j++) { + oin.readObject(); + } + } } } - - diff --git a/jdk/test/java/rmi/reliability/benchmark/bench/serial/Longs.java b/jdk/test/java/rmi/reliability/benchmark/bench/serial/Longs.java index 7ebac7f9ffb..fdc1e04e647 100644 --- a/jdk/test/java/rmi/reliability/benchmark/bench/serial/Longs.java +++ b/jdk/test/java/rmi/reliability/benchmark/bench/serial/Longs.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -35,7 +35,7 @@ import java.io.ObjectOutputStream; * Benchmark for testing speed of long reads/writes. */ public class Longs implements Benchmark { - + /** * Write and read long values to/from a stream. The benchmark is run in * batches: each "batch" consists of a fixed number of read/write cycles, @@ -44,39 +44,38 @@ public class Longs implements Benchmark { * Arguments: <# batches> <# cycles per batch> */ public long run(String[] args) throws Exception { - int nbatches = Integer.parseInt(args[0]); - int ncycles = Integer.parseInt(args[1]); - StreamBuffer sbuf = new StreamBuffer(); - ObjectOutputStream oout = - new ObjectOutputStream(sbuf.getOutputStream()); - ObjectInputStream oin = - new ObjectInputStream(sbuf.getInputStream()); - - doReps(oout, oin, sbuf, 1, ncycles); // warmup + int nbatches = Integer.parseInt(args[0]); + int ncycles = Integer.parseInt(args[1]); + StreamBuffer sbuf = new StreamBuffer(); + ObjectOutputStream oout = + new ObjectOutputStream(sbuf.getOutputStream()); + ObjectInputStream oin = + new ObjectInputStream(sbuf.getInputStream()); - long start = System.currentTimeMillis(); - doReps(oout, oin, sbuf, nbatches, ncycles); + doReps(oout, oin, sbuf, 1, ncycles); // warmup + + long start = System.currentTimeMillis(); + doReps(oout, oin, sbuf, nbatches, ncycles); return System.currentTimeMillis() - start; } - + /** * Run benchmark for given number of batches, with given number of cycles * for each batch. */ void doReps(ObjectOutputStream oout, ObjectInputStream oin, - StreamBuffer sbuf, int nbatches, int ncycles) - throws Exception + StreamBuffer sbuf, int nbatches, int ncycles) + throws Exception { - for (int i = 0; i < nbatches; i++) { - sbuf.reset(); - for (int j = 0; j < ncycles; j++) { - oout.writeLong(0); - } - oout.flush(); - for (int j = 0; j < ncycles; j++) { - oin.readLong(); - } - } + for (int i = 0; i < nbatches; i++) { + sbuf.reset(); + for (int j = 0; j < ncycles; j++) { + oout.writeLong(0); + } + oout.flush(); + for (int j = 0; j < ncycles; j++) { + oin.readLong(); + } + } } } - diff --git a/jdk/test/java/rmi/reliability/benchmark/bench/serial/Main.java b/jdk/test/java/rmi/reliability/benchmark/bench/serial/Main.java index aeaa4b19153..49e8e813f6e 100644 --- a/jdk/test/java/rmi/reliability/benchmark/bench/serial/Main.java +++ b/jdk/test/java/rmi/reliability/benchmark/bench/serial/Main.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1999-2005 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -46,7 +46,7 @@ import java.util.TimerTask; * Object serialization benchmark mainline. */ public class Main { - + static final String CONFFILE = "/bench/serial/config"; static final String VERSION = "1.3"; @@ -80,55 +80,55 @@ public class Main { p.println(" -o specify output file"); p.println(" -c specify (non-default) configuration file"); p.println(" -html format output as html (default is text)"); - p.println(" -xml format output as xml"); + p.println(" -xml format output as xml"); } /** * Print error message and exit. */ static void die(String mesg) { - System.err.println(mesg); - System.exit(1); + System.err.println(mesg); + System.exit(1); } /** * Mainline parses command line, then hands off to benchmark harness. */ public static void main(String[] args) { - parseArgs(args); - setupStreams(); - if (list) { - listConfig(); - } else { - setupHarness(); - setupReporter(); - if (exitOnTimer) { - setupTimer(testDurationSeconds); - while (true) { - runBenchmarks(); - if (exitRequested) { - System.exit(0); - } - } - } else { - runBenchmarks(); - System.exit(0); - } - } + parseArgs(args); + setupStreams(); + if (list) { + listConfig(); + } else { + setupHarness(); + setupReporter(); + if (exitOnTimer) { + setupTimer(testDurationSeconds); + while (true) { + runBenchmarks(); + if (exitRequested) { + System.exit(0); + } + } + } else { + runBenchmarks(); + System.exit(0); + } + } } - + /** * Parse command-line arguments. */ static void parseArgs(String[] args) { - for (int i = 0; i < args.length; i++) { - if (args[i].equals("-h")) { - usage(); - System.exit(0); - } else if (args[i].equals("-v")) { - verbose = true; - } else if (args[i].equals("-l")) { - list = true; + for (int i = 0; i < args.length; i++) { + if (args[i].equals("-h")) { + usage(); + System.exit(0); + } else if (args[i].equals("-v")) { + verbose = true; + } else if (args[i].equals("-l")) { + list = true; } else if (args[i].equals("-t")) { if (++i >= args.length) die("Error: no timeout value specified"); @@ -138,64 +138,64 @@ public class Main { } catch (Exception e) { die("Error: unable to determine timeout value"); } - } else if (args[i].equals("-o")) { - if (++i >= args.length) - die("Error: no output file specified"); - try { - repstr = new FileOutputStream(args[i]); - } catch (IOException e) { - die("Error: unable to open \"" + args[i] + "\""); - } - } else if (args[i].equals("-c")) { - if (++i >= args.length) - die("Error: no config file specified"); - try { - confstr = new FileInputStream(args[i]); - } catch (IOException e) { - die("Error: unable to open \"" + args[i] + "\""); - } - } else if (args[i].equals("-html")) { - if (format != TEXT) - die("Error: conflicting formats"); - format = HTML; - } else if (args[i].equals("-xml")) { - if (format != TEXT) - die("Error: conflicting formats"); - format = XML; - } else { - System.err.println("Illegal option: \"" + args[i] + "\""); - usage(); - System.exit(1); - } - } + } else if (args[i].equals("-o")) { + if (++i >= args.length) + die("Error: no output file specified"); + try { + repstr = new FileOutputStream(args[i]); + } catch (IOException e) { + die("Error: unable to open \"" + args[i] + "\""); + } + } else if (args[i].equals("-c")) { + if (++i >= args.length) + die("Error: no config file specified"); + try { + confstr = new FileInputStream(args[i]); + } catch (IOException e) { + die("Error: unable to open \"" + args[i] + "\""); + } + } else if (args[i].equals("-html")) { + if (format != TEXT) + die("Error: conflicting formats"); + format = HTML; + } else if (args[i].equals("-xml")) { + if (format != TEXT) + die("Error: conflicting formats"); + format = XML; + } else { + System.err.println("Illegal option: \"" + args[i] + "\""); + usage(); + System.exit(1); + } + } } - + /** * Set up configuration file and report streams, if not set already. */ static void setupStreams() { - if (repstr == null) - repstr = System.out; - if (confstr == null) - confstr = (new Main()).getClass().getResourceAsStream(CONFFILE); - if (confstr == null) - die("Error: unable to find default config file"); + if (repstr == null) + repstr = System.out; + if (confstr == null) + confstr = (new Main()).getClass().getResourceAsStream(CONFFILE); + if (confstr == null) + die("Error: unable to find default config file"); } - + /** * Print contents of configuration file to selected output stream. */ static void listConfig() { - try { - byte[] buf = new byte[256]; - int len; - while ((len = confstr.read(buf)) != -1) - repstr.write(buf, 0, len); - } catch (IOException e) { - die("Error: failed to list config file"); - } + try { + byte[] buf = new byte[256]; + int len; + while ((len = confstr.read(buf)) != -1) + repstr.write(buf, 0, len); + } catch (IOException e) { + die("Error: failed to list config file"); + } } - + /** * Set up the timer to end the test. * @@ -222,12 +222,12 @@ public class Main { } catch (ConfigFormatException e) { String errmsg = e.getMessage(); if (errmsg != null) { - die("Error parsing config file: " + errmsg); - } else { + die("Error parsing config file: " + errmsg); + } else { die("Error: illegal config file syntax"); - } + } } catch (IOException e) { - die("Error: failed to read config file"); + die("Error: failed to read config file"); } } @@ -236,22 +236,22 @@ public class Main { */ static void setupReporter() { String title = "Object Serialization Benchmark, v" + VERSION; - switch (format) { - case TEXT: - reporter = new TextReporter(repstr, title); - break; - - case HTML: - reporter = new HtmlReporter(repstr, title); - break; + switch (format) { + case TEXT: + reporter = new TextReporter(repstr, title); + break; - case XML: - reporter = new XmlReporter(repstr, title); - break; - - default: - die("Error: unrecognized format type"); - } + case HTML: + reporter = new HtmlReporter(repstr, title); + break; + + case XML: + reporter = new XmlReporter(repstr, title); + break; + + default: + die("Error: unrecognized format type"); + } } /** @@ -261,4 +261,3 @@ public class Main { harness.runBenchmarks(reporter, verbose); } } - diff --git a/jdk/test/java/rmi/reliability/benchmark/bench/serial/ObjArrays.java b/jdk/test/java/rmi/reliability/benchmark/bench/serial/ObjArrays.java index 1bd833e19c2..b9b1ec5fb7a 100644 --- a/jdk/test/java/rmi/reliability/benchmark/bench/serial/ObjArrays.java +++ b/jdk/test/java/rmi/reliability/benchmark/bench/serial/ObjArrays.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -39,16 +39,16 @@ public class ObjArrays implements Benchmark { static class Node implements Serializable { boolean z; - byte b; - char c; - short s; - int i; - float f; - long j; - double d; - String str = "bodega"; + byte b; + char c; + short s; + int i; + float f; + long j; + double d; + String str = "bodega"; Object parent, left, right; - + Node(Object parent, int depth) { this.parent = parent; if (depth > 0) { @@ -57,7 +57,7 @@ public class ObjArrays implements Benchmark { } } } - + /** * Write and read object arrays to/from a stream. The benchmark is run in * batches, with each batch consisting of a fixed number of read/write @@ -66,34 +66,34 @@ public class ObjArrays implements Benchmark { * Arguments: <# batches> <# cycles per batch> */ public long run(String[] args) throws Exception { - int size = Integer.parseInt(args[0]); - int nbatches = Integer.parseInt(args[1]); - int ncycles = Integer.parseInt(args[2]); - Node[][] arrays = genArrays(size, ncycles); - StreamBuffer sbuf = new StreamBuffer(); - ObjectOutputStream oout = - new ObjectOutputStream(sbuf.getOutputStream()); - ObjectInputStream oin = - new ObjectInputStream(sbuf.getInputStream()); + int size = Integer.parseInt(args[0]); + int nbatches = Integer.parseInt(args[1]); + int ncycles = Integer.parseInt(args[2]); + Node[][] arrays = genArrays(size, ncycles); + StreamBuffer sbuf = new StreamBuffer(); + ObjectOutputStream oout = + new ObjectOutputStream(sbuf.getOutputStream()); + ObjectInputStream oin = + new ObjectInputStream(sbuf.getInputStream()); - doReps(oout, oin, sbuf, arrays, 1); // warmup + doReps(oout, oin, sbuf, arrays, 1); // warmup - long start = System.currentTimeMillis(); - doReps(oout, oin, sbuf, arrays, nbatches); + long start = System.currentTimeMillis(); + doReps(oout, oin, sbuf, arrays, nbatches); return System.currentTimeMillis() - start; } - + /** * Generate object arrays. */ Node[][] genArrays(int size, int narrays) { - Node[][] arrays = new Node[narrays][size]; - for (int i = 0; i < narrays; i++) { - for (int j = 0; j < size; j++) { - arrays[i][j] = new Node(null, 0); - } - } - return arrays; + Node[][] arrays = new Node[narrays][size]; + for (int i = 0; i < narrays; i++) { + for (int j = 0; j < size; j++) { + arrays[i][j] = new Node(null, 0); + } + } + return arrays; } /** @@ -101,22 +101,20 @@ public class ObjArrays implements Benchmark { * for each batch. */ void doReps(ObjectOutputStream oout, ObjectInputStream oin, - StreamBuffer sbuf, Node[][] arrays, int nbatches) - throws Exception + StreamBuffer sbuf, Node[][] arrays, int nbatches) + throws Exception { - int ncycles = arrays.length; - for (int i = 0; i < nbatches; i++) { - sbuf.reset(); - oout.reset(); - for (int j = 0; j < ncycles; j++) { - oout.writeObject(arrays[j]); - } - oout.flush(); - for (int j = 0; j < ncycles; j++) { - oin.readObject(); - } - } + int ncycles = arrays.length; + for (int i = 0; i < nbatches; i++) { + sbuf.reset(); + oout.reset(); + for (int j = 0; j < ncycles; j++) { + oout.writeObject(arrays[j]); + } + oout.flush(); + for (int j = 0; j < ncycles; j++) { + oin.readObject(); + } + } } } - - diff --git a/jdk/test/java/rmi/reliability/benchmark/bench/serial/ObjTrees.java b/jdk/test/java/rmi/reliability/benchmark/bench/serial/ObjTrees.java index 2fc1cc57a90..f9405ba1d9c 100644 --- a/jdk/test/java/rmi/reliability/benchmark/bench/serial/ObjTrees.java +++ b/jdk/test/java/rmi/reliability/benchmark/bench/serial/ObjTrees.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -36,19 +36,19 @@ import java.io.Serializable; * Benchmark for testing speed of writes and reads of an object tree. */ public class ObjTrees implements Benchmark { - + static class Node implements Serializable { boolean z; - byte b; - char c; - short s; - int i; - float f; - long j; - double d; - String str = "bodega"; + byte b; + char c; + short s; + int i; + float f; + long j; + double d; + String str = "bodega"; Object parent, left, right; - + Node(Object parent, int depth) { this.parent = parent; if (depth > 0) { @@ -66,20 +66,20 @@ public class ObjTrees implements Benchmark { * Arguments: <# batches> <# cycles per batch> */ public long run(String[] args) throws Exception { - int depth = Integer.parseInt(args[0]); - int nbatches = Integer.parseInt(args[1]); - int ncycles = Integer.parseInt(args[2]); - Node[] trees = genTrees(depth, ncycles); - StreamBuffer sbuf = new StreamBuffer(); - ObjectOutputStream oout = - new ObjectOutputStream(sbuf.getOutputStream()); - ObjectInputStream oin = - new ObjectInputStream(sbuf.getInputStream()); - - doReps(oout, oin, sbuf, trees, 1); // warmup + int depth = Integer.parseInt(args[0]); + int nbatches = Integer.parseInt(args[1]); + int ncycles = Integer.parseInt(args[2]); + Node[] trees = genTrees(depth, ncycles); + StreamBuffer sbuf = new StreamBuffer(); + ObjectOutputStream oout = + new ObjectOutputStream(sbuf.getOutputStream()); + ObjectInputStream oin = + new ObjectInputStream(sbuf.getInputStream()); - long start = System.currentTimeMillis(); - doReps(oout, oin, sbuf, trees, nbatches); + doReps(oout, oin, sbuf, trees, 1); // warmup + + long start = System.currentTimeMillis(); + doReps(oout, oin, sbuf, trees, nbatches); return System.currentTimeMillis() - start; } @@ -87,33 +87,32 @@ public class ObjTrees implements Benchmark { * Generate object trees. */ Node[] genTrees(int depth, int ntrees) { - Node[] trees = new Node[ntrees]; - for (int i = 0; i < ntrees; i++) { - trees[i] = new Node(null, depth); - } - return trees; + Node[] trees = new Node[ntrees]; + for (int i = 0; i < ntrees; i++) { + trees[i] = new Node(null, depth); + } + return trees; } /** - * Run benchmark for given number of batches, with each batch containing + * Run benchmark for given number of batches, with each batch containing * the given number of cycles. */ void doReps(ObjectOutputStream oout, ObjectInputStream oin, - StreamBuffer sbuf, Node[] trees, int nbatches) - throws Exception + StreamBuffer sbuf, Node[] trees, int nbatches) + throws Exception { - int ncycles = trees.length; - for (int i = 0; i < nbatches; i++) { - sbuf.reset(); - oout.reset(); - for (int j = 0; j < ncycles; j++) { - oout.writeObject(trees[j]); - } - oout.flush(); - for (int j = 0; j < ncycles; j++) { - oin.readObject(); - } - } + int ncycles = trees.length; + for (int i = 0; i < nbatches; i++) { + sbuf.reset(); + oout.reset(); + for (int j = 0; j < ncycles; j++) { + oout.writeObject(trees[j]); + } + oout.flush(); + for (int j = 0; j < ncycles; j++) { + oin.readObject(); + } + } } } - diff --git a/jdk/test/java/rmi/reliability/benchmark/bench/serial/ProxyArrays.java b/jdk/test/java/rmi/reliability/benchmark/bench/serial/ProxyArrays.java index 2a114eac6ca..c6ad86dd50e 100644 --- a/jdk/test/java/rmi/reliability/benchmark/bench/serial/ProxyArrays.java +++ b/jdk/test/java/rmi/reliability/benchmark/bench/serial/ProxyArrays.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -42,15 +42,15 @@ import java.lang.reflect.Proxy; public class ProxyArrays implements Benchmark { static class DummyHandler implements InvocationHandler, Serializable { - public Object invoke(Object proxy, Method method, Object[] args) - throws Throwable - { - return null; - } + public Object invoke(Object proxy, Method method, Object[] args) + throws Throwable + { + return null; + } } - + static interface DummyInterface { - public void foo(); + public void foo(); } /** @@ -61,40 +61,40 @@ public class ProxyArrays implements Benchmark { * Arguments: <# batches> <# cycles per batch> */ public long run(String[] args) throws Exception { - int size = Integer.parseInt(args[0]); - int nbatches = Integer.parseInt(args[1]); - int ncycles = Integer.parseInt(args[2]); - Proxy[][] arrays = genArrays(size, ncycles); - StreamBuffer sbuf = new StreamBuffer(); - ObjectOutputStream oout = - new ObjectOutputStream(sbuf.getOutputStream()); - ObjectInputStream oin = - new ObjectInputStream(sbuf.getInputStream()); + int size = Integer.parseInt(args[0]); + int nbatches = Integer.parseInt(args[1]); + int ncycles = Integer.parseInt(args[2]); + Proxy[][] arrays = genArrays(size, ncycles); + StreamBuffer sbuf = new StreamBuffer(); + ObjectOutputStream oout = + new ObjectOutputStream(sbuf.getOutputStream()); + ObjectInputStream oin = + new ObjectInputStream(sbuf.getInputStream()); - doReps(oout, oin, sbuf, arrays, 1); // warmup + doReps(oout, oin, sbuf, arrays, 1); // warmup - long start = System.currentTimeMillis(); - doReps(oout, oin, sbuf, arrays, nbatches); + long start = System.currentTimeMillis(); + doReps(oout, oin, sbuf, arrays, nbatches); return System.currentTimeMillis() - start; } - + /** * Generate proxy arrays. */ Proxy[][] genArrays(int size, int narrays) throws Exception { - Class proxyClass = - Proxy.getProxyClass(DummyInterface.class.getClassLoader(), - new Class[] { DummyInterface.class }); - Constructor proxyCons = - proxyClass.getConstructor(new Class[] { InvocationHandler.class }); - Object[] consArgs = new Object[] { new DummyHandler() }; - Proxy[][] arrays = new Proxy[narrays][size]; - for (int i = 0; i < narrays; i++) { - for (int j = 0; j < size; j++) { - arrays[i][j] = (Proxy) proxyCons.newInstance(consArgs); - } - } - return arrays; + Class proxyClass = + Proxy.getProxyClass(DummyInterface.class.getClassLoader(), + new Class[] { DummyInterface.class }); + Constructor proxyCons = + proxyClass.getConstructor(new Class[] { InvocationHandler.class }); + Object[] consArgs = new Object[] { new DummyHandler() }; + Proxy[][] arrays = new Proxy[narrays][size]; + for (int i = 0; i < narrays; i++) { + for (int j = 0; j < size; j++) { + arrays[i][j] = (Proxy) proxyCons.newInstance(consArgs); + } + } + return arrays; } /** @@ -102,22 +102,20 @@ public class ProxyArrays implements Benchmark { * for each batch. */ void doReps(ObjectOutputStream oout, ObjectInputStream oin, - StreamBuffer sbuf, Proxy[][] arrays, int nbatches) - throws Exception + StreamBuffer sbuf, Proxy[][] arrays, int nbatches) + throws Exception { - int ncycles = arrays.length; - for (int i = 0; i < nbatches; i++) { - sbuf.reset(); - oout.reset(); - for (int j = 0; j < ncycles; j++) { - oout.writeObject(arrays[j]); - } - oout.flush(); - for (int j = 0; j < ncycles; j++) { - oin.readObject(); - } - } + int ncycles = arrays.length; + for (int i = 0; i < nbatches; i++) { + sbuf.reset(); + oout.reset(); + for (int j = 0; j < ncycles; j++) { + oout.writeObject(arrays[j]); + } + oout.flush(); + for (int j = 0; j < ncycles; j++) { + oin.readObject(); + } + } } } - - diff --git a/jdk/test/java/rmi/reliability/benchmark/bench/serial/ProxyClassDesc.java b/jdk/test/java/rmi/reliability/benchmark/bench/serial/ProxyClassDesc.java index a5ae07a09ad..4a0576361a2 100644 --- a/jdk/test/java/rmi/reliability/benchmark/bench/serial/ProxyClassDesc.java +++ b/jdk/test/java/rmi/reliability/benchmark/bench/serial/ProxyClassDesc.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -38,7 +38,7 @@ import java.lang.reflect.Proxy; * Benchmark for testing speed of proxy class descriptor reads/writes. */ public class ProxyClassDesc implements Benchmark { - + static interface A1 {}; static interface A2 {}; static interface A3 {}; @@ -54,75 +54,74 @@ public class ProxyClassDesc implements Benchmark { static interface C3 {}; static interface C4 {}; static interface C5 {}; - + /** * Write and read proxy class descriptors to/from a stream. * Arguments: <# cycles> */ public long run(String[] args) throws Exception { - int ncycles = Integer.parseInt(args[0]); - StreamBuffer sbuf = new StreamBuffer(); - ObjectOutputStream oout = - new ObjectOutputStream(sbuf.getOutputStream()); - ObjectInputStream oin = - new ObjectInputStream(sbuf.getInputStream()); - ObjectStreamClass[] descs = genDescs(); + int ncycles = Integer.parseInt(args[0]); + StreamBuffer sbuf = new StreamBuffer(); + ObjectOutputStream oout = + new ObjectOutputStream(sbuf.getOutputStream()); + ObjectInputStream oin = + new ObjectInputStream(sbuf.getInputStream()); + ObjectStreamClass[] descs = genDescs(); - doReps(oout, oin, sbuf, descs, 1); // warmup + doReps(oout, oin, sbuf, descs, 1); // warmup - long start = System.currentTimeMillis(); - doReps(oout, oin, sbuf, descs, ncycles); + long start = System.currentTimeMillis(); + doReps(oout, oin, sbuf, descs, ncycles); return System.currentTimeMillis() - start; } - + /** * Generate proxy class descriptors. */ ObjectStreamClass[] genDescs() { - ClassLoader ldr = ProxyClassDesc.class.getClassLoader(); - Class[] ifaces = new Class[3]; - Class[] a = - new Class[] { A1.class, A2.class, A3.class, A4.class, A5.class }; - Class[] b = - new Class[] { B1.class, B2.class, B3.class, B4.class, B5.class }; - Class[] c = - new Class[] { C1.class, C2.class, C3.class, C4.class, C5.class }; - ObjectStreamClass[] descs = - new ObjectStreamClass[a.length * b.length * c.length]; - int n = 0; - for (int i = 0; i < a.length; i++) { - ifaces[0] = a[i]; - for (int j = 0; j < b.length; j++) { - ifaces[1] = b[j]; - for (int k = 0; k < c.length; k++) { - ifaces[2] = c[k]; - Class proxyClass = Proxy.getProxyClass(ldr, ifaces); - descs[n++] = ObjectStreamClass.lookup(proxyClass); - } - } - } - return descs; + ClassLoader ldr = ProxyClassDesc.class.getClassLoader(); + Class[] ifaces = new Class[3]; + Class[] a = + new Class[] { A1.class, A2.class, A3.class, A4.class, A5.class }; + Class[] b = + new Class[] { B1.class, B2.class, B3.class, B4.class, B5.class }; + Class[] c = + new Class[] { C1.class, C2.class, C3.class, C4.class, C5.class }; + ObjectStreamClass[] descs = + new ObjectStreamClass[a.length * b.length * c.length]; + int n = 0; + for (int i = 0; i < a.length; i++) { + ifaces[0] = a[i]; + for (int j = 0; j < b.length; j++) { + ifaces[1] = b[j]; + for (int k = 0; k < c.length; k++) { + ifaces[2] = c[k]; + Class proxyClass = Proxy.getProxyClass(ldr, ifaces); + descs[n++] = ObjectStreamClass.lookup(proxyClass); + } + } + } + return descs; } /** * Run benchmark for given number of cycles. */ void doReps(ObjectOutputStream oout, ObjectInputStream oin, - StreamBuffer sbuf, ObjectStreamClass[] descs, int ncycles) - throws Exception + StreamBuffer sbuf, ObjectStreamClass[] descs, int ncycles) + throws Exception { - int ndescs = descs.length; - for (int i = 0; i < ncycles; i++) { - sbuf.reset(); - oout.reset(); - for (int j = 0; j < ndescs; j++) { - oout.writeObject(descs[j]); - } - oout.flush(); - for (int j = 0; j < ndescs; j++) { - oin.readObject(); - } - } + int ndescs = descs.length; + for (int i = 0; i < ncycles; i++) { + sbuf.reset(); + oout.reset(); + for (int j = 0; j < ndescs; j++) { + oout.writeObject(descs[j]); + } + oout.flush(); + for (int j = 0; j < ndescs; j++) { + oin.readObject(); + } + } } } - diff --git a/jdk/test/java/rmi/reliability/benchmark/bench/serial/RepeatObjs.java b/jdk/test/java/rmi/reliability/benchmark/bench/serial/RepeatObjs.java index ba95b451e60..08ae15908ef 100644 --- a/jdk/test/java/rmi/reliability/benchmark/bench/serial/RepeatObjs.java +++ b/jdk/test/java/rmi/reliability/benchmark/bench/serial/RepeatObjs.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -36,7 +36,7 @@ import java.io.Serializable; * Benchmark for testing speed of reads/writes of repeated objects. */ public class RepeatObjs implements Benchmark { - + static class Node implements Serializable { } @@ -49,50 +49,49 @@ public class RepeatObjs implements Benchmark { * Arguments: <# objects> <# cycles> */ public long run(String[] args) throws Exception { - int size = Integer.parseInt(args[0]); - int nbatches = Integer.parseInt(args[1]); - Node[] objs = genObjs(size); - StreamBuffer sbuf = new StreamBuffer(); - ObjectOutputStream oout = - new ObjectOutputStream(sbuf.getOutputStream()); - ObjectInputStream oin = - new ObjectInputStream(sbuf.getInputStream()); - - doReps(oout, oin, sbuf, objs, 1); // warmup + int size = Integer.parseInt(args[0]); + int nbatches = Integer.parseInt(args[1]); + Node[] objs = genObjs(size); + StreamBuffer sbuf = new StreamBuffer(); + ObjectOutputStream oout = + new ObjectOutputStream(sbuf.getOutputStream()); + ObjectInputStream oin = + new ObjectInputStream(sbuf.getInputStream()); - long start = System.currentTimeMillis(); - doReps(oout, oin, sbuf, objs, nbatches); + doReps(oout, oin, sbuf, objs, 1); // warmup + + long start = System.currentTimeMillis(); + doReps(oout, oin, sbuf, objs, nbatches); return System.currentTimeMillis() - start; } - + /** * Generate objects. */ Node[] genObjs(int nobjs) { - Node[] objs = new Node[nobjs]; - for (int i = 0; i < nobjs; i++) - objs[i] = new Node(); - return objs; + Node[] objs = new Node[nobjs]; + for (int i = 0; i < nobjs; i++) + objs[i] = new Node(); + return objs; } - + /** * Run benchmark for given number of batches. */ void doReps(ObjectOutputStream oout, ObjectInputStream oin, - StreamBuffer sbuf, Node[] objs, int nbatches) - throws Exception + StreamBuffer sbuf, Node[] objs, int nbatches) + throws Exception { - int nobjs = objs.length; - for (int i = 0; i < nbatches; i++) { - sbuf.reset(); - for (int j = 0; j < nobjs; j++) { - oout.writeObject(objs[j]); - } - oout.flush(); - for (int j = 0; j < nobjs; j++) { - oin.readObject(); - } - } + int nobjs = objs.length; + for (int i = 0; i < nbatches; i++) { + sbuf.reset(); + for (int j = 0; j < nobjs; j++) { + oout.writeObject(objs[j]); + } + oout.flush(); + for (int j = 0; j < nobjs; j++) { + oin.readObject(); + } + } } } - diff --git a/jdk/test/java/rmi/reliability/benchmark/bench/serial/ReplaceTrees.java b/jdk/test/java/rmi/reliability/benchmark/bench/serial/ReplaceTrees.java index f52f0438a59..e117453bd9b 100644 --- a/jdk/test/java/rmi/reliability/benchmark/bench/serial/ReplaceTrees.java +++ b/jdk/test/java/rmi/reliability/benchmark/bench/serial/ReplaceTrees.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -37,15 +37,15 @@ import java.io.Serializable; * objects. */ public class ReplaceTrees implements Benchmark { - + static class Node implements Serializable { Object parent, left, right; - - Node(Object parent, Object left, Object right) { - this.parent = parent; - this.left = left; - this.right = right; - } + + Node(Object parent, Object left, Object right) { + this.parent = parent; + this.left = left; + this.right = right; + } Node(Object parent, int depth) { this.parent = parent; @@ -54,26 +54,26 @@ public class ReplaceTrees implements Benchmark { right = new Node(this, depth - 1); } } - - Object writeReplace() { - return new RepNode(parent, left, right); - } + + Object writeReplace() { + return new RepNode(parent, left, right); + } } - + static class RepNode implements Serializable { - Object parent, left, right; - - RepNode(Object parent, Object left, Object right) { - this.parent = parent; - this.left = left; - this.right = right; - } - - Object readResolve() { - return new Node(parent, left, right); - } + Object parent, left, right; + + RepNode(Object parent, Object left, Object right) { + this.parent = parent; + this.left = left; + this.right = right; + } + + Object readResolve() { + return new Node(parent, left, right); + } } - + /** * Write and read a tree of replaceable objects from a stream. The * benchmark is run in batches: each "batch" consists of a fixed number of @@ -82,20 +82,20 @@ public class ReplaceTrees implements Benchmark { * Arguments: <# batches> <# cycles per batch> */ public long run(String[] args) throws Exception { - int depth = Integer.parseInt(args[0]); - int nbatches = Integer.parseInt(args[1]); - int ncycles = Integer.parseInt(args[2]); - Node[] trees = genTrees(depth, ncycles); - StreamBuffer sbuf = new StreamBuffer(); - ObjectOutputStream oout = - new ObjectOutputStream(sbuf.getOutputStream()); - ObjectInputStream oin = - new ObjectInputStream(sbuf.getInputStream()); - - doReps(oout, oin, sbuf, trees, 1); // warmup + int depth = Integer.parseInt(args[0]); + int nbatches = Integer.parseInt(args[1]); + int ncycles = Integer.parseInt(args[2]); + Node[] trees = genTrees(depth, ncycles); + StreamBuffer sbuf = new StreamBuffer(); + ObjectOutputStream oout = + new ObjectOutputStream(sbuf.getOutputStream()); + ObjectInputStream oin = + new ObjectInputStream(sbuf.getInputStream()); - long start = System.currentTimeMillis(); - doReps(oout, oin, sbuf, trees, nbatches); + doReps(oout, oin, sbuf, trees, 1); // warmup + + long start = System.currentTimeMillis(); + doReps(oout, oin, sbuf, trees, nbatches); return System.currentTimeMillis() - start; } @@ -103,11 +103,11 @@ public class ReplaceTrees implements Benchmark { * Generate object trees. */ Node[] genTrees(int depth, int ntrees) { - Node[] trees = new Node[ntrees]; - for (int i = 0; i < ntrees; i++) { - trees[i] = new Node(null, depth); - } - return trees; + Node[] trees = new Node[ntrees]; + for (int i = 0; i < ntrees; i++) { + trees[i] = new Node(null, depth); + } + return trees; } /** @@ -115,21 +115,20 @@ public class ReplaceTrees implements Benchmark { * the given number of cycles. */ void doReps(ObjectOutputStream oout, ObjectInputStream oin, - StreamBuffer sbuf, Node[] trees, int nbatches) - throws Exception + StreamBuffer sbuf, Node[] trees, int nbatches) + throws Exception { - int ncycles = trees.length; - for (int i = 0; i < nbatches; i++) { - sbuf.reset(); - oout.reset(); - for (int j = 0; j < ncycles; j++) { - oout.writeObject(trees[j]); - } - oout.flush(); - for (int j = 0; j < ncycles; j++) { - oin.readObject(); - } - } + int ncycles = trees.length; + for (int i = 0; i < nbatches; i++) { + sbuf.reset(); + oout.reset(); + for (int j = 0; j < ncycles; j++) { + oout.writeObject(trees[j]); + } + oout.flush(); + for (int j = 0; j < ncycles; j++) { + oin.readObject(); + } + } } } - diff --git a/jdk/test/java/rmi/reliability/benchmark/bench/serial/ShortArrays.java b/jdk/test/java/rmi/reliability/benchmark/bench/serial/ShortArrays.java index 9b8cf10a5ec..45339999c5b 100644 --- a/jdk/test/java/rmi/reliability/benchmark/bench/serial/ShortArrays.java +++ b/jdk/test/java/rmi/reliability/benchmark/bench/serial/ShortArrays.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -35,7 +35,7 @@ import java.io.ObjectOutputStream; * Benchmark for testing speed of short array reads/writes. */ public class ShortArrays implements Benchmark { - + /** * Write and read short arrays to/from a stream. The benchmark is run in * batches, with each batch consisting of a fixed number of read/write @@ -44,44 +44,42 @@ public class ShortArrays implements Benchmark { * Arguments: <# batches> <# cycles per batch> */ public long run(String[] args) throws Exception { - int size = Integer.parseInt(args[0]); - int nbatches = Integer.parseInt(args[1]); - int ncycles = Integer.parseInt(args[2]); - short[][] arrays = new short[ncycles][size]; - StreamBuffer sbuf = new StreamBuffer(); - ObjectOutputStream oout = - new ObjectOutputStream(sbuf.getOutputStream()); - ObjectInputStream oin = - new ObjectInputStream(sbuf.getInputStream()); + int size = Integer.parseInt(args[0]); + int nbatches = Integer.parseInt(args[1]); + int ncycles = Integer.parseInt(args[2]); + short[][] arrays = new short[ncycles][size]; + StreamBuffer sbuf = new StreamBuffer(); + ObjectOutputStream oout = + new ObjectOutputStream(sbuf.getOutputStream()); + ObjectInputStream oin = + new ObjectInputStream(sbuf.getInputStream()); - doReps(oout, oin, sbuf, arrays, 1); // warmup + doReps(oout, oin, sbuf, arrays, 1); // warmup - long start = System.currentTimeMillis(); - doReps(oout, oin, sbuf, arrays, nbatches); + long start = System.currentTimeMillis(); + doReps(oout, oin, sbuf, arrays, nbatches); return System.currentTimeMillis() - start; } - + /** * Run benchmark for given number of batches, with given number of cycles * for each batch. */ void doReps(ObjectOutputStream oout, ObjectInputStream oin, - StreamBuffer sbuf, short[][] arrays, int nbatches) - throws Exception + StreamBuffer sbuf, short[][] arrays, int nbatches) + throws Exception { - int ncycles = arrays.length; - for (int i = 0; i < nbatches; i++) { - sbuf.reset(); - oout.reset(); - for (int j = 0; j < ncycles; j++) { - oout.writeObject(arrays[j]); - } - oout.flush(); - for (int j = 0; j < ncycles; j++) { - oin.readObject(); - } - } + int ncycles = arrays.length; + for (int i = 0; i < nbatches; i++) { + sbuf.reset(); + oout.reset(); + for (int j = 0; j < ncycles; j++) { + oout.writeObject(arrays[j]); + } + oout.flush(); + for (int j = 0; j < ncycles; j++) { + oin.readObject(); + } + } } } - - diff --git a/jdk/test/java/rmi/reliability/benchmark/bench/serial/Shorts.java b/jdk/test/java/rmi/reliability/benchmark/bench/serial/Shorts.java index 985d7302a37..dafdf53c9f3 100644 --- a/jdk/test/java/rmi/reliability/benchmark/bench/serial/Shorts.java +++ b/jdk/test/java/rmi/reliability/benchmark/bench/serial/Shorts.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -35,7 +35,7 @@ import java.io.ObjectOutputStream; * Benchmark for testing speed of short reads/writes. */ public class Shorts implements Benchmark { - + /** * Write and read short values to/from a stream. The benchmark is run in * batches: each "batch" consists of a fixed number of read/write cycles, @@ -44,39 +44,38 @@ public class Shorts implements Benchmark { * Arguments: <# batches> <# cycles per batch> */ public long run(String[] args) throws Exception { - int nbatches = Integer.parseInt(args[0]); - int ncycles = Integer.parseInt(args[1]); - StreamBuffer sbuf = new StreamBuffer(); - ObjectOutputStream oout = - new ObjectOutputStream(sbuf.getOutputStream()); - ObjectInputStream oin = - new ObjectInputStream(sbuf.getInputStream()); - - doReps(oout, oin, sbuf, 1, ncycles); // warmup + int nbatches = Integer.parseInt(args[0]); + int ncycles = Integer.parseInt(args[1]); + StreamBuffer sbuf = new StreamBuffer(); + ObjectOutputStream oout = + new ObjectOutputStream(sbuf.getOutputStream()); + ObjectInputStream oin = + new ObjectInputStream(sbuf.getInputStream()); - long start = System.currentTimeMillis(); - doReps(oout, oin, sbuf, nbatches, ncycles); + doReps(oout, oin, sbuf, 1, ncycles); // warmup + + long start = System.currentTimeMillis(); + doReps(oout, oin, sbuf, nbatches, ncycles); return System.currentTimeMillis() - start; } - + /** * Run benchmark for given number of batches, with given number of cycles * for each batch. */ void doReps(ObjectOutputStream oout, ObjectInputStream oin, - StreamBuffer sbuf, int nbatches, int ncycles) - throws Exception + StreamBuffer sbuf, int nbatches, int ncycles) + throws Exception { - for (int i = 0; i < nbatches; i++) { - sbuf.reset(); - for (int j = 0; j < ncycles; j++) { - oout.writeShort(0); - } - oout.flush(); - for (int j = 0; j < ncycles; j++) { - oin.readShort(); - } - } + for (int i = 0; i < nbatches; i++) { + sbuf.reset(); + for (int j = 0; j < ncycles; j++) { + oout.writeShort(0); + } + oout.flush(); + for (int j = 0; j < ncycles; j++) { + oin.readShort(); + } + } } } - diff --git a/jdk/test/java/rmi/reliability/benchmark/bench/serial/SmallObjTrees.java b/jdk/test/java/rmi/reliability/benchmark/bench/serial/SmallObjTrees.java index 30bebd76d64..bb0394f3986 100644 --- a/jdk/test/java/rmi/reliability/benchmark/bench/serial/SmallObjTrees.java +++ b/jdk/test/java/rmi/reliability/benchmark/bench/serial/SmallObjTrees.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -36,10 +36,10 @@ import java.io.Serializable; * Benchmark for testing speed of writes and reads of a tree of small objects. */ public class SmallObjTrees implements Benchmark { - + static class Node implements Serializable { Object parent, left, right; - + Node(Object parent, int depth) { this.parent = parent; if (depth > 0) { @@ -57,20 +57,20 @@ public class SmallObjTrees implements Benchmark { * Arguments: <# batches> <# cycles per batch> */ public long run(String[] args) throws Exception { - int depth = Integer.parseInt(args[0]); - int nbatches = Integer.parseInt(args[1]); - int ncycles = Integer.parseInt(args[2]); - Node[] trees = genTrees(depth, ncycles); - StreamBuffer sbuf = new StreamBuffer(); - ObjectOutputStream oout = - new ObjectOutputStream(sbuf.getOutputStream()); - ObjectInputStream oin = - new ObjectInputStream(sbuf.getInputStream()); - - doReps(oout, oin, sbuf, trees, 1); // warmup + int depth = Integer.parseInt(args[0]); + int nbatches = Integer.parseInt(args[1]); + int ncycles = Integer.parseInt(args[2]); + Node[] trees = genTrees(depth, ncycles); + StreamBuffer sbuf = new StreamBuffer(); + ObjectOutputStream oout = + new ObjectOutputStream(sbuf.getOutputStream()); + ObjectInputStream oin = + new ObjectInputStream(sbuf.getInputStream()); - long start = System.currentTimeMillis(); - doReps(oout, oin, sbuf, trees, nbatches); + doReps(oout, oin, sbuf, trees, 1); // warmup + + long start = System.currentTimeMillis(); + doReps(oout, oin, sbuf, trees, nbatches); return System.currentTimeMillis() - start; } @@ -78,11 +78,11 @@ public class SmallObjTrees implements Benchmark { * Generate object trees. */ Node[] genTrees(int depth, int ntrees) { - Node[] trees = new Node[ntrees]; - for (int i = 0; i < ntrees; i++) { - trees[i] = new Node(null, depth); - } - return trees; + Node[] trees = new Node[ntrees]; + for (int i = 0; i < ntrees; i++) { + trees[i] = new Node(null, depth); + } + return trees; } /** @@ -90,21 +90,20 @@ public class SmallObjTrees implements Benchmark { * given number of cycles. */ void doReps(ObjectOutputStream oout, ObjectInputStream oin, - StreamBuffer sbuf, Node[] trees, int nbatches) - throws Exception + StreamBuffer sbuf, Node[] trees, int nbatches) + throws Exception { - int ncycles = trees.length; - for (int i = 0; i < nbatches; i++) { - sbuf.reset(); - oout.reset(); - for (int j = 0; j < ncycles; j++) { - oout.writeObject(trees[j]); - } - oout.flush(); - for (int j = 0; j < ncycles; j++) { - oin.readObject(); - } - } + int ncycles = trees.length; + for (int i = 0; i < nbatches; i++) { + sbuf.reset(); + oout.reset(); + for (int j = 0; j < ncycles; j++) { + oout.writeObject(trees[j]); + } + oout.flush(); + for (int j = 0; j < ncycles; j++) { + oin.readObject(); + } + } } } - diff --git a/jdk/test/java/rmi/reliability/benchmark/bench/serial/StreamBuffer.java b/jdk/test/java/rmi/reliability/benchmark/bench/serial/StreamBuffer.java index 100a294d1dd..33efee8724b 100644 --- a/jdk/test/java/rmi/reliability/benchmark/bench/serial/StreamBuffer.java +++ b/jdk/test/java/rmi/reliability/benchmark/bench/serial/StreamBuffer.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -47,85 +47,85 @@ import java.io.IOException; * StreamBufferInputStream.read(). */ public class StreamBuffer { - + /** * Output stream for writing to stream buffer. */ private class StreamBufferOutputStream extends OutputStream { - - private int pos; - public void write(int b) throws IOException { - if (mode != WRITE_MODE) - throw new IOException(); - while (pos >= buf.length) - grow(); - buf[pos++] = (byte) b; - } - - public void write(byte[] b, int off, int len) throws IOException { - if (mode != WRITE_MODE) - throw new IOException(); - while (pos + len > buf.length) - grow(); - System.arraycopy(b, off, buf, pos, len); - pos += len; - } - - public void close() throws IOException { - if (mode != WRITE_MODE) - throw new IOException(); - mode = READ_MODE; - } + private int pos; + + public void write(int b) throws IOException { + if (mode != WRITE_MODE) + throw new IOException(); + while (pos >= buf.length) + grow(); + buf[pos++] = (byte) b; + } + + public void write(byte[] b, int off, int len) throws IOException { + if (mode != WRITE_MODE) + throw new IOException(); + while (pos + len > buf.length) + grow(); + System.arraycopy(b, off, buf, pos, len); + pos += len; + } + + public void close() throws IOException { + if (mode != WRITE_MODE) + throw new IOException(); + mode = READ_MODE; + } } - + /** * Input stream for reading from stream buffer. */ private class StreamBufferInputStream extends InputStream { - - private int pos; - public int read() throws IOException { - if (mode == CLOSED_MODE) - throw new IOException(); - mode = READ_MODE; - return (pos < out.pos) ? (buf[pos++] & 0xFF) : -1; - } - - public int read(byte[] b, int off, int len) throws IOException { - if (mode == CLOSED_MODE) - throw new IOException(); - mode = READ_MODE; - int avail = out.pos - pos; - int rlen = (avail < len) ? avail : len; - System.arraycopy(buf, pos, b, off, rlen); - pos += rlen; - return rlen; - } - - public long skip(long len) throws IOException { - if (mode == CLOSED_MODE) - throw new IOException(); - mode = READ_MODE; - int avail = out.pos - pos; - long slen = (avail < len) ? avail : len; - pos += slen; - return slen; - } + private int pos; - public int available() throws IOException { - if (mode == CLOSED_MODE) - throw new IOException(); - mode = READ_MODE; - return out.pos - pos; - } - - public void close() throws IOException { - if (mode == CLOSED_MODE) - throw new IOException(); - mode = CLOSED_MODE; - } + public int read() throws IOException { + if (mode == CLOSED_MODE) + throw new IOException(); + mode = READ_MODE; + return (pos < out.pos) ? (buf[pos++] & 0xFF) : -1; + } + + public int read(byte[] b, int off, int len) throws IOException { + if (mode == CLOSED_MODE) + throw new IOException(); + mode = READ_MODE; + int avail = out.pos - pos; + int rlen = (avail < len) ? avail : len; + System.arraycopy(buf, pos, b, off, rlen); + pos += rlen; + return rlen; + } + + public long skip(long len) throws IOException { + if (mode == CLOSED_MODE) + throw new IOException(); + mode = READ_MODE; + int avail = out.pos - pos; + long slen = (avail < len) ? avail : len; + pos += slen; + return slen; + } + + public int available() throws IOException { + if (mode == CLOSED_MODE) + throw new IOException(); + mode = READ_MODE; + return out.pos - pos; + } + + public void close() throws IOException { + if (mode == CLOSED_MODE) + throw new IOException(); + mode = CLOSED_MODE; + } } private static final int START_BUFSIZE = 256; @@ -140,30 +140,29 @@ public class StreamBuffer { private int mode = WRITE_MODE; public StreamBuffer() { - this(START_BUFSIZE); + this(START_BUFSIZE); } - + public StreamBuffer(int size) { - buf = new byte[size]; + buf = new byte[size]; } - + public OutputStream getOutputStream() { - return out; + return out; } - + public InputStream getInputStream() { - return in; + return in; } - + public void reset() { - in.pos = out.pos = 0; - mode = WRITE_MODE; + in.pos = out.pos = 0; + mode = WRITE_MODE; } - + private void grow() { - byte[] newbuf = new byte[buf.length * GROW_FACTOR]; - System.arraycopy(buf, 0, newbuf, 0, buf.length); - buf = newbuf; + byte[] newbuf = new byte[buf.length * GROW_FACTOR]; + System.arraycopy(buf, 0, newbuf, 0, buf.length); + buf = newbuf; } } - diff --git a/jdk/test/java/rmi/reliability/benchmark/bench/serial/Strings.java b/jdk/test/java/rmi/reliability/benchmark/bench/serial/Strings.java index aad74b7212b..512e1a33de4 100644 --- a/jdk/test/java/rmi/reliability/benchmark/bench/serial/Strings.java +++ b/jdk/test/java/rmi/reliability/benchmark/bench/serial/Strings.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -45,20 +45,20 @@ public class Strings implements Benchmark { * Arguments: <# batches> <# cycles per batch> */ public long run(String[] args) throws Exception { - int slen = Integer.parseInt(args[0]); - int nbatches = Integer.parseInt(args[1]); - int ncycles = Integer.parseInt(args[2]); - String[] strs = genStrings(slen, ncycles); - StreamBuffer sbuf = new StreamBuffer(); - ObjectOutputStream oout = - new ObjectOutputStream(sbuf.getOutputStream()); - ObjectInputStream oin = - new ObjectInputStream(sbuf.getInputStream()); - - doReps(oout, oin, sbuf, strs, 1, ncycles); // warmup + int slen = Integer.parseInt(args[0]); + int nbatches = Integer.parseInt(args[1]); + int ncycles = Integer.parseInt(args[2]); + String[] strs = genStrings(slen, ncycles); + StreamBuffer sbuf = new StreamBuffer(); + ObjectOutputStream oout = + new ObjectOutputStream(sbuf.getOutputStream()); + ObjectInputStream oin = + new ObjectInputStream(sbuf.getInputStream()); - long start = System.currentTimeMillis(); - doReps(oout, oin, sbuf, strs, nbatches, ncycles); + doReps(oout, oin, sbuf, strs, 1, ncycles); // warmup + + long start = System.currentTimeMillis(); + doReps(oout, oin, sbuf, strs, nbatches, ncycles); return System.currentTimeMillis() - start; } @@ -66,16 +66,16 @@ public class Strings implements Benchmark { * Generate nstrings random strings, each of length len. */ String[] genStrings(int len, int nstrings) { - String[] strs = new String[nstrings]; - char[] ca = new char[len]; - Random rand = new Random(System.currentTimeMillis()); - for (int i = 0; i < nstrings; i++) { - for (int j = 0; j < len; j++) { - ca[j] = (char) rand.nextInt(); - } - strs[i] = new String(ca); - } - return strs; + String[] strs = new String[nstrings]; + char[] ca = new char[len]; + Random rand = new Random(System.currentTimeMillis()); + for (int i = 0; i < nstrings; i++) { + for (int j = 0; j < len; j++) { + ca[j] = (char) rand.nextInt(); + } + strs[i] = new String(ca); + } + return strs; } /** @@ -83,20 +83,19 @@ public class Strings implements Benchmark { * for each batch. */ void doReps(ObjectOutputStream oout, ObjectInputStream oin, - StreamBuffer sbuf, String[] strs, int nbatches, int ncycles) - throws Exception + StreamBuffer sbuf, String[] strs, int nbatches, int ncycles) + throws Exception { - for (int i = 0; i < nbatches; i++) { - sbuf.reset(); - oout.reset(); - for (int j = 0; j < ncycles; j++) { - oout.writeObject(strs[j]); - } - oout.flush(); - for (int j = 0; j < ncycles; j++) { - oin.readObject(); - } - } + for (int i = 0; i < nbatches; i++) { + sbuf.reset(); + oout.reset(); + for (int j = 0; j < ncycles; j++) { + oout.writeObject(strs[j]); + } + oout.flush(); + for (int j = 0; j < ncycles; j++) { + oin.readObject(); + } + } } } - diff --git a/jdk/test/java/rmi/reliability/juicer/Apple.java b/jdk/test/java/rmi/reliability/juicer/Apple.java index 10c5ba6fc6c..f1b6b640351 100644 --- a/jdk/test/java/rmi/reliability/juicer/Apple.java +++ b/jdk/test/java/rmi/reliability/juicer/Apple.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 2003 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -25,7 +25,7 @@ import java.rmi.Remote; import java.rmi.RemoteException; /** - * A remote factory for Orange instances. This interface also + * A remote factory for Orange instances. This interface also * includes a method to test object array serialization. */ public interface Apple extends Remote { diff --git a/jdk/test/java/rmi/reliability/juicer/AppleEvent.java b/jdk/test/java/rmi/reliability/juicer/AppleEvent.java index b019e29c26f..c76a6fd271e 100644 --- a/jdk/test/java/rmi/reliability/juicer/AppleEvent.java +++ b/jdk/test/java/rmi/reliability/juicer/AppleEvent.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 2003 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -26,7 +26,7 @@ import java.util.Date; /** * The AppleEvent class is simply an object to be passed to a - * remote object exported by an applet. The intent is to verify + * remote object exported by an applet. The intent is to verify * proper object serialization of arrays. */ public class AppleEvent implements Serializable { @@ -39,24 +39,24 @@ public class AppleEvent implements Serializable { private final Date when; public AppleEvent(int what) { - this.what = what; - this.when = new Date(); + this.what = what; + this.when = new Date(); } public String toString() { - String desc = "["; - switch (what) { - case BUY: - desc += "BUY"; - break; - case EAT: - desc += "EAT"; - break; - case THROW: - desc += "THROW"; - break; - } - desc += " @ " + when + "]"; - return desc; + String desc = "["; + switch (what) { + case BUY: + desc += "BUY"; + break; + case EAT: + desc += "EAT"; + break; + case THROW: + desc += "THROW"; + break; + } + desc += " @ " + when + "]"; + return desc; } } diff --git a/jdk/test/java/rmi/reliability/juicer/AppleImpl.java b/jdk/test/java/rmi/reliability/juicer/AppleImpl.java index f8027f063eb..f1f1c3ee94f 100644 --- a/jdk/test/java/rmi/reliability/juicer/AppleImpl.java +++ b/jdk/test/java/rmi/reliability/juicer/AppleImpl.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 2003 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -34,46 +34,46 @@ public class AppleImpl extends UnicastRemoteObject implements Apple { private static final Logger logger = Logger.getLogger("reliability.apple"); private final String name; - + public AppleImpl(String name) throws RemoteException { - this.name = name; + this.name = name; } /** * Receive an array of AppleEvent objects. */ public void notify(AppleEvent[] events) { - String threadName = Thread.currentThread().getName(); - logger.log(Level.FINEST, - threadName + ": " + toString() + ".notify: BEGIN"); + String threadName = Thread.currentThread().getName(); + logger.log(Level.FINEST, + threadName + ": " + toString() + ".notify: BEGIN"); - for (int i = 0; i < events.length; i++) { - logger.log(Level.FINEST, - threadName + ": " + toString() + ".notify(): events[" - + i + "] = " + events[i].toString()); - } + for (int i = 0; i < events.length; i++) { + logger.log(Level.FINEST, + threadName + ": " + toString() + ".notify(): events[" + + i + "] = " + events[i].toString()); + } - logger.log(Level.FINEST, - threadName + ": " + toString() + ".notify(): END"); + logger.log(Level.FINEST, + threadName + ": " + toString() + ".notify(): END"); } /** * Return a newly created and exported orange implementation. */ public Orange newOrange(String name) throws RemoteException { - String threadName = Thread.currentThread().getName(); - logger.log(Level.FINEST, - threadName + ": " + toString() + ".newOrange(" + name + "): BEGIN"); + String threadName = Thread.currentThread().getName(); + logger.log(Level.FINEST, + threadName + ": " + toString() + ".newOrange(" + name + "): BEGIN"); - Orange orange = new OrangeImpl(name); - - logger.log(Level.FINEST, - threadName + ": " + toString() + ".newOrange(" + name + "): END"); + Orange orange = new OrangeImpl(name); - return orange; + logger.log(Level.FINEST, + threadName + ": " + toString() + ".newOrange(" + name + "): END"); + + return orange; } public String toString() { - return name; + return name; } } diff --git a/jdk/test/java/rmi/reliability/juicer/AppleUser.java b/jdk/test/java/rmi/reliability/juicer/AppleUser.java index c7eb48d46b9..be86b053b12 100644 --- a/jdk/test/java/rmi/reliability/juicer/AppleUser.java +++ b/jdk/test/java/rmi/reliability/juicer/AppleUser.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 2003 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * diff --git a/jdk/test/java/rmi/reliability/juicer/AppleUserImpl.java b/jdk/test/java/rmi/reliability/juicer/AppleUserImpl.java index 475aca228e3..d2f8b681f5b 100644 --- a/jdk/test/java/rmi/reliability/juicer/AppleUserImpl.java +++ b/jdk/test/java/rmi/reliability/juicer/AppleUserImpl.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 2003-2005 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -27,30 +27,30 @@ * a large number of concurrent, long running, remote method invocations * between many threads which have exported remote objects. These * threads use remote objects that carry on deep "two party" - * recursion. The juicer relies on Distributed Garbage Collection to - * unexport these remote objects when no more references are held to them. + * recursion. The juicer relies on Distributed Garbage Collection to + * unexport these remote objects when no more references are held to them. * The two parties in the recursion are OrangeImpl and * OrangeEchoImpl. OrangeImpl checks the base case of the recursion * so that the program will exit. * * When the AppleUserImpl.main() method is invoked, the class binds an * instance of itself in a registry. A second server process, - * an ApplicationServer, is started which looks up the recently + * an ApplicationServer, is started which looks up the recently * bound AppleUser object. This server is either started up in * the same VM or can optionally be started in a separate VM on the - * same host or on a different host. When this test is run on the - * RMI profile, ApplicationServer must be started by AppleUserImpl + * same host or on a different host. When this test is run on the + * RMI profile, ApplicationServer must be started by AppleUserImpl * and the complete juicer runs in a single process. * * The second server process instructs the AppleUserImpl to "use" some apples. * AppleUserImpl creates a new thread for each apple. These threads * initiate the two party recursion. - * + * * Each recursive call nests to a depth determined by this - * expression: (2 + Math.abs(random.nextInt() % (maxLevel + 1)), + * expression: (2 + Math.abs(random.nextInt() % (maxLevel + 1)), * where maxLevel is a command line parameter. Thus each recursive * call nests a random number of levels between 2 and maxLevel. - * + * * The test ends when an exception is encountered or the stop time * has been reached. * @@ -81,8 +81,8 @@ import java.util.logging.Level; */ public class AppleUserImpl extends UnicastRemoteObject implements AppleUser { - private static final Logger logger = - Logger.getLogger("reliability.appleuser"); + private static final Logger logger = + Logger.getLogger("reliability.appleuser"); private static int threadNum = 0; private static long testDuration = 0; private static int maxLevel = 7; @@ -91,7 +91,7 @@ public class AppleUserImpl extends UnicastRemoteObject implements AppleUser { private static boolean startTestNotified = false; private static final Random random = new Random(); private static final Object lock = new Object(); - + public AppleUserImpl() throws RemoteException { } @@ -100,7 +100,7 @@ public class AppleUserImpl extends UnicastRemoteObject implements AppleUser { * to start "juicing". */ public synchronized void startTest() throws RemoteException { - startTestNotified = true; + startTestNotified = true; this.notifyAll(); } @@ -109,9 +109,9 @@ public class AppleUserImpl extends UnicastRemoteObject implements AppleUser { * process and thereby terminate the test. */ public void reportException(Exception status) throws RemoteException { - synchronized (lock) { - this.status = status; - lock.notifyAll(); + synchronized (lock) { + this.status = status; + lock.notifyAll(); } } @@ -120,136 +120,136 @@ public class AppleUserImpl extends UnicastRemoteObject implements AppleUser { * stress it out. */ public synchronized void useApple(Apple apple) throws RemoteException { - String threadName = Thread.currentThread().getName(); - logger.log(Level.FINEST, - threadName + ": AppleUserImpl.useApple(): BEGIN"); + String threadName = Thread.currentThread().getName(); + logger.log(Level.FINEST, + threadName + ": AppleUserImpl.useApple(): BEGIN"); - AppleUserThread t = - new AppleUserThread("AppleUserThread-" + (++threadNum), apple); - t.start(); + AppleUserThread t = + new AppleUserThread("AppleUserThread-" + (++threadNum), apple); + t.start(); - logger.log(Level.FINEST, - threadName + ": AppleUserImpl.useApple(): END"); + logger.log(Level.FINEST, + threadName + ": AppleUserImpl.useApple(): END"); } - + /** * The AppleUserThread class repeatedly invokes calls on its associated * Apple object to stress the RMI system. */ class AppleUserThread extends Thread { - final Apple apple; + final Apple apple; - public AppleUserThread(String name, Apple apple) { - super(name); - this.apple = apple; - } + public AppleUserThread(String name, Apple apple) { + super(name); + this.apple = apple; + } - public void run() { - int orangeNum = 0; + public void run() { + int orangeNum = 0; long stopTime = System.currentTimeMillis() + testDuration; Logger logger = Logger.getLogger("reliability.appleuserthread"); - - try { - do { // loop until stopTime is reached - /* - * Notify apple with some apple events. This tests + try { + do { // loop until stopTime is reached + + /* + * Notify apple with some apple events. This tests * serialization of arrays. - */ - int numEvents = Math.abs(random.nextInt() % 5); - AppleEvent[] events = new AppleEvent[numEvents]; - for (int i = 0; i < events.length; i++) { - events[i] = new AppleEvent(orangeNum % 3); - } - apple.notify(events); + */ + int numEvents = Math.abs(random.nextInt() % 5); + AppleEvent[] events = new AppleEvent[numEvents]; + for (int i = 0; i < events.length; i++) { + events[i] = new AppleEvent(orangeNum % 3); + } + apple.notify(events); - /* - * Request a new orange object be created in + /* + * Request a new orange object be created in * the application server. - */ - Orange orange = apple.newOrange( - "Orange(" + getName() + ")-" + (++orangeNum)); + */ + Orange orange = apple.newOrange( + "Orange(" + getName() + ")-" + (++orangeNum)); - /* - * Create a large message of random ints to pass to orange. - */ + /* + * Create a large message of random ints to pass to orange. + */ int msgLength = 1000 + Math.abs(random.nextInt() % 3000); - int[] message = new int[msgLength]; - for (int i = 0; i < message.length; i++) { - message[i] = random.nextInt(); - } + int[] message = new int[msgLength]; + for (int i = 0; i < message.length; i++) { + message[i] = random.nextInt(); + } - /* - * Invoke recursive call on the orange. Base case + /* + * Invoke recursive call on the orange. Base case * of recursion inverts messgage. - */ - OrangeEchoImpl echo = new OrangeEchoImpl( - "OrangeEcho(" + getName() + ")-" + orangeNum); - int[] response = orange.recurse(echo, message, - 2 + Math.abs(random.nextInt() % (maxLevel + 1))); + */ + OrangeEchoImpl echo = new OrangeEchoImpl( + "OrangeEcho(" + getName() + ")-" + orangeNum); + int[] response = orange.recurse(echo, message, + 2 + Math.abs(random.nextInt() % (maxLevel + 1))); - /* - * Verify message was properly inverted and not corrupted - * through all the recursive method invocations. - */ - if (response.length != message.length) { - throw new RuntimeException( - "ERROR: CORRUPTED RESPONSE: " + - "wrong length of returned array " + "(should be " + - message.length + ", is " + response.length + ")"); - } - for (int i = 0; i < message.length; i++) { - if (~message[i] != response[i]) { - throw new RuntimeException( - "ERROR: CORRUPTED RESPONSE: " + - "at element " + i + "/" + message.length + - " of returned array (should be " + - Integer.toHexString(~message[i]) + ", is " + - Integer.toHexString(response[i]) + ")"); - } - } + /* + * Verify message was properly inverted and not corrupted + * through all the recursive method invocations. + */ + if (response.length != message.length) { + throw new RuntimeException( + "ERROR: CORRUPTED RESPONSE: " + + "wrong length of returned array " + "(should be " + + message.length + ", is " + response.length + ")"); + } + for (int i = 0; i < message.length; i++) { + if (~message[i] != response[i]) { + throw new RuntimeException( + "ERROR: CORRUPTED RESPONSE: " + + "at element " + i + "/" + message.length + + " of returned array (should be " + + Integer.toHexString(~message[i]) + ", is " + + Integer.toHexString(response[i]) + ")"); + } + } - try { - Thread.sleep(Math.abs(random.nextInt() % 10) * 1000); - } catch (InterruptedException e) { - } + try { + Thread.sleep(Math.abs(random.nextInt() % 10) * 1000); + } catch (InterruptedException e) { + } - } while (System.currentTimeMillis() < stopTime); + } while (System.currentTimeMillis() < stopTime); - } catch (Exception e) { - status = e; - } - finished = true; - synchronized (lock) { - lock.notifyAll(); - } - } + } catch (Exception e) { + status = e; + } + finished = true; + synchronized (lock) { + lock.notifyAll(); + } + } } private static void usage() { - System.err.println("Usage: AppleUserImpl [-hours | " + - "-seconds ]"); - System.err.println(" [-maxLevel ]"); - System.err.println(" [-othervm]"); - System.err.println(" [-exit]"); - System.err.println(" hours The number of hours to run the juicer."); - System.err.println(" The default is 0 hours."); - System.err.println(" seconds The number of seconds to run the juicer."); - System.err.println(" The default is 0 seconds."); - System.err.println(" maxLevel The maximum number of levels to "); - System.err.println(" recurse on each call."); - System.err.println(" The default is 7 levels."); - System.err.println(" othervm If present, the VM will wait for the"); - System.err.println(" ApplicationServer to start in"); - System.err.println(" another process."); - System.err.println(" The default is to run everything in"); - System.err.println(" a single VM."); - System.err.println(" exit If present, the VM will call"); - System.err.println(" System.exit() when main() finishes."); - System.err.println(" The default is to not call"); - System.err.println(" System.exit()."); - System.err.println(); + System.err.println("Usage: AppleUserImpl [-hours | " + + "-seconds ]"); + System.err.println(" [-maxLevel ]"); + System.err.println(" [-othervm]"); + System.err.println(" [-exit]"); + System.err.println(" hours The number of hours to run the juicer."); + System.err.println(" The default is 0 hours."); + System.err.println(" seconds The number of seconds to run the juicer."); + System.err.println(" The default is 0 seconds."); + System.err.println(" maxLevel The maximum number of levels to "); + System.err.println(" recurse on each call."); + System.err.println(" The default is 7 levels."); + System.err.println(" othervm If present, the VM will wait for the"); + System.err.println(" ApplicationServer to start in"); + System.err.println(" another process."); + System.err.println(" The default is to run everything in"); + System.err.println(" a single VM."); + System.err.println(" exit If present, the VM will call"); + System.err.println(" System.exit() when main() finishes."); + System.err.println(" The default is to not call"); + System.err.println(" System.exit()."); + System.err.println(); } /** @@ -257,122 +257,122 @@ public class AppleUserImpl extends UnicastRemoteObject implements AppleUser { * an apple user implementation in an rmiregistry running on localhost. */ public static void main(String[] args) { - String durationString = null; + String durationString = null; boolean othervm = false; boolean exit = false; - try { - // parse command line args - for (int i = 0; i < args.length ; i++ ) { + try { + // parse command line args + for (int i = 0; i < args.length ; i++ ) { String arg = args[i]; if (arg.equals("-hours")) { - if (durationString != null) { - usage(); - } - i++; - int hours = Integer.parseInt(args[i]); - durationString = hours + " hours"; - testDuration = hours * 60 * 60 * 1000; + if (durationString != null) { + usage(); + } + i++; + int hours = Integer.parseInt(args[i]); + durationString = hours + " hours"; + testDuration = hours * 60 * 60 * 1000; } else if (arg.equals("-seconds")) { - if (durationString != null) { - usage(); - } - i++; - long seconds = Long.parseLong(args[i]); - durationString = seconds + " seconds"; - testDuration = seconds * 1000; + if (durationString != null) { + usage(); + } + i++; + long seconds = Long.parseLong(args[i]); + durationString = seconds + " seconds"; + testDuration = seconds * 1000; } else if (arg.equals("-maxLevel")) { - i++; - maxLevel = Integer.parseInt(args[i]); + i++; + maxLevel = Integer.parseInt(args[i]); } else if (arg.equals("-othervm")) { - othervm = true; + othervm = true; } else if (arg.equals("-exit")) { - exit = true; + exit = true; } else { - usage(); + usage(); } } if (durationString == null) { durationString = testDuration + " milliseconds"; } - } catch (Throwable t) { - usage(); - throw new RuntimeException("TEST FAILED: Bad argument"); - } + } catch (Throwable t) { + usage(); + throw new RuntimeException("TEST FAILED: Bad argument"); + } - AppleUserImpl user = null; - long startTime = 0; - Thread server = null; - int exitValue = 0; - try { - user = new AppleUserImpl(); + AppleUserImpl user = null; + long startTime = 0; + Thread server = null; + int exitValue = 0; + try { + user = new AppleUserImpl(); - synchronized (user) { - // create new registry and bind new AppleUserImpl in registry + synchronized (user) { + // create new registry and bind new AppleUserImpl in registry LocateRegistry.createRegistry(2006); LocateRegistry.getRegistry(2006).rebind("AppleUser",user); - - // start the other server if applicable - if (othervm) { - // the other server must be running in a separate process - logger.log(Level.INFO, "Application server must be " + - "started in separate process"); - } else { - Class app = Class.forName("ApplicationServer"); - server = new Thread((Runnable) app.newInstance()); - logger.log(Level.INFO, "Starting application server " + + + // start the other server if applicable + if (othervm) { + // the other server must be running in a separate process + logger.log(Level.INFO, "Application server must be " + + "started in separate process"); + } else { + Class app = Class.forName("ApplicationServer"); + server = new Thread((Runnable) app.newInstance()); + logger.log(Level.INFO, "Starting application server " + "in same process"); - server.start(); - } + server.start(); + } - // wait for other server to call startTest method - logger.log(Level.INFO, "Waiting for application server " + + // wait for other server to call startTest method + logger.log(Level.INFO, "Waiting for application server " + "process to start"); - while (!startTestNotified) { - user.wait(); - } - } - - startTime = System.currentTimeMillis(); - logger.log(Level.INFO, "Test starting"); - - // wait for exception to be reported or first thread to complete - logger.log(Level.INFO, "Waiting " + durationString + " for " + - "test to complete or exception to be thrown"); - - synchronized (lock) { - while (status == null && !finished) { - lock.wait(); - } - } - - if (status != null) { - throw new RuntimeException("TEST FAILED: " - + "juicer server reported an exception", status); - } else { - logger.log(Level.INFO, "TEST PASSED"); + while (!startTestNotified) { + user.wait(); + } } - } catch (Exception e) { - logger.log(Level.INFO, "TEST FAILED"); - exitValue = 1; - if (exit) { - e.printStackTrace(); - } - throw new RuntimeException("TEST FAILED: " - + "unexpected exception", e); - } finally { - long actualDuration = System.currentTimeMillis() - startTime; - logger.log(Level.INFO, "Test finished"); - try { - UnicastRemoteObject.unexportObject(user, true); + + startTime = System.currentTimeMillis(); + logger.log(Level.INFO, "Test starting"); + + // wait for exception to be reported or first thread to complete + logger.log(Level.INFO, "Waiting " + durationString + " for " + + "test to complete or exception to be thrown"); + + synchronized (lock) { + while (status == null && !finished) { + lock.wait(); + } + } + + if (status != null) { + throw new RuntimeException("TEST FAILED: " + + "juicer server reported an exception", status); + } else { + logger.log(Level.INFO, "TEST PASSED"); + } + } catch (Exception e) { + logger.log(Level.INFO, "TEST FAILED"); + exitValue = 1; + if (exit) { + e.printStackTrace(); + } + throw new RuntimeException("TEST FAILED: " + + "unexpected exception", e); + } finally { + long actualDuration = System.currentTimeMillis() - startTime; + logger.log(Level.INFO, "Test finished"); + try { + UnicastRemoteObject.unexportObject(user, true); } catch (NoSuchObjectException ignore) { - } - logger.log(Level.INFO, "Test duration was " + - (actualDuration/1000) + " seconds " + - "(" + (actualDuration/3600000) + " hours)"); - System.gc(); System.gc(); - if (exit) { - System.exit(exitValue); - } + } + logger.log(Level.INFO, "Test duration was " + + (actualDuration/1000) + " seconds " + + "(" + (actualDuration/3600000) + " hours)"); + System.gc(); System.gc(); + if (exit) { + System.exit(exitValue); + } } } } diff --git a/jdk/test/java/rmi/reliability/juicer/ApplicationServer.java b/jdk/test/java/rmi/reliability/juicer/ApplicationServer.java index 050da0e3b7b..e17528af81b 100644 --- a/jdk/test/java/rmi/reliability/juicer/ApplicationServer.java +++ b/jdk/test/java/rmi/reliability/juicer/ApplicationServer.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 2003 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -32,7 +32,7 @@ import java.util.logging.Level; * stress test of RMI. */ public class ApplicationServer implements Runnable { - + /** number of remote Apple objects to export */ private static final Logger logger = Logger.getLogger("reliability.orange"); private static final int LOOKUP_ATTEMPTS = 5; @@ -58,102 +58,102 @@ public class ApplicationServer implements Runnable { * them with server. */ public void run() { - try { - int i = 0; + try { + int i = 0; - /* - * Locate apple user object in registry. The lookup will - * occur until it is successful or fails LOOKUP_ATTEMPTS times. - * These repeated attempts allow the ApplicationServer - * to be started before the AppleUserImpl. - */ - Exception exc = null; - for (i = 0; i < LOOKUP_ATTEMPTS; i++) { - try { - Registry registry = LocateRegistry.getRegistry( - registryHost, 2006); - user = (AppleUser) registry.lookup("AppleUser"); - user.startTest(); - break; //successfully obtained AppleUser - } catch (Exception e) { - exc = e; - Thread.sleep(10000); //sleep 10 seconds and try again - } - } - if (user == null) { - logger.log(Level.SEVERE, "Failed to lookup AppleUser:", exc); - return; - } - - /* - * Create and export apple implementations. - */ - try { - for (i = 0; i < numApples; i++) { - apples[i] = new AppleImpl("AppleImpl #" + (i + 1)); - } - } catch (RemoteException e) { - logger.log(Level.SEVERE, - "Failed to create AppleImpl #" + (i + 1) + ":", e); - user.reportException(e); - return; - } - - /* - * Hand apple objects to apple user. - */ - try { - for (i = 0; i < numApples; i++) { - user.useApple(apples[i]); + /* + * Locate apple user object in registry. The lookup will + * occur until it is successful or fails LOOKUP_ATTEMPTS times. + * These repeated attempts allow the ApplicationServer + * to be started before the AppleUserImpl. + */ + Exception exc = null; + for (i = 0; i < LOOKUP_ATTEMPTS; i++) { + try { + Registry registry = LocateRegistry.getRegistry( + registryHost, 2006); + user = (AppleUser) registry.lookup("AppleUser"); + user.startTest(); + break; //successfully obtained AppleUser + } catch (Exception e) { + exc = e; + Thread.sleep(10000); //sleep 10 seconds and try again } - } catch (RemoteException e) { - logger.log(Level.SEVERE, - "Failed to register callbacks for " + apples[i] + ":", e); - user.reportException(e); - return; - } - } catch (Exception e) { - logger.log(Level.SEVERE, "Unexpected exception:", e); - } + } + if (user == null) { + logger.log(Level.SEVERE, "Failed to lookup AppleUser:", exc); + return; + } + + /* + * Create and export apple implementations. + */ + try { + for (i = 0; i < numApples; i++) { + apples[i] = new AppleImpl("AppleImpl #" + (i + 1)); + } + } catch (RemoteException e) { + logger.log(Level.SEVERE, + "Failed to create AppleImpl #" + (i + 1) + ":", e); + user.reportException(e); + return; + } + + /* + * Hand apple objects to apple user. + */ + try { + for (i = 0; i < numApples; i++) { + user.useApple(apples[i]); + } + } catch (RemoteException e) { + logger.log(Level.SEVERE, + "Failed to register callbacks for " + apples[i] + ":", e); + user.reportException(e); + return; + } + } catch (Exception e) { + logger.log(Level.SEVERE, "Unexpected exception:", e); + } } private static void usage() { - System.err.println("Usage: ApplicationServer [-numApples ]"); - System.err.println(" [-registryHost ]"); - System.err.println(" numApples The number of apples (threads) to use."); - System.err.println(" The default is 10 apples."); - System.err.println(" host The host running rmiregistry " + - "which contains AppleUser."); - System.err.println(" The default is \"localhost\"."); - System.err.println(); + System.err.println("Usage: ApplicationServer [-numApples ]"); + System.err.println(" [-registryHost ]"); + System.err.println(" numApples The number of apples (threads) to use."); + System.err.println(" The default is 10 apples."); + System.err.println(" host The host running rmiregistry " + + "which contains AppleUser."); + System.err.println(" The default is \"localhost\"."); + System.err.println(); } public static void main(String[] args) { int num = DEFAULT_NUMAPPLES; String host = DEFAULT_REGISTRYHOST; - // parse command line args - try { + // parse command line args + try { for (int i = 0; i < args.length ; i++ ) { - String arg = args[i]; - if (arg.equals("-numApples")) { + String arg = args[i]; + if (arg.equals("-numApples")) { i++; num = Integer.parseInt(args[i]); - } else if (arg.equals("-registryHost")) { + } else if (arg.equals("-registryHost")) { i++; host = args[i]; - } else { + } else { usage(); - } + } } - } catch (Throwable t) { + } catch (Throwable t) { usage(); - throw new RuntimeException("TEST FAILED: Bad argument"); - } + throw new RuntimeException("TEST FAILED: Bad argument"); + } - // start the client server - Thread server = new Thread(new ApplicationServer(num,host)); - server.start(); - // main should exit once all exported remote objects are gc'd + // start the client server + Thread server = new Thread(new ApplicationServer(num,host)); + server.start(); + // main should exit once all exported remote objects are gc'd } } diff --git a/jdk/test/java/rmi/reliability/juicer/Orange.java b/jdk/test/java/rmi/reliability/juicer/Orange.java index 6020eae3681..40e670a7ee5 100644 --- a/jdk/test/java/rmi/reliability/juicer/Orange.java +++ b/jdk/test/java/rmi/reliability/juicer/Orange.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 2003 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -26,11 +26,11 @@ import java.rmi.RemoteException; /** * Represents one remote party of the deep 2-party recursion implemented by - * this RMI reliability test. An Orange instance recursively calls back + * this RMI reliability test. An Orange instance recursively calls back * to it's caller, typically an OrangeEcho instance. * The recursion stops when it reaches a given 'level'. */ public interface Orange extends Remote { - int[] recurse(OrangeEcho echo, int[] message, int level) - throws RemoteException; + int[] recurse(OrangeEcho echo, int[] message, int level) + throws RemoteException; } diff --git a/jdk/test/java/rmi/reliability/juicer/OrangeEcho.java b/jdk/test/java/rmi/reliability/juicer/OrangeEcho.java index 77e5d2f103f..8077afad8bf 100644 --- a/jdk/test/java/rmi/reliability/juicer/OrangeEcho.java +++ b/jdk/test/java/rmi/reliability/juicer/OrangeEcho.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 2003 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -26,11 +26,11 @@ import java.rmi.RemoteException; /** * Represents one remote party of the deep 2-party recursion implemented by - * this RMI reliability test. An OrangeEcho instance recursively calls back + * this RMI reliability test. An OrangeEcho instance recursively calls back * to it's caller, an Orange instance. * The recursion stops when it reaches a given 'level'. */ public interface OrangeEcho extends Remote { int[] recurse(Orange orange, int[] message, int level) - throws RemoteException; + throws RemoteException; } diff --git a/jdk/test/java/rmi/reliability/juicer/OrangeEchoImpl.java b/jdk/test/java/rmi/reliability/juicer/OrangeEchoImpl.java index 494bf1914fa..5472138bd31 100644 --- a/jdk/test/java/rmi/reliability/juicer/OrangeEchoImpl.java +++ b/jdk/test/java/rmi/reliability/juicer/OrangeEchoImpl.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 2003 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -33,12 +33,12 @@ import java.util.logging.Level; */ public class OrangeEchoImpl extends UnicastRemoteObject implements OrangeEcho { - private static final Logger logger = - Logger.getLogger("reliability.orangeecho"); + private static final Logger logger = + Logger.getLogger("reliability.orangeecho"); private final String name; public OrangeEchoImpl(String name) throws RemoteException { - this.name = name; + this.name = name; } /** @@ -46,24 +46,24 @@ public class OrangeEchoImpl extends UnicastRemoteObject implements OrangeEcho { * with the same message data and a decremented recursion level. */ public int[] recurse(Orange orange, int[] message, int level) - throws RemoteException + throws RemoteException { - String threadName = Thread.currentThread().getName(); + String threadName = Thread.currentThread().getName(); - logger.log(Level.FINEST, - threadName + ": " + toString() + ".recurse(message[" - + message.length + "], " + level + "): BEGIN"); + logger.log(Level.FINEST, + threadName + ": " + toString() + ".recurse(message[" + + message.length + "], " + level + "): BEGIN"); - int[] response = orange.recurse(this, message, level - 1); + int[] response = orange.recurse(this, message, level - 1); - logger.log(Level.FINEST, - threadName + ": " + toString() + ".recurse(message[" - + message.length + "], " + level + "): END"); + logger.log(Level.FINEST, + threadName + ": " + toString() + ".recurse(message[" + + message.length + "], " + level + "): END"); - return response; + return response; } public String toString() { - return name; + return name; } } diff --git a/jdk/test/java/rmi/reliability/juicer/OrangeImpl.java b/jdk/test/java/rmi/reliability/juicer/OrangeImpl.java index 876617e1acb..9643ca52fea 100644 --- a/jdk/test/java/rmi/reliability/juicer/OrangeImpl.java +++ b/jdk/test/java/rmi/reliability/juicer/OrangeImpl.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 2003 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -36,7 +36,7 @@ public class OrangeImpl extends UnicastRemoteObject implements Orange { private final String name; public OrangeImpl(String name) throws RemoteException { - this.name = name; + this.name = name; } /** @@ -44,31 +44,31 @@ public class OrangeImpl extends UnicastRemoteObject implements Orange { * object if not at recursion level zero. */ public int[] recurse(OrangeEcho echo, int[] message, int level) - throws RemoteException + throws RemoteException { - String threadName = Thread.currentThread().getName(); - logger.log(Level.FINEST, - threadName + ": " + toString() + ".recurse(message[" - + message.length + "], " + level + "): BEGIN"); + String threadName = Thread.currentThread().getName(); + logger.log(Level.FINEST, + threadName + ": " + toString() + ".recurse(message[" + + message.length + "], " + level + "): BEGIN"); - int[] response; - if (level > 0) { - response = echo.recurse(this, message, level); - } else { - for (int i = 0; i < message.length; i++) { - message[i] = ~message[i]; - } - response = message; - } + int[] response; + if (level > 0) { + response = echo.recurse(this, message, level); + } else { + for (int i = 0; i < message.length; i++) { + message[i] = ~message[i]; + } + response = message; + } - logger.log(Level.FINEST, - threadName + ": " + toString() + ".recurse(message[" - + message.length + "], " + level + "): END"); + logger.log(Level.FINEST, + threadName + ": " + toString() + ".recurse(message[" + + message.length + "], " + level + "): END"); - return response; + return response; } public String toString() { - return name; + return name; } } diff --git a/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/activatable/CompressConstants.java b/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/activatable/CompressConstants.java index 7db4a6b9c8a..cc7526077d8 100644 --- a/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/activatable/CompressConstants.java +++ b/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/activatable/CompressConstants.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -27,9 +27,9 @@ interface CompressConstants { // constants for 6-bit code values - static final int NOP = 0; // no operation: used to pad words on flush() - static final int RAW = 1; // introduces raw byte format - static final int BASE = 2; // base for codes found in lookup table + static final int NOP = 0; // no operation: used to pad words on flush() + static final int RAW = 1; // introduces raw byte format + static final int BASE = 2; // base for codes found in lookup table static final String codeTable = - "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ,.!?\"'()"; + "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ,.!?\"'()"; } diff --git a/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/activatable/CompressInputStream.java b/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/activatable/CompressInputStream.java index 3a42bb18073..31577a1c2ad 100644 --- a/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/activatable/CompressInputStream.java +++ b/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/activatable/CompressInputStream.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -31,7 +31,7 @@ class CompressInputStream extends FilterInputStream { public CompressInputStream(InputStream in) { - super(in); + super(in); } // buffer of unpacked 6-bit codes from last 32-word read @@ -41,70 +41,70 @@ class CompressInputStream extends FilterInputStream int bufPos = 5; public int read() throws IOException { - try { - int code; - do { - code = readCode(); - } while (code == NOP); // ignore NOP codes + try { + int code; + do { + code = readCode(); + } while (code == NOP); // ignore NOP codes - if (code >= BASE) - return codeTable.charAt(code - BASE); - else if (code == RAW) { - int high = readCode(); - int low = readCode(); - return (high << 4) | low; - } else - throw new IOException("unknown compression code: " + code); - } catch (EOFException e) { - return -1; - } + if (code >= BASE) + return codeTable.charAt(code - BASE); + else if (code == RAW) { + int high = readCode(); + int low = readCode(); + return (high << 4) | low; + } else + throw new IOException("unknown compression code: " + code); + } catch (EOFException e) { + return -1; + } } public int read(byte b[], int off, int len) throws IOException { - if (len <= 0) { - return 0; - } + if (len <= 0) { + return 0; + } - int c = read(); - if (c == -1) { - return -1; - } - b[off] = (byte)c; + int c = read(); + if (c == -1) { + return -1; + } + b[off] = (byte)c; - int i = 1; + int i = 1; /***** - try { - for (; i < len ; i++) { - c = read(); - if (c == -1) { - break; - } - if (b != null) { - b[off + i] = (byte)c; - } - } - } catch (IOException ee) { - } + try { + for (; i < len ; i++) { + c = read(); + if (c == -1) { + break; + } + if (b != null) { + b[off + i] = (byte)c; + } + } + } catch (IOException ee) { + } *****/ - return i; + return i; } private int readCode() throws IOException { - if (bufPos == 5) { - int b1 = in.read(); - int b2 = in.read(); - int b3 = in.read(); - int b4 = in.read(); - if ((b1 | b2 | b3 | b4) < 0) - throw new EOFException(); - int pack = (b1 << 24) | (b2 << 16) | (b3 << 8) | b4; - buf[0] = (pack >>> 24) & 0x3F; - buf[1] = (pack >>> 18) & 0x3F; - buf[2] = (pack >>> 12) & 0x3F; - buf[3] = (pack >>> 6) & 0x3F; - buf[4] = (pack >>> 0) & 0x3F; - bufPos = 0; - } - return buf[bufPos++]; + if (bufPos == 5) { + int b1 = in.read(); + int b2 = in.read(); + int b3 = in.read(); + int b4 = in.read(); + if ((b1 | b2 | b3 | b4) < 0) + throw new EOFException(); + int pack = (b1 << 24) | (b2 << 16) | (b3 << 8) | b4; + buf[0] = (pack >>> 24) & 0x3F; + buf[1] = (pack >>> 18) & 0x3F; + buf[2] = (pack >>> 12) & 0x3F; + buf[3] = (pack >>> 6) & 0x3F; + buf[4] = (pack >>> 0) & 0x3F; + bufPos = 0; + } + return buf[bufPos++]; } } diff --git a/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/activatable/CompressOutputStream.java b/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/activatable/CompressOutputStream.java index ca1a5963f95..5d38e147b18 100644 --- a/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/activatable/CompressOutputStream.java +++ b/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/activatable/CompressOutputStream.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -31,7 +31,7 @@ class CompressOutputStream extends FilterOutputStream { public CompressOutputStream(OutputStream out) { - super(out); + super(out); } // buffer of 6-bit codes to pack into next 32-bit word @@ -41,44 +41,44 @@ class CompressOutputStream extends FilterOutputStream int bufPos = 0; public void write(int b) throws IOException { - b &= 0xFF; // force argument to a byte + b &= 0xFF; // force argument to a byte - int pos = codeTable.indexOf((char)b); - if (pos != -1) - writeCode(BASE + pos); - else { - writeCode(RAW); - writeCode(b >> 4); - writeCode(b & 0xF); - } + int pos = codeTable.indexOf((char)b); + if (pos != -1) + writeCode(BASE + pos); + else { + writeCode(RAW); + writeCode(b >> 4); + writeCode(b & 0xF); + } } public void write(byte b[], int off, int len) throws IOException { - /* - * This is quite an inefficient implementation, because it has to - * call the other write method for every byte in the array. It + /* + * This is quite an inefficient implementation, because it has to + * call the other write method for every byte in the array. It * could be optimized for performance by doing all the processing - * in this method. - */ - for (int i = 0; i < len; i++) - write(b[off + i]); + * in this method. + */ + for (int i = 0; i < len; i++) + write(b[off + i]); } public void flush() throws IOException { - while (bufPos > 0) - writeCode(NOP); + while (bufPos > 0) + writeCode(NOP); } private void writeCode(int c) throws IOException { - buf[bufPos++] = c; - if (bufPos == 5) { // write next word when we have 5 codes - int pack = (buf[0] << 24) | (buf[1] << 18) | (buf[2] << 12) | - (buf[3] << 6) | buf[4]; - out.write((pack >>> 24) & 0xFF); - out.write((pack >>> 16) & 0xFF); - out.write((pack >>> 8) & 0xFF); - out.write((pack >>> 0) & 0xFF); - bufPos = 0; - } + buf[bufPos++] = c; + if (bufPos == 5) { // write next word when we have 5 codes + int pack = (buf[0] << 24) | (buf[1] << 18) | (buf[2] << 12) | + (buf[3] << 6) | buf[4]; + out.write((pack >>> 24) & 0xFF); + out.write((pack >>> 16) & 0xFF); + out.write((pack >>> 8) & 0xFF); + out.write((pack >>> 0) & 0xFF); + bufPos = 0; + } } } diff --git a/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/activatable/Echo.java b/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/activatable/Echo.java index b313a906dc2..074781b2559 100644 --- a/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/activatable/Echo.java +++ b/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/activatable/Echo.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * diff --git a/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/activatable/EchoImpl.java b/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/activatable/EchoImpl.java index ee01472f7eb..7b334fe0375 100644 --- a/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/activatable/EchoImpl.java +++ b/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/activatable/EchoImpl.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -39,49 +39,49 @@ public class EchoImpl * Initialization constructor. */ public EchoImpl(String protocol) - throws ActivationException, RemoteException + throws ActivationException, RemoteException { - super(null, makeMarshalledObject(protocol), false, 0, - new MultiSocketFactory.ClientFactory(protocol, pattern), - new MultiSocketFactory.ServerFactory(protocol, pattern)); + super(null, makeMarshalledObject(protocol), false, 0, + new MultiSocketFactory.ClientFactory(protocol, pattern), + new MultiSocketFactory.ServerFactory(protocol, pattern)); } /** * Activation constructor. */ public EchoImpl(ActivationID id, MarshalledObject obj) - throws RemoteException + throws RemoteException { - super(id, 0, - new MultiSocketFactory.ClientFactory(getProtocol(obj), pattern), - new MultiSocketFactory.ServerFactory(getProtocol(obj), pattern)); + super(id, 0, + new MultiSocketFactory.ClientFactory(getProtocol(obj), pattern), + new MultiSocketFactory.ServerFactory(getProtocol(obj), pattern)); } private static MarshalledObject makeMarshalledObject(String protocol) { - MarshalledObject obj = null; - try { - obj = new MarshalledObject(protocol); - } catch (Exception willNotHappen) { - } + MarshalledObject obj = null; + try { + obj = new MarshalledObject(protocol); + } catch (Exception willNotHappen) { + } - return obj; + return obj; } private static String getProtocol(MarshalledObject obj) { - String protocol = ""; - try { - protocol = (String) obj.get(); - } catch (Exception willNotHappen) { - } + String protocol = ""; + try { + protocol = (String) obj.get(); + } catch (Exception willNotHappen) { + } - return protocol; + return protocol; } - + public byte[] echoNot(byte[] data) { - byte[] result = new byte[data.length]; - for (int i = 0; i < data.length; i++) - result[i] = (byte) ~data[i]; - return result; + byte[] result = new byte[data.length]; + for (int i = 0; i < data.length; i++) + result[i] = (byte) ~data[i]; + return result; } /** @@ -89,7 +89,7 @@ public class EchoImpl */ public void shutdown() throws Exception { - (new Thread(this,"Echo.shutdown")).start(); + (new Thread(this,"Echo.shutdown")).start(); } /** @@ -98,43 +98,43 @@ public class EchoImpl * object may still have pending/executing calls), then * unexport the object forcibly. */ - public void run() + public void run() { - ActivationLibrary.deactivate(this, getID()); + ActivationLibrary.deactivate(this, getID()); } public static void main(String[] args) { - /* - * The following line is required with the JDK 1.2 VM so that the - * VM can exit gracefully when this test completes. Otherwise, the - * conservative garbage collector will find a handle to the server - * object on the native stack and not clear the weak reference to - * it in the RMI runtime's object table. - */ - Object dummy = new Object(); - - System.setSecurityManager(new RMISecurityManager()); - - try { - String protocol = ""; - if (args.length >= 1) - protocol = args[0]; + /* + * The following line is required with the JDK 1.2 VM so that the + * VM can exit gracefully when this test completes. Otherwise, the + * conservative garbage collector will find a handle to the server + * object on the native stack and not clear the weak reference to + * it in the RMI runtime's object table. + */ + Object dummy = new Object(); - System.out.println("EchoServer: creating remote object"); - ActivationGroupDesc groupDesc = - new ActivationGroupDesc(null, null); - ActivationSystem system = ActivationGroup.getSystem(); - ActivationGroupID groupID = system.registerGroup(groupDesc); - ActivationGroup.createGroup(groupID, groupDesc, 0); - - EchoImpl impl = new EchoImpl(protocol); - System.out.println("EchoServer: binding in registry"); - Naming.rebind("//:" + UseCustomSocketFactory.REGISTRY_PORT + - "/EchoServer", impl); - System.out.println("EchoServer ready."); - } catch (Exception e) { - System.err.println("EXCEPTION OCCURRED:"); - e.printStackTrace(); - } + System.setSecurityManager(new RMISecurityManager()); + + try { + String protocol = ""; + if (args.length >= 1) + protocol = args[0]; + + System.out.println("EchoServer: creating remote object"); + ActivationGroupDesc groupDesc = + new ActivationGroupDesc(null, null); + ActivationSystem system = ActivationGroup.getSystem(); + ActivationGroupID groupID = system.registerGroup(groupDesc); + ActivationGroup.createGroup(groupID, groupDesc, 0); + + EchoImpl impl = new EchoImpl(protocol); + System.out.println("EchoServer: binding in registry"); + Naming.rebind("//:" + UseCustomSocketFactory.REGISTRY_PORT + + "/EchoServer", impl); + System.out.println("EchoServer ready."); + } catch (Exception e) { + System.err.println("EXCEPTION OCCURRED:"); + e.printStackTrace(); + } } } diff --git a/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/activatable/EchoImpl_Stub.java b/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/activatable/EchoImpl_Stub.java index 5ff9b36e12f..134446486fd 100644 --- a/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/activatable/EchoImpl_Stub.java +++ b/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/activatable/EchoImpl_Stub.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -29,47 +29,47 @@ public final class EchoImpl_Stub implements Echo, java.rmi.Remote { private static final long serialVersionUID = 2; - + private static java.lang.reflect.Method $method_echoNot_0; private static java.lang.reflect.Method $method_shutdown_1; - + static { - try { - $method_echoNot_0 = Echo.class.getMethod("echoNot", new java.lang.Class[] {byte[].class}); - $method_shutdown_1 = Echo.class.getMethod("shutdown", new java.lang.Class[] {}); - } catch (java.lang.NoSuchMethodException e) { - throw new java.lang.NoSuchMethodError( - "stub class initialization failed"); - } + try { + $method_echoNot_0 = Echo.class.getMethod("echoNot", new java.lang.Class[] {byte[].class}); + $method_shutdown_1 = Echo.class.getMethod("shutdown", new java.lang.Class[] {}); + } catch (java.lang.NoSuchMethodException e) { + throw new java.lang.NoSuchMethodError( + "stub class initialization failed"); + } } - + // constructors public EchoImpl_Stub(java.rmi.server.RemoteRef ref) { - super(ref); + super(ref); } - + // methods from remote interfaces - + // implementation of echoNot(byte[]) public byte[] echoNot(byte[] $param_arrayOf_byte_1) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { - try { - Object $result = ref.invoke(this, $method_echoNot_0, new java.lang.Object[] {$param_arrayOf_byte_1}, -4295721514897591756L); - return ((byte[]) $result); - } catch (java.lang.RuntimeException e) { - throw e; - } catch (java.rmi.RemoteException e) { - throw e; - } catch (java.lang.Exception e) { - throw new java.rmi.UnexpectedException("undeclared checked exception", e); - } + try { + Object $result = ref.invoke(this, $method_echoNot_0, new java.lang.Object[] {$param_arrayOf_byte_1}, -4295721514897591756L); + return ((byte[]) $result); + } catch (java.lang.RuntimeException e) { + throw e; + } catch (java.rmi.RemoteException e) { + throw e; + } catch (java.lang.Exception e) { + throw new java.rmi.UnexpectedException("undeclared checked exception", e); + } } - + // implementation of shutdown() public void shutdown() - throws java.lang.Exception + throws java.lang.Exception { - ref.invoke(this, $method_shutdown_1, null, -7207851917985848402L); + ref.invoke(this, $method_shutdown_1, null, -7207851917985848402L); } } diff --git a/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/activatable/MultiSocketFactory.java b/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/activatable/MultiSocketFactory.java index f8ef69fac1c..9ebfa3236e0 100644 --- a/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/activatable/MultiSocketFactory.java +++ b/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/activatable/MultiSocketFactory.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -34,194 +34,193 @@ import java.util.zip.*; public class MultiSocketFactory { private static RMISocketFactory def = - RMISocketFactory.getDefaultSocketFactory(); + RMISocketFactory.getDefaultSocketFactory(); + - public static class ServerFactory - implements RMIServerSocketFactory, Serializable + implements RMIServerSocketFactory, Serializable { - private String protocol; - private byte[] data; + private String protocol; + private byte[] data; - public ServerFactory(String protocol, byte[] data) { - this.protocol = protocol; - this.data = data; - } + public ServerFactory(String protocol, byte[] data) { + this.protocol = protocol; + this.data = data; + } - public ServerSocket createServerSocket(int port) throws IOException - { - if (protocol.equals("compress")) { - return new CompressServerSocket(port); - - } else if (protocol.equals("xor")) { - if (data == null || data.length != 1) - throw new IOException("invalid argument for XOR protocol"); - return new XorServerSocket(port, data[0]); + public ServerSocket createServerSocket(int port) throws IOException + { + if (protocol.equals("compress")) { + return new CompressServerSocket(port); - } - - return def.createServerSocket(port); - } + } else if (protocol.equals("xor")) { + if (data == null || data.length != 1) + throw new IOException("invalid argument for XOR protocol"); + return new XorServerSocket(port, data[0]); + + } + + return def.createServerSocket(port); + } } public static class ClientFactory - implements RMIClientSocketFactory, Serializable + implements RMIClientSocketFactory, Serializable { - private String protocol; - private byte[] data; + private String protocol; + private byte[] data; - public ClientFactory(String protocol, byte[] data) { - this.protocol = protocol; - this.data = data; - } - - public Socket createSocket(String host, int port) - throws IOException - { - if (protocol.equals("compress")) { - return new CompressSocket(host, port); - - } else if (protocol.equals("xor")) { - if (data == null || data.length != 1) - throw new IOException("invalid argument for XOR protocol"); - return new XorSocket(host, port, data[0]); + public ClientFactory(String protocol, byte[] data) { + this.protocol = protocol; + this.data = data; + } - } + public Socket createSocket(String host, int port) + throws IOException + { + if (protocol.equals("compress")) { + return new CompressSocket(host, port); - return def.createSocket(host, port); - } + } else if (protocol.equals("xor")) { + if (data == null || data.length != 1) + throw new IOException("invalid argument for XOR protocol"); + return new XorSocket(host, port, data[0]); + + } + + return def.createSocket(host, port); + } } static class CompressSocket extends Socket { - private InputStream in; - private OutputStream out; - public CompressSocket() { super(); } - public CompressSocket(String host, int port) throws IOException { - super(host, port); - } - public InputStream getInputStream() throws IOException { - if (in == null) { - in = new CompressInputStream(super.getInputStream()); - } - return in; + private InputStream in; + private OutputStream out; + public CompressSocket() { super(); } + public CompressSocket(String host, int port) throws IOException { + super(host, port); + } + public InputStream getInputStream() throws IOException { + if (in == null) { + in = new CompressInputStream(super.getInputStream()); + } + return in; + } + public OutputStream getOutputStream() throws IOException { + if (out == null) { + out = new CompressOutputStream(super.getOutputStream()); + } + return out; } - public OutputStream getOutputStream() throws IOException { - if (out == null) { - out = new CompressOutputStream(super.getOutputStream()); - } - return out; - } } static class CompressServerSocket extends ServerSocket { - public CompressServerSocket(int port) throws IOException { - super(port); - } - public Socket accept() throws IOException { - Socket s = new CompressSocket(); - implAccept(s); - return s; - } + public CompressServerSocket(int port) throws IOException { + super(port); + } + public Socket accept() throws IOException { + Socket s = new CompressSocket(); + implAccept(s); + return s; + } } static class XorSocket extends Socket { - private byte pattern; - private InputStream in; - private OutputStream out; - public XorSocket(byte pattern) { super(); this.pattern = pattern; } - public XorSocket(String host, int port, byte pattern) - throws IOException - { - super(host, port); - this.pattern = pattern; - } - public InputStream getInputStream() throws IOException { - if (in == null) { - in = new XorInputStream(super.getInputStream(), pattern); - } - return in; + private byte pattern; + private InputStream in; + private OutputStream out; + public XorSocket(byte pattern) { super(); this.pattern = pattern; } + public XorSocket(String host, int port, byte pattern) + throws IOException + { + super(host, port); + this.pattern = pattern; + } + public InputStream getInputStream() throws IOException { + if (in == null) { + in = new XorInputStream(super.getInputStream(), pattern); + } + return in; + } + public OutputStream getOutputStream() throws IOException { + if (out == null) { + out = new XorOutputStream(super.getOutputStream(), pattern); + } + return out; } - public OutputStream getOutputStream() throws IOException { - if (out == null) { - out = new XorOutputStream(super.getOutputStream(), pattern); - } - return out; - } } static class XorServerSocket extends ServerSocket { - private byte pattern; - public XorServerSocket(int port, byte pattern) throws IOException { - super(port); - this.pattern = pattern; - } - public Socket accept() throws IOException { - Socket s = new XorSocket(pattern); - implAccept(s); - return s; - } + private byte pattern; + public XorServerSocket(int port, byte pattern) throws IOException { + super(port); + this.pattern = pattern; + } + public Socket accept() throws IOException { + Socket s = new XorSocket(pattern); + implAccept(s); + return s; + } } static class XorOutputStream extends FilterOutputStream { - private byte pattern; - public XorOutputStream(OutputStream out, byte pattern) { - super(out); - this.pattern = pattern; - } - public void write(int b) throws IOException { - out.write(b ^ pattern); - out.flush(); - } - public void write(byte b[], int off, int len) throws IOException { - for (int i = 0; i < len; i++) - write(b[off + i]); - } + private byte pattern; + public XorOutputStream(OutputStream out, byte pattern) { + super(out); + this.pattern = pattern; + } + public void write(int b) throws IOException { + out.write(b ^ pattern); + out.flush(); + } + public void write(byte b[], int off, int len) throws IOException { + for (int i = 0; i < len; i++) + write(b[off + i]); + } } static class XorInputStream extends FilterInputStream { - private byte pattern; - public XorInputStream(InputStream in, byte pattern) { - super(in); - this.pattern = pattern; - } - public int read() throws IOException { - int b = in.read(); -// System.out.print("BEFORE: " + Integer.toHexString(b)); - if (b != -1) - b = (b ^ pattern) & 0xFF; -// System.out.println("\tAFTER: " + Integer.toHexString(b)); - return b; - } - public int read(byte b[], int off, int len) throws IOException { - if (len <= 0) { - return 0; - } + private byte pattern; + public XorInputStream(InputStream in, byte pattern) { + super(in); + this.pattern = pattern; + } + public int read() throws IOException { + int b = in.read(); +// System.out.print("BEFORE: " + Integer.toHexString(b)); + if (b != -1) + b = (b ^ pattern) & 0xFF; +// System.out.println("\tAFTER: " + Integer.toHexString(b)); + return b; + } + public int read(byte b[], int off, int len) throws IOException { + if (len <= 0) { + return 0; + } - int c = read(); - if (c == -1) { - return -1; - } - b[off] = (byte)c; + int c = read(); + if (c == -1) { + return -1; + } + b[off] = (byte)c; - int i = 1; + int i = 1; /***** - try { - for (; i < len ; i++) { - c = read(); - if (c == -1) { - break; - } - if (b != null) { - b[off + i] = (byte)c; - } - } - } catch (IOException ee) { - } + try { + for (; i < len ; i++) { + c = read(); + if (c == -1) { + break; + } + if (b != null) { + b[off + i] = (byte)c; + } + } + } catch (IOException ee) { + } *****/ - return i; - } + return i; + } } } - diff --git a/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/activatable/UseCustomSocketFactory.java b/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/activatable/UseCustomSocketFactory.java index 7fbcd7f3018..b3e7a77b99b 100644 --- a/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/activatable/UseCustomSocketFactory.java +++ b/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/activatable/UseCustomSocketFactory.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1998-1999 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -45,124 +45,124 @@ public class UseCustomSocketFactory { final static int REGISTRY_PORT = 2006; static String[] protocol = new String[] { "", "compress", "xor" }; - + public static void main(String[] args) { - System.out.println("\nRegression test for bug 4115696\n"); - - TestLibrary.suggestSecurityManager("java.rmi.RMISecurityManager"); + System.out.println("\nRegression test for bug 4115696\n"); - try { - LocateRegistry.createRegistry(REGISTRY_PORT); - } catch (Exception e) { - TestLibrary.bomb("creating registry", e); - } + TestLibrary.suggestSecurityManager("java.rmi.RMISecurityManager"); - RMID rmid = null; - - try { - rmid = RMID.createRMID(true); - rmid.addArguments(new String[] { - "-C-Djava.security.policy=" + - TestParams.defaultGroupPolicy + - " -C-Djava.security.manager=java.rmi.RMISecurityManager "}); - rmid.start(); + try { + LocateRegistry.createRegistry(REGISTRY_PORT); + } catch (Exception e) { + TestLibrary.bomb("creating registry", e); + } - Echo[] echo = spawnAndTest(); - reactivateAndTest(echo); - } catch (IOException e) { - TestLibrary.bomb("creating rmid", e); - } finally { - if (rmid != null) - rmid.destroy(); - } + RMID rmid = null; + + try { + rmid = RMID.createRMID(true); + rmid.addArguments(new String[] { + "-C-Djava.security.policy=" + + TestParams.defaultGroupPolicy + + " -C-Djava.security.manager=java.rmi.RMISecurityManager "}); + rmid.start(); + + Echo[] echo = spawnAndTest(); + reactivateAndTest(echo); + } catch (IOException e) { + TestLibrary.bomb("creating rmid", e); + } finally { + if (rmid != null) + rmid.destroy(); + } } private static Echo[] spawnAndTest() { - - System.err.println("\nCreate Test-->"); - Echo[] echo = new Echo[protocol.length]; - - for (int i = 0; i < protocol.length; i++) { - - JavaVM serverVM = new JavaVM("EchoImpl", - "-Djava.security.policy=" + - TestParams.defaultPolicy, - protocol[i]); + System.err.println("\nCreate Test-->"); - System.err.println("\nusing protocol: " + - (protocol[i] == "" ? "none" : protocol[i])); - - try { - /* spawn VM for EchoServer */ - serverVM.start(); + Echo[] echo = new Echo[protocol.length]; - /* lookup server */ - int tries = 12; // need enough tries for slow machine. - echo[i] = null; - do { - try { - echo[i] = (Echo) Naming.lookup("//:" + REGISTRY_PORT + - "/EchoServer"); - break; - } catch (NotBoundException e) { - try { - Thread.sleep(2000); - } catch (Exception ignore) { - } - continue; - } - } while (--tries > 0); + for (int i = 0; i < protocol.length; i++) { - if (echo[i] == null) - TestLibrary.bomb("server not bound in 12 tries", null); + JavaVM serverVM = new JavaVM("EchoImpl", + "-Djava.security.policy=" + + TestParams.defaultPolicy, + protocol[i]); - /* invoke remote method and print result*/ - System.err.println("Bound to " + echo[i]); - byte[] data = ("Greetings, citizen " + - System.getProperty("user.name") + "!"). getBytes(); - byte[] result = echo[i].echoNot(data); - for (int j = 0; j < result.length; j++) - result[j] = (byte) ~result[j]; - System.err.println("Result: " + new String(result)); - echo[i].shutdown(); - - } catch (Exception e) { - TestLibrary.bomb("test failed", e); - - } finally { - serverVM.destroy(); - try { - Naming.unbind("//:" + REGISTRY_PORT + "/EchoServer"); - } catch (Exception e) { - TestLibrary.bomb("unbinding EchoServer", e); - - } - } - } - return echo; + System.err.println("\nusing protocol: " + + (protocol[i] == "" ? "none" : protocol[i])); + + try { + /* spawn VM for EchoServer */ + serverVM.start(); + + /* lookup server */ + int tries = 12; // need enough tries for slow machine. + echo[i] = null; + do { + try { + echo[i] = (Echo) Naming.lookup("//:" + REGISTRY_PORT + + "/EchoServer"); + break; + } catch (NotBoundException e) { + try { + Thread.sleep(2000); + } catch (Exception ignore) { + } + continue; + } + } while (--tries > 0); + + if (echo[i] == null) + TestLibrary.bomb("server not bound in 12 tries", null); + + /* invoke remote method and print result*/ + System.err.println("Bound to " + echo[i]); + byte[] data = ("Greetings, citizen " + + System.getProperty("user.name") + "!"). getBytes(); + byte[] result = echo[i].echoNot(data); + for (int j = 0; j < result.length; j++) + result[j] = (byte) ~result[j]; + System.err.println("Result: " + new String(result)); + echo[i].shutdown(); + + } catch (Exception e) { + TestLibrary.bomb("test failed", e); + + } finally { + serverVM.destroy(); + try { + Naming.unbind("//:" + REGISTRY_PORT + "/EchoServer"); + } catch (Exception e) { + TestLibrary.bomb("unbinding EchoServer", e); + + } + } + } + return echo; } private static void reactivateAndTest(Echo[] echo) { - System.err.println("\nReactivate Test-->"); + System.err.println("\nReactivate Test-->"); - for (int i = 0; i < echo.length; i++) { - try { - System.err.println("\nusing protocol: " + - (protocol[i] == "" ? "none" : protocol[i])); - byte[] data = ("Greetings, citizen " + - System.getProperty("user.name") + "!").getBytes(); - byte[] result = echo[i].echoNot(data); - for (int j = 0; j < result.length; j++) - result[j] = (byte) ~result[j]; - System.err.println("Result: " + new String(result)); - echo[i].shutdown(); - } catch (Exception e) { - TestLibrary.bomb("activating EchoServer for protocol " + protocol[i], e); - } - } + for (int i = 0; i < echo.length; i++) { + try { + System.err.println("\nusing protocol: " + + (protocol[i] == "" ? "none" : protocol[i])); + byte[] data = ("Greetings, citizen " + + System.getProperty("user.name") + "!").getBytes(); + byte[] result = echo[i].echoNot(data); + for (int j = 0; j < result.length; j++) + result[j] = (byte) ~result[j]; + System.err.println("Result: " + new String(result)); + echo[i].shutdown(); + } catch (Exception e) { + TestLibrary.bomb("activating EchoServer for protocol " + protocol[i], e); + } + } } } diff --git a/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/registry/Compress.java b/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/registry/Compress.java index 67bcf970a0b..88057b954a0 100644 --- a/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/registry/Compress.java +++ b/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/registry/Compress.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1998-1999 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -31,204 +31,204 @@ import java.net.*; public class Compress { interface CompressConstants { - // constants for 6-bit code values - static final int NOP = 0; // no operation: used to pad words on flush() - static final int RAW = 1; // introduces raw byte format - static final int BASE = 2; // base for codes found in lookup table - static final String codeTable = - "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ,.!?\"'()"; - } - - public static class CompressRMIClientSocketFactory - implements java.rmi.server.RMIClientSocketFactory, Serializable { - - public Socket createSocket(String host, int port) - throws IOException { - - return ((Socket) new CompressSocket(host, port)); - } + // constants for 6-bit code values + static final int NOP = 0; // no operation: used to pad words on flush() + static final int RAW = 1; // introduces raw byte format + static final int BASE = 2; // base for codes found in lookup table + static final String codeTable = + "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ,.!?\"'()"; } - public static class CompressRMIServerSocketFactory - implements RMIServerSocketFactory, - Serializable { - - public ServerSocket createServerSocket(int port) - throws IOException { + public static class CompressRMIClientSocketFactory + implements java.rmi.server.RMIClientSocketFactory, Serializable { - return ((ServerSocket) new CompressServerSocket(port)); - } - } - - public static class CompressSocket extends Socket { - private InputStream in; - private OutputStream out; - public CompressSocket() { super(); } - public CompressSocket(String host, int port) throws IOException { - super(host, port); - } - public InputStream getInputStream() throws IOException { - if (in == null) { - in = new CompressInputStream(super.getInputStream()); - } - return in; + public Socket createSocket(String host, int port) + throws IOException { + + return ((Socket) new CompressSocket(host, port)); + } + } + + public static class CompressRMIServerSocketFactory + implements RMIServerSocketFactory, + Serializable { + + public ServerSocket createServerSocket(int port) + throws IOException { + + return ((ServerSocket) new CompressServerSocket(port)); + } + } + + public static class CompressSocket extends Socket { + private InputStream in; + private OutputStream out; + public CompressSocket() { super(); } + public CompressSocket(String host, int port) throws IOException { + super(host, port); + } + public InputStream getInputStream() throws IOException { + if (in == null) { + in = new CompressInputStream(super.getInputStream()); + } + return in; + } + public OutputStream getOutputStream() throws IOException { + if (out == null) { + out = new CompressOutputStream(super.getOutputStream()); + } + return out; } - public OutputStream getOutputStream() throws IOException { - if (out == null) { - out = new CompressOutputStream(super.getOutputStream()); - } - return out; - } } public static class CompressServerSocket extends ServerSocket { - public CompressServerSocket(int port) throws IOException { - super(port); - } - public Socket accept() throws IOException { - Socket s = new CompressSocket(); - implAccept(s); - return s; - } + public CompressServerSocket(int port) throws IOException { + super(port); + } + public Socket accept() throws IOException { + Socket s = new CompressSocket(); + implAccept(s); + return s; + } } public static class CompressInputStream extends FilterInputStream - implements CompressConstants + implements CompressConstants { - - public CompressInputStream(InputStream in) { - super(in); - } - - // buffer of unpacked 6-bit codes from last 32-word read - int buf[] = new int[5]; - - // position of next code to read in buffer (5 == end of buffer) - int bufPos = 5; - - public int read() throws IOException { - try { - int code; - do { - code = readCode(); - } while (code == NOP); // ignore NOP codes - - if (code >= BASE) - return codeTable.charAt(code - BASE); - else if (code == RAW) { - int high = readCode(); - int low = readCode(); - return (high << 4) | low; - } else - throw new IOException("unknown compression code: " + code); - } catch (EOFException e) { - return -1; - } - } - - public int read(byte b[], int off, int len) throws IOException { - if (len <= 0) { - return 0; - } - - int c = read(); - if (c == -1) { - return -1; - } - b[off] = (byte)c; - - int i = 1; - /***** - try { - for (; i < len ; i++) { - c = read(); - if (c == -1) { - break; - } - if (b != null) { - b[off + i] = (byte)c; - } - } - } catch (IOException ee) { - } - *****/ - return i; - } - - private int readCode() throws IOException { - if (bufPos == 5) { - int b1 = in.read(); - int b2 = in.read(); - int b3 = in.read(); - int b4 = in.read(); - if ((b1 | b2 | b3 | b4) < 0) - throw new EOFException(); - int pack = (b1 << 24) | (b2 << 16) | (b3 << 8) | b4; - buf[0] = (pack >>> 24) & 0x3F; - buf[1] = (pack >>> 18) & 0x3F; - buf[2] = (pack >>> 12) & 0x3F; - buf[3] = (pack >>> 6) & 0x3F; - buf[4] = (pack >>> 0) & 0x3F; - bufPos = 0; - } - return buf[bufPos++]; - } + + public CompressInputStream(InputStream in) { + super(in); + } + + // buffer of unpacked 6-bit codes from last 32-word read + int buf[] = new int[5]; + + // position of next code to read in buffer (5 == end of buffer) + int bufPos = 5; + + public int read() throws IOException { + try { + int code; + do { + code = readCode(); + } while (code == NOP); // ignore NOP codes + + if (code >= BASE) + return codeTable.charAt(code - BASE); + else if (code == RAW) { + int high = readCode(); + int low = readCode(); + return (high << 4) | low; + } else + throw new IOException("unknown compression code: " + code); + } catch (EOFException e) { + return -1; + } + } + + public int read(byte b[], int off, int len) throws IOException { + if (len <= 0) { + return 0; + } + + int c = read(); + if (c == -1) { + return -1; + } + b[off] = (byte)c; + + int i = 1; + /***** + try { + for (; i < len ; i++) { + c = read(); + if (c == -1) { + break; + } + if (b != null) { + b[off + i] = (byte)c; + } + } + } catch (IOException ee) { + } + *****/ + return i; + } + + private int readCode() throws IOException { + if (bufPos == 5) { + int b1 = in.read(); + int b2 = in.read(); + int b3 = in.read(); + int b4 = in.read(); + if ((b1 | b2 | b3 | b4) < 0) + throw new EOFException(); + int pack = (b1 << 24) | (b2 << 16) | (b3 << 8) | b4; + buf[0] = (pack >>> 24) & 0x3F; + buf[1] = (pack >>> 18) & 0x3F; + buf[2] = (pack >>> 12) & 0x3F; + buf[3] = (pack >>> 6) & 0x3F; + buf[4] = (pack >>> 0) & 0x3F; + bufPos = 0; + } + return buf[bufPos++]; + } } public static class CompressOutputStream extends FilterOutputStream - implements CompressConstants + implements CompressConstants { - - public CompressOutputStream(OutputStream out) { - super(out); - } - - // buffer of 6-bit codes to pack into next 32-bit word - int buf[] = new int[5]; - - // number of valid codes pending in buffer - int bufPos = 0; - - public void write(int b) throws IOException { - b &= 0xFF; // force argument to a byte - - int pos = codeTable.indexOf((char)b); - if (pos != -1) - writeCode(BASE + pos); - else { - writeCode(RAW); - writeCode(b >> 4); - writeCode(b & 0xF); - } - } - - public void write(byte b[], int off, int len) throws IOException { - /* - * This is quite an inefficient implementation, because it has to - * call the other write method for every byte in the array. It - * could be optimized for performance by doing all the processing - * in this method. - */ - for (int i = 0; i < len; i++) - write(b[off + i]); - } - - public void flush() throws IOException { - while (bufPos > 0) - writeCode(NOP); - } - - private void writeCode(int c) throws IOException { - buf[bufPos++] = c; - if (bufPos == 5) { // write next word when we have 5 codes - int pack = (buf[0] << 24) | (buf[1] << 18) | (buf[2] << 12) | - (buf[3] << 6) | buf[4]; - out.write((pack >>> 24) & 0xFF); - out.write((pack >>> 16) & 0xFF); - out.write((pack >>> 8) & 0xFF); - out.write((pack >>> 0) & 0xFF); - bufPos = 0; - } - } + + public CompressOutputStream(OutputStream out) { + super(out); + } + + // buffer of 6-bit codes to pack into next 32-bit word + int buf[] = new int[5]; + + // number of valid codes pending in buffer + int bufPos = 0; + + public void write(int b) throws IOException { + b &= 0xFF; // force argument to a byte + + int pos = codeTable.indexOf((char)b); + if (pos != -1) + writeCode(BASE + pos); + else { + writeCode(RAW); + writeCode(b >> 4); + writeCode(b & 0xF); + } + } + + public void write(byte b[], int off, int len) throws IOException { + /* + * This is quite an inefficient implementation, because it has to + * call the other write method for every byte in the array. It + * could be optimized for performance by doing all the processing + * in this method. + */ + for (int i = 0; i < len; i++) + write(b[off + i]); + } + + public void flush() throws IOException { + while (bufPos > 0) + writeCode(NOP); + } + + private void writeCode(int c) throws IOException { + buf[bufPos++] = c; + if (bufPos == 5) { // write next word when we have 5 codes + int pack = (buf[0] << 24) | (buf[1] << 18) | (buf[2] << 12) | + (buf[3] << 6) | buf[4]; + out.write((pack >>> 24) & 0xFF); + out.write((pack >>> 16) & 0xFF); + out.write((pack >>> 8) & 0xFF); + out.write((pack >>> 0) & 0xFF); + bufPos = 0; + } + } } } diff --git a/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/registry/Hello.java b/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/registry/Hello.java index 5d3a83e7e8b..347dd9cc8e3 100644 --- a/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/registry/Hello.java +++ b/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/registry/Hello.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1998-1999 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * diff --git a/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/registry/HelloImpl.java b/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/registry/HelloImpl.java index adb1819ec82..13f74488a6c 100644 --- a/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/registry/HelloImpl.java +++ b/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/registry/HelloImpl.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1998-1999 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -36,49 +36,49 @@ public class HelloImpl public static boolean clientCalledSuccessfully = false; public HelloImpl() throws RemoteException { - super(0); + super(0); } - + public synchronized String sayHello() { - HelloImpl.clientCalledSuccessfully = true; - System.out.println("hello method called"); - this.notifyAll(); - return "hello"; + HelloImpl.clientCalledSuccessfully = true; + System.out.println("hello method called"); + this.notifyAll(); + return "hello"; } public static void main(String[] args) { - /* - * The following line is required with the JDK 1.2 VM so that the - * VM can exit gracefully when this test completes. Otherwise, the - * conservative garbage collector will find a handle to the server - * object on the native stack and not clear the weak reference to - * it in the RMI runtime's object table. - */ - Object dummy = new Object(); - Hello hello = null; - Registry registry = null; + /* + * The following line is required with the JDK 1.2 VM so that the + * VM can exit gracefully when this test completes. Otherwise, the + * conservative garbage collector will find a handle to the server + * object on the native stack and not clear the weak reference to + * it in the RMI runtime's object table. + */ + Object dummy = new Object(); + Hello hello = null; + Registry registry = null; - TestLibrary.suggestSecurityManager("java.rmi.RMISecurityManager"); + TestLibrary.suggestSecurityManager("java.rmi.RMISecurityManager"); - try { - String protocol = ""; - if (args.length >= 1) - protocol = args[0]; + try { + String protocol = ""; + if (args.length >= 1) + protocol = args[0]; - registry = java.rmi.registry.LocateRegistry. - getRegistry("localhost", TestLibrary.REGISTRY_PORT, - new Compress.CompressRMIClientSocketFactory()); - UseCustomSocketFactory.checkStub(registry, "RMIClientSocket"); - hello = (Hello) registry.lookup("/HelloServer"); + registry = java.rmi.registry.LocateRegistry. + getRegistry("localhost", TestLibrary.REGISTRY_PORT, + new Compress.CompressRMIClientSocketFactory()); + UseCustomSocketFactory.checkStub(registry, "RMIClientSocket"); + hello = (Hello) registry.lookup("/HelloServer"); - /* lookup server */ - System.err.println(hello.sayHello() + - ", remote greeting."); - } catch (Exception e) { - System.err.println("EXCEPTION OCCURRED:"); - e.printStackTrace(); - } finally { - hello = null; - } + /* lookup server */ + System.err.println(hello.sayHello() + + ", remote greeting."); + } catch (Exception e) { + System.err.println("EXCEPTION OCCURRED:"); + e.printStackTrace(); + } finally { + hello = null; + } } } diff --git a/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/registry/HelloImpl_Stub.java b/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/registry/HelloImpl_Stub.java index e500d6741f1..a2858f1ece8 100644 --- a/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/registry/HelloImpl_Stub.java +++ b/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/registry/HelloImpl_Stub.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -29,72 +29,72 @@ public final class HelloImpl_Stub implements Hello, java.rmi.Remote { private static java.rmi.server.Operation[] operations = { - new java.rmi.server.Operation("java.lang.String sayHello()") + new java.rmi.server.Operation("java.lang.String sayHello()") }; - + private static final long interfaceHash = 6486744599627128933L; - + private static final long serialVersionUID = 2; - + private static boolean useNewInvoke; private static java.lang.reflect.Method $method_sayHello_0; - + static { - try { - java.rmi.server.RemoteRef.class.getMethod("invoke", - new java.lang.Class[] { - java.rmi.Remote.class, - java.lang.reflect.Method.class, - java.lang.Object[].class, - long.class - }); - useNewInvoke = true; - $method_sayHello_0 = Hello.class.getMethod("sayHello", new java.lang.Class[] {}); - } catch (java.lang.NoSuchMethodException e) { - useNewInvoke = false; - } + try { + java.rmi.server.RemoteRef.class.getMethod("invoke", + new java.lang.Class[] { + java.rmi.Remote.class, + java.lang.reflect.Method.class, + java.lang.Object[].class, + long.class + }); + useNewInvoke = true; + $method_sayHello_0 = Hello.class.getMethod("sayHello", new java.lang.Class[] {}); + } catch (java.lang.NoSuchMethodException e) { + useNewInvoke = false; + } } - + // constructors public HelloImpl_Stub() { - super(); + super(); } public HelloImpl_Stub(java.rmi.server.RemoteRef ref) { - super(ref); + super(ref); } - + // methods from remote interfaces - + // implementation of sayHello() public java.lang.String sayHello() - throws java.rmi.RemoteException + throws java.rmi.RemoteException { - try { - if (useNewInvoke) { - Object $result = ref.invoke(this, $method_sayHello_0, null, 6043973830760146143L); - return ((java.lang.String) $result); - } else { - java.rmi.server.RemoteCall call = ref.newCall((java.rmi.server.RemoteObject) this, operations, 0, interfaceHash); - ref.invoke(call); - java.lang.String $result; - try { - java.io.ObjectInput in = call.getInputStream(); - $result = (java.lang.String) in.readObject(); - } catch (java.io.IOException e) { - throw new java.rmi.UnmarshalException("error unmarshalling return", e); - } catch (java.lang.ClassNotFoundException e) { - throw new java.rmi.UnmarshalException("error unmarshalling return", e); - } finally { - ref.done(call); - } - return $result; - } - } catch (java.lang.RuntimeException e) { - throw e; - } catch (java.rmi.RemoteException e) { - throw e; - } catch (java.lang.Exception e) { - throw new java.rmi.UnexpectedException("undeclared checked exception", e); - } + try { + if (useNewInvoke) { + Object $result = ref.invoke(this, $method_sayHello_0, null, 6043973830760146143L); + return ((java.lang.String) $result); + } else { + java.rmi.server.RemoteCall call = ref.newCall((java.rmi.server.RemoteObject) this, operations, 0, interfaceHash); + ref.invoke(call); + java.lang.String $result; + try { + java.io.ObjectInput in = call.getInputStream(); + $result = (java.lang.String) in.readObject(); + } catch (java.io.IOException e) { + throw new java.rmi.UnmarshalException("error unmarshalling return", e); + } catch (java.lang.ClassNotFoundException e) { + throw new java.rmi.UnmarshalException("error unmarshalling return", e); + } finally { + ref.done(call); + } + return $result; + } + } catch (java.lang.RuntimeException e) { + throw e; + } catch (java.rmi.RemoteException e) { + throw e; + } catch (java.lang.Exception e) { + throw new java.rmi.UnexpectedException("undeclared checked exception", e); + } } } diff --git a/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/registry/UseCustomSocketFactory.java b/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/registry/UseCustomSocketFactory.java index 767a7c47c8f..3bce0037a8a 100644 --- a/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/registry/UseCustomSocketFactory.java +++ b/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/registry/UseCustomSocketFactory.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1998-1999 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -47,86 +47,86 @@ import java.rmi.registry.*; * (i.e. compression) client and server socket factories. */ public class UseCustomSocketFactory { - + Hello hello = null; - + public static void main(String[] args) { - - Registry registry = null; - HelloImpl impl = null; - System.out.println("\nRegression test for bug 4148850\n"); - - TestLibrary.suggestSecurityManager("java.rmi.RMISecurityManager"); + Registry registry = null; + HelloImpl impl = null; - try { - impl = new HelloImpl(); + System.out.println("\nRegression test for bug 4148850\n"); - /* Make sure that the rmiregistry can communicate over a - * custom socket. Ensure that the functionality exists to - * allow the rmiregistry to be secure. - */ - registry = LocateRegistry. - createRegistry(TestLibrary.REGISTRY_PORT, - new Compress.CompressRMIClientSocketFactory(), - new Compress.CompressRMIServerSocketFactory()); - registry.rebind("/HelloServer", impl); - checkStub(registry, "RMIServerSocket"); - - } catch (Exception e) { - TestLibrary.bomb("creating registry", e); - } - - JavaVM serverVM = new JavaVM("HelloImpl", "-Djava.security.policy=" + - TestParams.defaultPolicy, ""); + TestLibrary.suggestSecurityManager("java.rmi.RMISecurityManager"); - try { + try { + impl = new HelloImpl(); - /* - * spawn VM for HelloServer which will download a client socket - * factory - */ - serverVM.start(); + /* Make sure that the rmiregistry can communicate over a + * custom socket. Ensure that the functionality exists to + * allow the rmiregistry to be secure. + */ + registry = LocateRegistry. + createRegistry(TestLibrary.REGISTRY_PORT, + new Compress.CompressRMIClientSocketFactory(), + new Compress.CompressRMIServerSocketFactory()); + registry.rebind("/HelloServer", impl); + checkStub(registry, "RMIServerSocket"); - synchronized (impl) { + } catch (Exception e) { + TestLibrary.bomb("creating registry", e); + } - System.out.println("waiting for remote notification"); - - if (!HelloImpl.clientCalledSuccessfully) { - impl.wait(75 * 1000); - } - - if (!HelloImpl.clientCalledSuccessfully) { - throw new RuntimeException("Client did not execute call in time..."); - } - } + JavaVM serverVM = new JavaVM("HelloImpl", "-Djava.security.policy=" + + TestParams.defaultPolicy, ""); - System.err.println("\nRegression test for bug 4148850 passed.\n "); + try { - } catch (Exception e) { - TestLibrary.bomb("test failed", e); - - } finally { - serverVM.destroy(); - try { - registry.unbind("/HelloServer"); - } catch (Exception e) { - TestLibrary.bomb("unbinding HelloServer", e); - } - TestLibrary.unexport(registry); - TestLibrary.unexport(impl); - impl = null; - registry = null; - } + /* + * spawn VM for HelloServer which will download a client socket + * factory + */ + serverVM.start(); + + synchronized (impl) { + + System.out.println("waiting for remote notification"); + + if (!HelloImpl.clientCalledSuccessfully) { + impl.wait(75 * 1000); + } + + if (!HelloImpl.clientCalledSuccessfully) { + throw new RuntimeException("Client did not execute call in time..."); + } + } + + System.err.println("\nRegression test for bug 4148850 passed.\n "); + + } catch (Exception e) { + TestLibrary.bomb("test failed", e); + + } finally { + serverVM.destroy(); + try { + registry.unbind("/HelloServer"); + } catch (Exception e) { + TestLibrary.bomb("unbinding HelloServer", e); + } + TestLibrary.unexport(registry); + TestLibrary.unexport(impl); + impl = null; + registry = null; + } } static void checkStub(Object stub, String toCheck) throws RemoteException { - System.err.println("Ensuring that the stub contains a socket factory string: " + - toCheck); - System.err.println(stub); - if (stub.toString().indexOf(toCheck) < 0) { - throw new RemoteException("RemoteStub.toString() did not contain instance of " - + toCheck); - } + System.err.println("Ensuring that the stub contains a socket factory string: " + + toCheck); + System.err.println(stub); + if (stub.toString().indexOf(toCheck) < 0) { + throw new RemoteException("RemoteStub.toString() did not contain instance of " + + toCheck); + } } } diff --git a/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/unicast/CompressConstants.java b/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/unicast/CompressConstants.java index 7db4a6b9c8a..cc7526077d8 100644 --- a/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/unicast/CompressConstants.java +++ b/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/unicast/CompressConstants.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -27,9 +27,9 @@ interface CompressConstants { // constants for 6-bit code values - static final int NOP = 0; // no operation: used to pad words on flush() - static final int RAW = 1; // introduces raw byte format - static final int BASE = 2; // base for codes found in lookup table + static final int NOP = 0; // no operation: used to pad words on flush() + static final int RAW = 1; // introduces raw byte format + static final int BASE = 2; // base for codes found in lookup table static final String codeTable = - "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ,.!?\"'()"; + "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ,.!?\"'()"; } diff --git a/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/unicast/CompressInputStream.java b/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/unicast/CompressInputStream.java index 3a42bb18073..31577a1c2ad 100644 --- a/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/unicast/CompressInputStream.java +++ b/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/unicast/CompressInputStream.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -31,7 +31,7 @@ class CompressInputStream extends FilterInputStream { public CompressInputStream(InputStream in) { - super(in); + super(in); } // buffer of unpacked 6-bit codes from last 32-word read @@ -41,70 +41,70 @@ class CompressInputStream extends FilterInputStream int bufPos = 5; public int read() throws IOException { - try { - int code; - do { - code = readCode(); - } while (code == NOP); // ignore NOP codes + try { + int code; + do { + code = readCode(); + } while (code == NOP); // ignore NOP codes - if (code >= BASE) - return codeTable.charAt(code - BASE); - else if (code == RAW) { - int high = readCode(); - int low = readCode(); - return (high << 4) | low; - } else - throw new IOException("unknown compression code: " + code); - } catch (EOFException e) { - return -1; - } + if (code >= BASE) + return codeTable.charAt(code - BASE); + else if (code == RAW) { + int high = readCode(); + int low = readCode(); + return (high << 4) | low; + } else + throw new IOException("unknown compression code: " + code); + } catch (EOFException e) { + return -1; + } } public int read(byte b[], int off, int len) throws IOException { - if (len <= 0) { - return 0; - } + if (len <= 0) { + return 0; + } - int c = read(); - if (c == -1) { - return -1; - } - b[off] = (byte)c; + int c = read(); + if (c == -1) { + return -1; + } + b[off] = (byte)c; - int i = 1; + int i = 1; /***** - try { - for (; i < len ; i++) { - c = read(); - if (c == -1) { - break; - } - if (b != null) { - b[off + i] = (byte)c; - } - } - } catch (IOException ee) { - } + try { + for (; i < len ; i++) { + c = read(); + if (c == -1) { + break; + } + if (b != null) { + b[off + i] = (byte)c; + } + } + } catch (IOException ee) { + } *****/ - return i; + return i; } private int readCode() throws IOException { - if (bufPos == 5) { - int b1 = in.read(); - int b2 = in.read(); - int b3 = in.read(); - int b4 = in.read(); - if ((b1 | b2 | b3 | b4) < 0) - throw new EOFException(); - int pack = (b1 << 24) | (b2 << 16) | (b3 << 8) | b4; - buf[0] = (pack >>> 24) & 0x3F; - buf[1] = (pack >>> 18) & 0x3F; - buf[2] = (pack >>> 12) & 0x3F; - buf[3] = (pack >>> 6) & 0x3F; - buf[4] = (pack >>> 0) & 0x3F; - bufPos = 0; - } - return buf[bufPos++]; + if (bufPos == 5) { + int b1 = in.read(); + int b2 = in.read(); + int b3 = in.read(); + int b4 = in.read(); + if ((b1 | b2 | b3 | b4) < 0) + throw new EOFException(); + int pack = (b1 << 24) | (b2 << 16) | (b3 << 8) | b4; + buf[0] = (pack >>> 24) & 0x3F; + buf[1] = (pack >>> 18) & 0x3F; + buf[2] = (pack >>> 12) & 0x3F; + buf[3] = (pack >>> 6) & 0x3F; + buf[4] = (pack >>> 0) & 0x3F; + bufPos = 0; + } + return buf[bufPos++]; } } diff --git a/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/unicast/CompressOutputStream.java b/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/unicast/CompressOutputStream.java index ca1a5963f95..5d38e147b18 100644 --- a/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/unicast/CompressOutputStream.java +++ b/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/unicast/CompressOutputStream.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -31,7 +31,7 @@ class CompressOutputStream extends FilterOutputStream { public CompressOutputStream(OutputStream out) { - super(out); + super(out); } // buffer of 6-bit codes to pack into next 32-bit word @@ -41,44 +41,44 @@ class CompressOutputStream extends FilterOutputStream int bufPos = 0; public void write(int b) throws IOException { - b &= 0xFF; // force argument to a byte + b &= 0xFF; // force argument to a byte - int pos = codeTable.indexOf((char)b); - if (pos != -1) - writeCode(BASE + pos); - else { - writeCode(RAW); - writeCode(b >> 4); - writeCode(b & 0xF); - } + int pos = codeTable.indexOf((char)b); + if (pos != -1) + writeCode(BASE + pos); + else { + writeCode(RAW); + writeCode(b >> 4); + writeCode(b & 0xF); + } } public void write(byte b[], int off, int len) throws IOException { - /* - * This is quite an inefficient implementation, because it has to - * call the other write method for every byte in the array. It + /* + * This is quite an inefficient implementation, because it has to + * call the other write method for every byte in the array. It * could be optimized for performance by doing all the processing - * in this method. - */ - for (int i = 0; i < len; i++) - write(b[off + i]); + * in this method. + */ + for (int i = 0; i < len; i++) + write(b[off + i]); } public void flush() throws IOException { - while (bufPos > 0) - writeCode(NOP); + while (bufPos > 0) + writeCode(NOP); } private void writeCode(int c) throws IOException { - buf[bufPos++] = c; - if (bufPos == 5) { // write next word when we have 5 codes - int pack = (buf[0] << 24) | (buf[1] << 18) | (buf[2] << 12) | - (buf[3] << 6) | buf[4]; - out.write((pack >>> 24) & 0xFF); - out.write((pack >>> 16) & 0xFF); - out.write((pack >>> 8) & 0xFF); - out.write((pack >>> 0) & 0xFF); - bufPos = 0; - } + buf[bufPos++] = c; + if (bufPos == 5) { // write next word when we have 5 codes + int pack = (buf[0] << 24) | (buf[1] << 18) | (buf[2] << 12) | + (buf[3] << 6) | buf[4]; + out.write((pack >>> 24) & 0xFF); + out.write((pack >>> 16) & 0xFF); + out.write((pack >>> 8) & 0xFF); + out.write((pack >>> 0) & 0xFF); + bufPos = 0; + } } } diff --git a/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/unicast/Echo.java b/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/unicast/Echo.java index 8a9fc44998f..03441f25a50 100644 --- a/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/unicast/Echo.java +++ b/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/unicast/Echo.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * diff --git a/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/unicast/EchoImpl.java b/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/unicast/EchoImpl.java index 78cf7414adb..c156ff903e9 100644 --- a/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/unicast/EchoImpl.java +++ b/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/unicast/EchoImpl.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1998-1999 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -33,44 +33,44 @@ public class EchoImpl private static final byte[] pattern = { (byte) 'A' }; public EchoImpl(String protocol) throws RemoteException { - super(0, - new MultiSocketFactory.ClientFactory(protocol, pattern), - new MultiSocketFactory.ServerFactory(protocol, pattern)); + super(0, + new MultiSocketFactory.ClientFactory(protocol, pattern), + new MultiSocketFactory.ServerFactory(protocol, pattern)); } - + public byte[] echoNot(byte[] data) { - byte[] result = new byte[data.length]; - for (int i = 0; i < data.length; i++) - result[i] = (byte) ~data[i]; - return result; + byte[] result = new byte[data.length]; + for (int i = 0; i < data.length; i++) + result[i] = (byte) ~data[i]; + return result; } public static void main(String[] args) { - /* - * The following line is required with the JDK 1.2 VM so that the - * VM can exit gracefully when this test completes. Otherwise, the - * conservative garbage collector will find a handle to the server - * object on the native stack and not clear the weak reference to - * it in the RMI runtime's object table. - */ - Object dummy = new Object(); - - TestLibrary.suggestSecurityManager("java.rmi.RMISecurityManager"); - - try { - String protocol = ""; - if (args.length >= 1) - protocol = args[0]; + /* + * The following line is required with the JDK 1.2 VM so that the + * VM can exit gracefully when this test completes. Otherwise, the + * conservative garbage collector will find a handle to the server + * object on the native stack and not clear the weak reference to + * it in the RMI runtime's object table. + */ + Object dummy = new Object(); - System.out.println("EchoServer: creating remote object"); - EchoImpl impl = new EchoImpl(protocol); - System.out.println("EchoServer: binding in registry"); - Naming.rebind("//:" + TestLibrary.REGISTRY_PORT + - "/EchoServer", impl); - System.out.println("EchoServer ready."); - } catch (Exception e) { - System.err.println("EXCEPTION OCCURRED:"); - e.printStackTrace(); - } + TestLibrary.suggestSecurityManager("java.rmi.RMISecurityManager"); + + try { + String protocol = ""; + if (args.length >= 1) + protocol = args[0]; + + System.out.println("EchoServer: creating remote object"); + EchoImpl impl = new EchoImpl(protocol); + System.out.println("EchoServer: binding in registry"); + Naming.rebind("//:" + TestLibrary.REGISTRY_PORT + + "/EchoServer", impl); + System.out.println("EchoServer ready."); + } catch (Exception e) { + System.err.println("EXCEPTION OCCURRED:"); + e.printStackTrace(); + } } } diff --git a/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/unicast/EchoImpl_Stub.java b/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/unicast/EchoImpl_Stub.java index be15d2722d8..05e866e61d9 100644 --- a/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/unicast/EchoImpl_Stub.java +++ b/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/unicast/EchoImpl_Stub.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -29,38 +29,38 @@ public final class EchoImpl_Stub implements Echo, java.rmi.Remote { private static final long serialVersionUID = 2; - + private static java.lang.reflect.Method $method_echoNot_0; - + static { - try { - $method_echoNot_0 = Echo.class.getMethod("echoNot", new java.lang.Class[] {byte[].class}); - } catch (java.lang.NoSuchMethodException e) { - throw new java.lang.NoSuchMethodError( - "stub class initialization failed"); - } + try { + $method_echoNot_0 = Echo.class.getMethod("echoNot", new java.lang.Class[] {byte[].class}); + } catch (java.lang.NoSuchMethodException e) { + throw new java.lang.NoSuchMethodError( + "stub class initialization failed"); + } } - + // constructors public EchoImpl_Stub(java.rmi.server.RemoteRef ref) { - super(ref); + super(ref); } - + // methods from remote interfaces - + // implementation of echoNot(byte[]) public byte[] echoNot(byte[] $param_arrayOf_byte_1) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { - try { - Object $result = ref.invoke(this, $method_echoNot_0, new java.lang.Object[] {$param_arrayOf_byte_1}, -4295721514897591756L); - return ((byte[]) $result); - } catch (java.lang.RuntimeException e) { - throw e; - } catch (java.rmi.RemoteException e) { - throw e; - } catch (java.lang.Exception e) { - throw new java.rmi.UnexpectedException("undeclared checked exception", e); - } + try { + Object $result = ref.invoke(this, $method_echoNot_0, new java.lang.Object[] {$param_arrayOf_byte_1}, -4295721514897591756L); + return ((byte[]) $result); + } catch (java.lang.RuntimeException e) { + throw e; + } catch (java.rmi.RemoteException e) { + throw e; + } catch (java.lang.Exception e) { + throw new java.rmi.UnexpectedException("undeclared checked exception", e); + } } } diff --git a/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/unicast/MultiSocketFactory.java b/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/unicast/MultiSocketFactory.java index f8ef69fac1c..9ebfa3236e0 100644 --- a/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/unicast/MultiSocketFactory.java +++ b/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/unicast/MultiSocketFactory.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -34,194 +34,193 @@ import java.util.zip.*; public class MultiSocketFactory { private static RMISocketFactory def = - RMISocketFactory.getDefaultSocketFactory(); + RMISocketFactory.getDefaultSocketFactory(); + - public static class ServerFactory - implements RMIServerSocketFactory, Serializable + implements RMIServerSocketFactory, Serializable { - private String protocol; - private byte[] data; + private String protocol; + private byte[] data; - public ServerFactory(String protocol, byte[] data) { - this.protocol = protocol; - this.data = data; - } + public ServerFactory(String protocol, byte[] data) { + this.protocol = protocol; + this.data = data; + } - public ServerSocket createServerSocket(int port) throws IOException - { - if (protocol.equals("compress")) { - return new CompressServerSocket(port); - - } else if (protocol.equals("xor")) { - if (data == null || data.length != 1) - throw new IOException("invalid argument for XOR protocol"); - return new XorServerSocket(port, data[0]); + public ServerSocket createServerSocket(int port) throws IOException + { + if (protocol.equals("compress")) { + return new CompressServerSocket(port); - } - - return def.createServerSocket(port); - } + } else if (protocol.equals("xor")) { + if (data == null || data.length != 1) + throw new IOException("invalid argument for XOR protocol"); + return new XorServerSocket(port, data[0]); + + } + + return def.createServerSocket(port); + } } public static class ClientFactory - implements RMIClientSocketFactory, Serializable + implements RMIClientSocketFactory, Serializable { - private String protocol; - private byte[] data; + private String protocol; + private byte[] data; - public ClientFactory(String protocol, byte[] data) { - this.protocol = protocol; - this.data = data; - } - - public Socket createSocket(String host, int port) - throws IOException - { - if (protocol.equals("compress")) { - return new CompressSocket(host, port); - - } else if (protocol.equals("xor")) { - if (data == null || data.length != 1) - throw new IOException("invalid argument for XOR protocol"); - return new XorSocket(host, port, data[0]); + public ClientFactory(String protocol, byte[] data) { + this.protocol = protocol; + this.data = data; + } - } + public Socket createSocket(String host, int port) + throws IOException + { + if (protocol.equals("compress")) { + return new CompressSocket(host, port); - return def.createSocket(host, port); - } + } else if (protocol.equals("xor")) { + if (data == null || data.length != 1) + throw new IOException("invalid argument for XOR protocol"); + return new XorSocket(host, port, data[0]); + + } + + return def.createSocket(host, port); + } } static class CompressSocket extends Socket { - private InputStream in; - private OutputStream out; - public CompressSocket() { super(); } - public CompressSocket(String host, int port) throws IOException { - super(host, port); - } - public InputStream getInputStream() throws IOException { - if (in == null) { - in = new CompressInputStream(super.getInputStream()); - } - return in; + private InputStream in; + private OutputStream out; + public CompressSocket() { super(); } + public CompressSocket(String host, int port) throws IOException { + super(host, port); + } + public InputStream getInputStream() throws IOException { + if (in == null) { + in = new CompressInputStream(super.getInputStream()); + } + return in; + } + public OutputStream getOutputStream() throws IOException { + if (out == null) { + out = new CompressOutputStream(super.getOutputStream()); + } + return out; } - public OutputStream getOutputStream() throws IOException { - if (out == null) { - out = new CompressOutputStream(super.getOutputStream()); - } - return out; - } } static class CompressServerSocket extends ServerSocket { - public CompressServerSocket(int port) throws IOException { - super(port); - } - public Socket accept() throws IOException { - Socket s = new CompressSocket(); - implAccept(s); - return s; - } + public CompressServerSocket(int port) throws IOException { + super(port); + } + public Socket accept() throws IOException { + Socket s = new CompressSocket(); + implAccept(s); + return s; + } } static class XorSocket extends Socket { - private byte pattern; - private InputStream in; - private OutputStream out; - public XorSocket(byte pattern) { super(); this.pattern = pattern; } - public XorSocket(String host, int port, byte pattern) - throws IOException - { - super(host, port); - this.pattern = pattern; - } - public InputStream getInputStream() throws IOException { - if (in == null) { - in = new XorInputStream(super.getInputStream(), pattern); - } - return in; + private byte pattern; + private InputStream in; + private OutputStream out; + public XorSocket(byte pattern) { super(); this.pattern = pattern; } + public XorSocket(String host, int port, byte pattern) + throws IOException + { + super(host, port); + this.pattern = pattern; + } + public InputStream getInputStream() throws IOException { + if (in == null) { + in = new XorInputStream(super.getInputStream(), pattern); + } + return in; + } + public OutputStream getOutputStream() throws IOException { + if (out == null) { + out = new XorOutputStream(super.getOutputStream(), pattern); + } + return out; } - public OutputStream getOutputStream() throws IOException { - if (out == null) { - out = new XorOutputStream(super.getOutputStream(), pattern); - } - return out; - } } static class XorServerSocket extends ServerSocket { - private byte pattern; - public XorServerSocket(int port, byte pattern) throws IOException { - super(port); - this.pattern = pattern; - } - public Socket accept() throws IOException { - Socket s = new XorSocket(pattern); - implAccept(s); - return s; - } + private byte pattern; + public XorServerSocket(int port, byte pattern) throws IOException { + super(port); + this.pattern = pattern; + } + public Socket accept() throws IOException { + Socket s = new XorSocket(pattern); + implAccept(s); + return s; + } } static class XorOutputStream extends FilterOutputStream { - private byte pattern; - public XorOutputStream(OutputStream out, byte pattern) { - super(out); - this.pattern = pattern; - } - public void write(int b) throws IOException { - out.write(b ^ pattern); - out.flush(); - } - public void write(byte b[], int off, int len) throws IOException { - for (int i = 0; i < len; i++) - write(b[off + i]); - } + private byte pattern; + public XorOutputStream(OutputStream out, byte pattern) { + super(out); + this.pattern = pattern; + } + public void write(int b) throws IOException { + out.write(b ^ pattern); + out.flush(); + } + public void write(byte b[], int off, int len) throws IOException { + for (int i = 0; i < len; i++) + write(b[off + i]); + } } static class XorInputStream extends FilterInputStream { - private byte pattern; - public XorInputStream(InputStream in, byte pattern) { - super(in); - this.pattern = pattern; - } - public int read() throws IOException { - int b = in.read(); -// System.out.print("BEFORE: " + Integer.toHexString(b)); - if (b != -1) - b = (b ^ pattern) & 0xFF; -// System.out.println("\tAFTER: " + Integer.toHexString(b)); - return b; - } - public int read(byte b[], int off, int len) throws IOException { - if (len <= 0) { - return 0; - } + private byte pattern; + public XorInputStream(InputStream in, byte pattern) { + super(in); + this.pattern = pattern; + } + public int read() throws IOException { + int b = in.read(); +// System.out.print("BEFORE: " + Integer.toHexString(b)); + if (b != -1) + b = (b ^ pattern) & 0xFF; +// System.out.println("\tAFTER: " + Integer.toHexString(b)); + return b; + } + public int read(byte b[], int off, int len) throws IOException { + if (len <= 0) { + return 0; + } - int c = read(); - if (c == -1) { - return -1; - } - b[off] = (byte)c; + int c = read(); + if (c == -1) { + return -1; + } + b[off] = (byte)c; - int i = 1; + int i = 1; /***** - try { - for (; i < len ; i++) { - c = read(); - if (c == -1) { - break; - } - if (b != null) { - b[off + i] = (byte)c; - } - } - } catch (IOException ee) { - } + try { + for (; i < len ; i++) { + c = read(); + if (c == -1) { + break; + } + if (b != null) { + b[off + i] = (byte)c; + } + } + } catch (IOException ee) { + } *****/ - return i; - } + return i; + } } } - diff --git a/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/unicast/UseCustomSocketFactory.java b/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/unicast/UseCustomSocketFactory.java index 04e81e45083..f1b01f9b7c6 100644 --- a/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/unicast/UseCustomSocketFactory.java +++ b/jdk/test/java/rmi/server/RMISocketFactory/useSocketFactory/unicast/UseCustomSocketFactory.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1998-1999 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -25,7 +25,7 @@ * @bug 4127826 * * @summary synopsis: need to download factories for use with custom socket - * types + * types * @author Ann Wollrath * * @library ../../../../testlibrary @@ -45,77 +45,77 @@ import java.rmi.registry.*; public class UseCustomSocketFactory { public static void main(String[] args) { - - String[] protocol = new String[] { "", "compress", "xor" }; - System.out.println("\nRegression test for bug 4127826\n"); - - TestLibrary.suggestSecurityManager("java.rmi.RMISecurityManager"); + String[] protocol = new String[] { "", "compress", "xor" }; - try { - LocateRegistry.createRegistry(TestLibrary.REGISTRY_PORT); - } catch (Exception e) { - TestLibrary.bomb("creating registry", e); - } + System.out.println("\nRegression test for bug 4127826\n"); - for (int i = 0; i < protocol.length; i++) { + TestLibrary.suggestSecurityManager("java.rmi.RMISecurityManager"); - System.err.println("test policy: " + - TestParams.defaultPolicy); + try { + LocateRegistry.createRegistry(TestLibrary.REGISTRY_PORT); + } catch (Exception e) { + TestLibrary.bomb("creating registry", e); + } - JavaVM serverVM = new JavaVM("EchoImpl", - "-Djava.security.policy=" + - TestParams.defaultPolicy, - protocol[i]); - System.err.println("\nusing protocol: " + - (protocol[i] == "" ? "none" : protocol[i])); - - try { - /* spawn VM for EchoServer */ - serverVM.start(); + for (int i = 0; i < protocol.length; i++) { - /* lookup server */ - int tries = 8; - Echo obj = null; - do { - try { - obj = (Echo) Naming.lookup("//:" + TestLibrary.REGISTRY_PORT + - "/EchoServer"); - break; - } catch (NotBoundException e) { - try { - Thread.sleep(2000); - } catch (Exception ignore) { - } - continue; - } - } while (--tries > 0); + System.err.println("test policy: " + + TestParams.defaultPolicy); - if (obj == null) - TestLibrary.bomb("server not bound in 8 tries", null); + JavaVM serverVM = new JavaVM("EchoImpl", + "-Djava.security.policy=" + + TestParams.defaultPolicy, + protocol[i]); + System.err.println("\nusing protocol: " + + (protocol[i] == "" ? "none" : protocol[i])); - /* invoke remote method and print result*/ - System.err.println("Bound to " + obj); - byte[] data = ("Greetings, citizen " + - System.getProperty("user.name") + "!"). getBytes(); - byte[] result = obj.echoNot(data); - for (int j = 0; j < result.length; j++) - result[j] = (byte) ~result[j]; - System.err.println("Result: " + new String(result)); - - } catch (Exception e) { - TestLibrary.bomb("test failed", e); - - } finally { - serverVM.destroy(); - try { - Naming.unbind("//:" + TestLibrary.REGISTRY_PORT + - "/EchoServer"); - } catch (Exception e) { - TestLibrary.bomb("unbinding EchoServer", e); - - } - } - } + try { + /* spawn VM for EchoServer */ + serverVM.start(); + + /* lookup server */ + int tries = 8; + Echo obj = null; + do { + try { + obj = (Echo) Naming.lookup("//:" + TestLibrary.REGISTRY_PORT + + "/EchoServer"); + break; + } catch (NotBoundException e) { + try { + Thread.sleep(2000); + } catch (Exception ignore) { + } + continue; + } + } while (--tries > 0); + + if (obj == null) + TestLibrary.bomb("server not bound in 8 tries", null); + + /* invoke remote method and print result*/ + System.err.println("Bound to " + obj); + byte[] data = ("Greetings, citizen " + + System.getProperty("user.name") + "!"). getBytes(); + byte[] result = obj.echoNot(data); + for (int j = 0; j < result.length; j++) + result[j] = (byte) ~result[j]; + System.err.println("Result: " + new String(result)); + + } catch (Exception e) { + TestLibrary.bomb("test failed", e); + + } finally { + serverVM.destroy(); + try { + Naming.unbind("//:" + TestLibrary.REGISTRY_PORT + + "/EchoServer"); + } catch (Exception e) { + TestLibrary.bomb("unbinding EchoServer", e); + + } + } + } } } diff --git a/jdk/test/java/rmi/server/RemoteServer/setLogPermission/SetLogPermission.java b/jdk/test/java/rmi/server/RemoteServer/setLogPermission/SetLogPermission.java index 75ba21e3d44..5d191fe67a6 100644 --- a/jdk/test/java/rmi/server/RemoteServer/setLogPermission/SetLogPermission.java +++ b/jdk/test/java/rmi/server/RemoteServer/setLogPermission/SetLogPermission.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 2002-2003 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -25,7 +25,7 @@ * @bug 4533390 * @summary SecurityException can be obtained but is not specified. * The RemoteServer.setLog method requires - * java.util.log.LoggingPermission("control"). + * java.util.log.LoggingPermission("control"). * @author Ann Wollrath * @run main/othervm/policy=java.policy SetLogPermission */ @@ -40,42 +40,42 @@ public class SetLogPermission { public static void main(String[] args) throws Exception { - System.err.println("\nRegression test for bug 4533390\n"); + System.err.println("\nRegression test for bug 4533390\n"); - if (System.getSecurityManager() == null) { - System.setSecurityManager(new SecurityManager()); - } - - CodeSource codesource = new CodeSource(null, (Certificate[]) null); - Permissions perms = null; - ProtectionDomain pd = new ProtectionDomain(codesource, perms); - AccessControlContext acc = - new AccessControlContext(new ProtectionDomain[] { pd }); - - java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - public Object run() { - try { - System.err.println( - "Attempt to set log without permission"); - RemoteServer.setLog(new ByteArrayOutputStream()); - throw new RuntimeException( - "TEST FAILED: set log without permission"); - } catch (SecurityException e) { - System.err.println( - "TEST PASSED: unable to set log without permission"); - } - return null; - }}, acc); + if (System.getSecurityManager() == null) { + System.setSecurityManager(new SecurityManager()); + } - try { - System.err.println("Attempt to set log with permission"); - RemoteServer.setLog(new ByteArrayOutputStream()); - System.err.println( - "TEST PASSED: sufficient permission to set log"); - } catch (SecurityException e) { - System.err.println("TEST FAILED: unable to set log"); - throw e; - } + CodeSource codesource = new CodeSource(null, (Certificate[]) null); + Permissions perms = null; + ProtectionDomain pd = new ProtectionDomain(codesource, perms); + AccessControlContext acc = + new AccessControlContext(new ProtectionDomain[] { pd }); + + java.security.AccessController.doPrivileged( + new java.security.PrivilegedAction() { + public Object run() { + try { + System.err.println( + "Attempt to set log without permission"); + RemoteServer.setLog(new ByteArrayOutputStream()); + throw new RuntimeException( + "TEST FAILED: set log without permission"); + } catch (SecurityException e) { + System.err.println( + "TEST PASSED: unable to set log without permission"); + } + return null; + }}, acc); + + try { + System.err.println("Attempt to set log with permission"); + RemoteServer.setLog(new ByteArrayOutputStream()); + System.err.println( + "TEST PASSED: sufficient permission to set log"); + } catch (SecurityException e) { + System.err.println("TEST FAILED: unable to set log"); + throw e; + } } } diff --git a/jdk/test/java/rmi/server/UnicastRemoteObject/changeHostName/ChangeHostName.java b/jdk/test/java/rmi/server/UnicastRemoteObject/changeHostName/ChangeHostName.java index 0a7754a75f3..436d70a4051 100644 --- a/jdk/test/java/rmi/server/UnicastRemoteObject/changeHostName/ChangeHostName.java +++ b/jdk/test/java/rmi/server/UnicastRemoteObject/changeHostName/ChangeHostName.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -50,40 +50,40 @@ public class ChangeHostName } public void receive(Remote obj) { - System.err.println("received: " + obj.toString()); + System.err.println("received: " + obj.toString()); } public static void main(String[] args) throws Exception { - InetAddress localAddress = InetAddress.getLocalHost(); - String[] hostlist = new String[] { - localAddress.getHostAddress(), localAddress.getHostName() }; + InetAddress localAddress = InetAddress.getLocalHost(); + String[] hostlist = new String[] { + localAddress.getHostAddress(), localAddress.getHostName() }; - for (int i = 0; i < hostlist.length; i++) { - - System.setProperty("java.rmi.server.hostname", hostlist[i]); - Remote impl = new ChangeHostName(); - System.err.println("\ncreated impl extending URO: " + impl); - - Receiver stub = (Receiver) RemoteObject.toStub(impl); - System.err.println("stub for impl: " + stub); + for (int i = 0; i < hostlist.length; i++) { - System.err.println("invoking method on stub"); - stub.receive(stub); + System.setProperty("java.rmi.server.hostname", hostlist[i]); + Remote impl = new ChangeHostName(); + System.err.println("\ncreated impl extending URO: " + impl); - UnicastRemoteObject.unexportObject(impl, true); - System.err.println("unexported impl"); + Receiver stub = (Receiver) RemoteObject.toStub(impl); + System.err.println("stub for impl: " + stub); - if (stub.toString().indexOf(hostlist[i]) >= 0) { - System.err.println("stub's ref contains hostname: " + - hostlist[i]); - } else { - throw new RuntimeException( - "TEST FAILED: stub's ref doesn't contain hostname: " + - hostlist[i]); - } - } - System.err.println("TEST PASSED"); + System.err.println("invoking method on stub"); + stub.receive(stub); + + UnicastRemoteObject.unexportObject(impl, true); + System.err.println("unexported impl"); + + if (stub.toString().indexOf(hostlist[i]) >= 0) { + System.err.println("stub's ref contains hostname: " + + hostlist[i]); + } else { + throw new RuntimeException( + "TEST FAILED: stub's ref doesn't contain hostname: " + + hostlist[i]); + } + } + System.err.println("TEST PASSED"); } } diff --git a/jdk/test/java/rmi/server/UnicastRemoteObject/changeHostName/ChangeHostName_Stub.java b/jdk/test/java/rmi/server/UnicastRemoteObject/changeHostName/ChangeHostName_Stub.java index ff67210c4c2..f42eda7d419 100644 --- a/jdk/test/java/rmi/server/UnicastRemoteObject/changeHostName/ChangeHostName_Stub.java +++ b/jdk/test/java/rmi/server/UnicastRemoteObject/changeHostName/ChangeHostName_Stub.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -29,37 +29,37 @@ public final class ChangeHostName_Stub implements Receiver, java.rmi.Remote { private static final long serialVersionUID = 2; - + private static java.lang.reflect.Method $method_receive_0; - + static { - try { - $method_receive_0 = Receiver.class.getMethod("receive", new java.lang.Class[] {java.rmi.Remote.class}); - } catch (java.lang.NoSuchMethodException e) { - throw new java.lang.NoSuchMethodError( - "stub class initialization failed"); - } + try { + $method_receive_0 = Receiver.class.getMethod("receive", new java.lang.Class[] {java.rmi.Remote.class}); + } catch (java.lang.NoSuchMethodException e) { + throw new java.lang.NoSuchMethodError( + "stub class initialization failed"); + } } - + // constructors public ChangeHostName_Stub(java.rmi.server.RemoteRef ref) { - super(ref); + super(ref); } - + // methods from remote interfaces - + // implementation of receive(Remote) public void receive(java.rmi.Remote $param_Remote_1) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { - try { - ref.invoke(this, $method_receive_0, new java.lang.Object[] {$param_Remote_1}, 5876293363550629411L); - } catch (java.lang.RuntimeException e) { - throw e; - } catch (java.rmi.RemoteException e) { - throw e; - } catch (java.lang.Exception e) { - throw new java.rmi.UnexpectedException("undeclared checked exception", e); - } + try { + ref.invoke(this, $method_receive_0, new java.lang.Object[] {$param_Remote_1}, 5876293363550629411L); + } catch (java.lang.RuntimeException e) { + throw e; + } catch (java.rmi.RemoteException e) { + throw e; + } catch (java.lang.Exception e) { + throw new java.rmi.UnexpectedException("undeclared checked exception", e); + } } } diff --git a/jdk/test/java/rmi/server/UnicastRemoteObject/keepAliveDuringCall/KeepAliveDuringCall.java b/jdk/test/java/rmi/server/UnicastRemoteObject/keepAliveDuringCall/KeepAliveDuringCall.java index e4a41b06f52..9ea571a41c6 100644 --- a/jdk/test/java/rmi/server/UnicastRemoteObject/keepAliveDuringCall/KeepAliveDuringCall.java +++ b/jdk/test/java/rmi/server/UnicastRemoteObject/keepAliveDuringCall/KeepAliveDuringCall.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -59,83 +59,83 @@ public class KeepAliveDuringCall implements ShutdownMonitor { private boolean stillAlive = false; public void submitShutdown(Shutdown shutdown) { - synchronized (lock) { - this.shutdown = shutdown; - lock.notifyAll(); - } + synchronized (lock) { + this.shutdown = shutdown; + lock.notifyAll(); + } } public void declareStillAlive() { - synchronized (lock) { - stillAlive = true; - lock.notifyAll(); - } + synchronized (lock) { + stillAlive = true; + lock.notifyAll(); + } } public static void main(String[] args) { - System.err.println("\nRegression test for bug 4308492\n"); + System.err.println("\nRegression test for bug 4308492\n"); - KeepAliveDuringCall obj = new KeepAliveDuringCall(); + KeepAliveDuringCall obj = new KeepAliveDuringCall(); - try { - UnicastRemoteObject.exportObject(obj); - System.err.println("exported shutdown monitor"); + try { + UnicastRemoteObject.exportObject(obj); + System.err.println("exported shutdown monitor"); - Registry localRegistry = - LocateRegistry.createRegistry(TestLibrary.REGISTRY_PORT); - System.err.println("created local registry"); + Registry localRegistry = + LocateRegistry.createRegistry(TestLibrary.REGISTRY_PORT); + System.err.println("created local registry"); - localRegistry.bind(BINDING, obj); - System.err.println("bound shutdown monitor in local registry"); + localRegistry.bind(BINDING, obj); + System.err.println("bound shutdown monitor in local registry"); - System.err.println("starting remote ShutdownImpl VM..."); - (new JavaVM("ShutdownImpl")).start(); + System.err.println("starting remote ShutdownImpl VM..."); + (new JavaVM("ShutdownImpl")).start(); - Shutdown s; - synchronized (obj.lock) { - System.err.println( - "waiting for submission of object to shutdown..."); - while ((s = obj.shutdown) == null) { - obj.lock.wait(TIMEOUT); - } - if (s == null) { - throw new RuntimeException( - "TEST FAILED: timeout waiting for shutdown object " + - "to make initial contact"); - } - System.err.println("shutdown object submitted: " + s); - } + Shutdown s; + synchronized (obj.lock) { + System.err.println( + "waiting for submission of object to shutdown..."); + while ((s = obj.shutdown) == null) { + obj.lock.wait(TIMEOUT); + } + if (s == null) { + throw new RuntimeException( + "TEST FAILED: timeout waiting for shutdown object " + + "to make initial contact"); + } + System.err.println("shutdown object submitted: " + s); + } - try { - s.shutdown(); - } catch (RemoteException e) { - throw new RuntimeException( - "TEST FAILED: shutdown method threw remote exception", e); - } + try { + s.shutdown(); + } catch (RemoteException e) { + throw new RuntimeException( + "TEST FAILED: shutdown method threw remote exception", e); + } - synchronized (obj.lock) { - if (!obj.stillAlive) { - throw new RuntimeException("TEST FAILED: " + - "shutdown object not detected alive after unexport"); - } - } + synchronized (obj.lock) { + if (!obj.stillAlive) { + throw new RuntimeException("TEST FAILED: " + + "shutdown object not detected alive after unexport"); + } + } - System.err.println("TEST PASSED: " + - "shutdown object detected still alive after unexport"); + System.err.println("TEST PASSED: " + + "shutdown object detected still alive after unexport"); - } catch (Exception e) { - if (e instanceof RuntimeException) { - throw (RuntimeException) e; - } else { - throw new RuntimeException( - "TEST FAILED: unexpected exception", e); - } - } finally { - try { - UnicastRemoteObject.unexportObject(obj, true); - } catch (RemoteException e) { - } - } + } catch (Exception e) { + if (e instanceof RuntimeException) { + throw (RuntimeException) e; + } else { + throw new RuntimeException( + "TEST FAILED: unexpected exception", e); + } + } finally { + try { + UnicastRemoteObject.unexportObject(obj, true); + } catch (RemoteException e) { + } + } } } diff --git a/jdk/test/java/rmi/server/UnicastRemoteObject/keepAliveDuringCall/KeepAliveDuringCall_Stub.java b/jdk/test/java/rmi/server/UnicastRemoteObject/keepAliveDuringCall/KeepAliveDuringCall_Stub.java index d7ba21cdfdb..9583f53546b 100644 --- a/jdk/test/java/rmi/server/UnicastRemoteObject/keepAliveDuringCall/KeepAliveDuringCall_Stub.java +++ b/jdk/test/java/rmi/server/UnicastRemoteObject/keepAliveDuringCall/KeepAliveDuringCall_Stub.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -29,54 +29,54 @@ public final class KeepAliveDuringCall_Stub implements ShutdownMonitor { private static final long serialVersionUID = 2; - + private static java.lang.reflect.Method $method_declareStillAlive_0; private static java.lang.reflect.Method $method_submitShutdown_1; - + static { - try { - $method_declareStillAlive_0 = ShutdownMonitor.class.getMethod("declareStillAlive", new java.lang.Class[] {}); - $method_submitShutdown_1 = ShutdownMonitor.class.getMethod("submitShutdown", new java.lang.Class[] {Shutdown.class}); - } catch (java.lang.NoSuchMethodException e) { - throw new java.lang.NoSuchMethodError( - "stub class initialization failed"); - } + try { + $method_declareStillAlive_0 = ShutdownMonitor.class.getMethod("declareStillAlive", new java.lang.Class[] {}); + $method_submitShutdown_1 = ShutdownMonitor.class.getMethod("submitShutdown", new java.lang.Class[] {Shutdown.class}); + } catch (java.lang.NoSuchMethodException e) { + throw new java.lang.NoSuchMethodError( + "stub class initialization failed"); + } } - + // constructors public KeepAliveDuringCall_Stub(java.rmi.server.RemoteRef ref) { - super(ref); + super(ref); } - + // methods from remote interfaces - + // implementation of declareStillAlive() public void declareStillAlive() - throws java.rmi.RemoteException + throws java.rmi.RemoteException { - try { - ref.invoke(this, $method_declareStillAlive_0, null, -1562228924246272634L); - } catch (java.lang.RuntimeException e) { - throw e; - } catch (java.rmi.RemoteException e) { - throw e; - } catch (java.lang.Exception e) { - throw new java.rmi.UnexpectedException("undeclared checked exception", e); - } + try { + ref.invoke(this, $method_declareStillAlive_0, null, -1562228924246272634L); + } catch (java.lang.RuntimeException e) { + throw e; + } catch (java.rmi.RemoteException e) { + throw e; + } catch (java.lang.Exception e) { + throw new java.rmi.UnexpectedException("undeclared checked exception", e); + } } - + // implementation of submitShutdown(Shutdown) public void submitShutdown(Shutdown $param_Shutdown_1) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { - try { - ref.invoke(this, $method_submitShutdown_1, new java.lang.Object[] {$param_Shutdown_1}, 7574258166120515108L); - } catch (java.lang.RuntimeException e) { - throw e; - } catch (java.rmi.RemoteException e) { - throw e; - } catch (java.lang.Exception e) { - throw new java.rmi.UnexpectedException("undeclared checked exception", e); - } + try { + ref.invoke(this, $method_submitShutdown_1, new java.lang.Object[] {$param_Shutdown_1}, 7574258166120515108L); + } catch (java.lang.RuntimeException e) { + throw e; + } catch (java.rmi.RemoteException e) { + throw e; + } catch (java.lang.Exception e) { + throw new java.rmi.UnexpectedException("undeclared checked exception", e); + } } } diff --git a/jdk/test/java/rmi/server/UnicastRemoteObject/keepAliveDuringCall/Shutdown.java b/jdk/test/java/rmi/server/UnicastRemoteObject/keepAliveDuringCall/Shutdown.java index d3aa3283069..4dadbe51b2e 100644 --- a/jdk/test/java/rmi/server/UnicastRemoteObject/keepAliveDuringCall/Shutdown.java +++ b/jdk/test/java/rmi/server/UnicastRemoteObject/keepAliveDuringCall/Shutdown.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * diff --git a/jdk/test/java/rmi/server/UnicastRemoteObject/keepAliveDuringCall/ShutdownImpl.java b/jdk/test/java/rmi/server/UnicastRemoteObject/keepAliveDuringCall/ShutdownImpl.java index 39952ed5f2c..32c0c118b25 100644 --- a/jdk/test/java/rmi/server/UnicastRemoteObject/keepAliveDuringCall/ShutdownImpl.java +++ b/jdk/test/java/rmi/server/UnicastRemoteObject/keepAliveDuringCall/ShutdownImpl.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -32,58 +32,58 @@ import java.rmi.server.UnicastRemoteObject; public class ShutdownImpl implements Shutdown { - private static Remote impl; // rooted here to prevent GC + private static Remote impl; // rooted here to prevent GC private final ShutdownMonitor monitor; private ShutdownImpl(ShutdownMonitor monitor) { - this.monitor = monitor; + this.monitor = monitor; } public void shutdown() { - try { - System.err.println( - "(ShutdownImpl.shutdown) shutdown method invoked:"); + try { + System.err.println( + "(ShutdownImpl.shutdown) shutdown method invoked:"); - UnicastRemoteObject.unexportObject(this, true); - System.err.println( - "(ShutdownImpl.shutdown) shutdown object unexported"); + UnicastRemoteObject.unexportObject(this, true); + System.err.println( + "(ShutdownImpl.shutdown) shutdown object unexported"); - Thread.sleep(500); - System.err.println("(ShutDownImpl.shutdown) FEE"); - Thread.sleep(500); - System.err.println("(ShutDownImpl.shutdown) FIE"); - Thread.sleep(500); - System.err.println("(ShutDownImpl.shutdown) FOE"); - Thread.sleep(500); - System.err.println("(ShutDownImpl.shutdown) FOO"); + Thread.sleep(500); + System.err.println("(ShutDownImpl.shutdown) FEE"); + Thread.sleep(500); + System.err.println("(ShutDownImpl.shutdown) FIE"); + Thread.sleep(500); + System.err.println("(ShutDownImpl.shutdown) FOE"); + Thread.sleep(500); + System.err.println("(ShutDownImpl.shutdown) FOO"); - monitor.declareStillAlive(); - System.err.println("(ShutDownImpl.shutdown) still alive!"); - } catch (Exception e) { - throw new RuntimeException( - "unexpected exception occurred in shutdown method", e); - } + monitor.declareStillAlive(); + System.err.println("(ShutDownImpl.shutdown) still alive!"); + } catch (Exception e) { + throw new RuntimeException( + "unexpected exception occurred in shutdown method", e); + } } public static void main(String[] args) { - try { - Registry registry = - LocateRegistry.getRegistry("", TestLibrary.REGISTRY_PORT); - ShutdownMonitor monitor = (ShutdownMonitor) - registry.lookup(KeepAliveDuringCall.BINDING); - System.err.println("(ShutdownImpl) retrieved shutdown monitor"); + try { + Registry registry = + LocateRegistry.getRegistry("", TestLibrary.REGISTRY_PORT); + ShutdownMonitor monitor = (ShutdownMonitor) + registry.lookup(KeepAliveDuringCall.BINDING); + System.err.println("(ShutdownImpl) retrieved shutdown monitor"); - impl = new ShutdownImpl(monitor); - Shutdown stub = (Shutdown) UnicastRemoteObject.exportObject(impl); - System.err.println("(ShutdownImpl) exported shutdown object"); + impl = new ShutdownImpl(monitor); + Shutdown stub = (Shutdown) UnicastRemoteObject.exportObject(impl); + System.err.println("(ShutdownImpl) exported shutdown object"); - monitor.submitShutdown(stub); - System.err.println("(ShutdownImpl) submitted shutdown object"); + monitor.submitShutdown(stub); + System.err.println("(ShutdownImpl) submitted shutdown object"); - } catch (Exception e) { - System.err.println("(ShutdownImpl) TEST SUBPROCESS FAILURE:"); - e.printStackTrace(); - } + } catch (Exception e) { + System.err.println("(ShutdownImpl) TEST SUBPROCESS FAILURE:"); + e.printStackTrace(); + } } } diff --git a/jdk/test/java/rmi/server/UnicastRemoteObject/keepAliveDuringCall/ShutdownImpl_Stub.java b/jdk/test/java/rmi/server/UnicastRemoteObject/keepAliveDuringCall/ShutdownImpl_Stub.java index 0540a634574..97c62ca33f8 100644 --- a/jdk/test/java/rmi/server/UnicastRemoteObject/keepAliveDuringCall/ShutdownImpl_Stub.java +++ b/jdk/test/java/rmi/server/UnicastRemoteObject/keepAliveDuringCall/ShutdownImpl_Stub.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -29,37 +29,37 @@ public final class ShutdownImpl_Stub implements Shutdown { private static final long serialVersionUID = 2; - + private static java.lang.reflect.Method $method_shutdown_0; - + static { - try { - $method_shutdown_0 = Shutdown.class.getMethod("shutdown", new java.lang.Class[] {}); - } catch (java.lang.NoSuchMethodException e) { - throw new java.lang.NoSuchMethodError( - "stub class initialization failed"); - } + try { + $method_shutdown_0 = Shutdown.class.getMethod("shutdown", new java.lang.Class[] {}); + } catch (java.lang.NoSuchMethodException e) { + throw new java.lang.NoSuchMethodError( + "stub class initialization failed"); + } } - + // constructors public ShutdownImpl_Stub(java.rmi.server.RemoteRef ref) { - super(ref); + super(ref); } - + // methods from remote interfaces - + // implementation of shutdown() public void shutdown() - throws java.rmi.RemoteException + throws java.rmi.RemoteException { - try { - ref.invoke(this, $method_shutdown_0, null, -7207851917985848402L); - } catch (java.lang.RuntimeException e) { - throw e; - } catch (java.rmi.RemoteException e) { - throw e; - } catch (java.lang.Exception e) { - throw new java.rmi.UnexpectedException("undeclared checked exception", e); - } + try { + ref.invoke(this, $method_shutdown_0, null, -7207851917985848402L); + } catch (java.lang.RuntimeException e) { + throw e; + } catch (java.rmi.RemoteException e) { + throw e; + } catch (java.lang.Exception e) { + throw new java.rmi.UnexpectedException("undeclared checked exception", e); + } } } diff --git a/jdk/test/java/rmi/server/UnicastRemoteObject/keepAliveDuringCall/ShutdownMonitor.java b/jdk/test/java/rmi/server/UnicastRemoteObject/keepAliveDuringCall/ShutdownMonitor.java index 45c4deb0c76..29f630b1fe0 100644 --- a/jdk/test/java/rmi/server/UnicastRemoteObject/keepAliveDuringCall/ShutdownMonitor.java +++ b/jdk/test/java/rmi/server/UnicastRemoteObject/keepAliveDuringCall/ShutdownMonitor.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * diff --git a/jdk/test/java/rmi/server/UnicastRemoteObject/marshalAfterUnexport/MarshalAfterUnexport.java b/jdk/test/java/rmi/server/UnicastRemoteObject/marshalAfterUnexport/MarshalAfterUnexport.java index 10536f2fe13..0fb37c62209 100644 --- a/jdk/test/java/rmi/server/UnicastRemoteObject/marshalAfterUnexport/MarshalAfterUnexport.java +++ b/jdk/test/java/rmi/server/UnicastRemoteObject/marshalAfterUnexport/MarshalAfterUnexport.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -53,35 +53,35 @@ public class MarshalAfterUnexport } public static void main(String[] args) throws Exception { - Remote impl2 = null; - try { - Remote impl = new MarshalAfterUnexport(); - System.err.println("created impl extending URO: " + impl); + Remote impl2 = null; + try { + Remote impl = new MarshalAfterUnexport(); + System.err.println("created impl extending URO: " + impl); - Receiver stub = (Receiver) RemoteObject.toStub(impl); - System.err.println("stub for impl: " + stub); + Receiver stub = (Receiver) RemoteObject.toStub(impl); + System.err.println("stub for impl: " + stub); - UnicastRemoteObject.unexportObject(impl, true); - System.err.println("unexported impl"); + UnicastRemoteObject.unexportObject(impl, true); + System.err.println("unexported impl"); - impl2 = new MarshalAfterUnexport(); - Receiver stub2 = (Receiver) RemoteObject.toStub(impl2); + impl2 = new MarshalAfterUnexport(); + Receiver stub2 = (Receiver) RemoteObject.toStub(impl2); - System.err.println("marshalling unexported object:"); - MarshalledObject mobj = new MarshalledObject(impl); + System.err.println("marshalling unexported object:"); + MarshalledObject mobj = new MarshalledObject(impl); - System.err.println("passing unexported object via RMI-JRMP:"); - stub2.receive(stub); + System.err.println("passing unexported object via RMI-JRMP:"); + stub2.receive(stub); - System.err.println("TEST PASSED"); - } finally { - if (impl2 != null) { - try { - UnicastRemoteObject.unexportObject(impl2, true); - } catch (Throwable t) { - } - } - } + System.err.println("TEST PASSED"); + } finally { + if (impl2 != null) { + try { + UnicastRemoteObject.unexportObject(impl2, true); + } catch (Throwable t) { + } + } + } } } diff --git a/jdk/test/java/rmi/server/UnicastRemoteObject/marshalAfterUnexport/MarshalAfterUnexport2.java b/jdk/test/java/rmi/server/UnicastRemoteObject/marshalAfterUnexport/MarshalAfterUnexport2.java index f7d1e575d66..7e8d3592872 100644 --- a/jdk/test/java/rmi/server/UnicastRemoteObject/marshalAfterUnexport/MarshalAfterUnexport2.java +++ b/jdk/test/java/rmi/server/UnicastRemoteObject/marshalAfterUnexport/MarshalAfterUnexport2.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -49,47 +49,47 @@ public class MarshalAfterUnexport2 implements Receiver { public MarshalAfterUnexport2() throws RemoteException { - super(0, null, null); + super(0, null, null); } public void receive(Remote obj) { } public static void main(String[] args) throws Exception { - - System.err.println("\nRegression test for bug 4513223\n"); - - Remote impl2 = null; - try { - Remote impl = new MarshalAfterUnexport2(); - System.err.println( - "created impl extending URO (with a UnicastServerRef2): " + - impl); - Receiver stub = (Receiver) RemoteObject.toStub(impl); - System.err.println("stub for impl: " + stub); + System.err.println("\nRegression test for bug 4513223\n"); - UnicastRemoteObject.unexportObject(impl, true); - System.err.println("unexported impl"); + Remote impl2 = null; + try { + Remote impl = new MarshalAfterUnexport2(); + System.err.println( + "created impl extending URO (with a UnicastServerRef2): " + + impl); - impl2 = new MarshalAfterUnexport2(); - Receiver stub2 = (Receiver) RemoteObject.toStub(impl2); + Receiver stub = (Receiver) RemoteObject.toStub(impl); + System.err.println("stub for impl: " + stub); - System.err.println("marshalling unexported object:"); - MarshalledObject mobj = new MarshalledObject(impl); + UnicastRemoteObject.unexportObject(impl, true); + System.err.println("unexported impl"); - System.err.println("passing unexported object via RMI-JRMP:"); - stub2.receive(stub); + impl2 = new MarshalAfterUnexport2(); + Receiver stub2 = (Receiver) RemoteObject.toStub(impl2); - System.err.println("TEST PASSED"); - } finally { - if (impl2 != null) { - try { - UnicastRemoteObject.unexportObject(impl2, true); - } catch (Throwable t) { - } - } - } + System.err.println("marshalling unexported object:"); + MarshalledObject mobj = new MarshalledObject(impl); + + System.err.println("passing unexported object via RMI-JRMP:"); + stub2.receive(stub); + + System.err.println("TEST PASSED"); + } finally { + if (impl2 != null) { + try { + UnicastRemoteObject.unexportObject(impl2, true); + } catch (Throwable t) { + } + } + } } } diff --git a/jdk/test/java/rmi/server/UnicastRemoteObject/marshalAfterUnexport/MarshalAfterUnexport2_Stub.java b/jdk/test/java/rmi/server/UnicastRemoteObject/marshalAfterUnexport/MarshalAfterUnexport2_Stub.java index b122813d559..bbefd5248aa 100644 --- a/jdk/test/java/rmi/server/UnicastRemoteObject/marshalAfterUnexport/MarshalAfterUnexport2_Stub.java +++ b/jdk/test/java/rmi/server/UnicastRemoteObject/marshalAfterUnexport/MarshalAfterUnexport2_Stub.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -29,37 +29,37 @@ public final class MarshalAfterUnexport2_Stub implements Receiver, java.rmi.Remote { private static final long serialVersionUID = 2; - + private static java.lang.reflect.Method $method_receive_0; - + static { - try { - $method_receive_0 = Receiver.class.getMethod("receive", new java.lang.Class[] {java.rmi.Remote.class}); - } catch (java.lang.NoSuchMethodException e) { - throw new java.lang.NoSuchMethodError( - "stub class initialization failed"); - } + try { + $method_receive_0 = Receiver.class.getMethod("receive", new java.lang.Class[] {java.rmi.Remote.class}); + } catch (java.lang.NoSuchMethodException e) { + throw new java.lang.NoSuchMethodError( + "stub class initialization failed"); + } } - + // constructors public MarshalAfterUnexport2_Stub(java.rmi.server.RemoteRef ref) { - super(ref); + super(ref); } - + // methods from remote interfaces - + // implementation of receive(Remote) public void receive(java.rmi.Remote $param_Remote_1) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { - try { - ref.invoke(this, $method_receive_0, new java.lang.Object[] {$param_Remote_1}, 5876293363550629411L); - } catch (java.lang.RuntimeException e) { - throw e; - } catch (java.rmi.RemoteException e) { - throw e; - } catch (java.lang.Exception e) { - throw new java.rmi.UnexpectedException("undeclared checked exception", e); - } + try { + ref.invoke(this, $method_receive_0, new java.lang.Object[] {$param_Remote_1}, 5876293363550629411L); + } catch (java.lang.RuntimeException e) { + throw e; + } catch (java.rmi.RemoteException e) { + throw e; + } catch (java.lang.Exception e) { + throw new java.rmi.UnexpectedException("undeclared checked exception", e); + } } } diff --git a/jdk/test/java/rmi/server/UnicastRemoteObject/marshalAfterUnexport/MarshalAfterUnexport_Stub.java b/jdk/test/java/rmi/server/UnicastRemoteObject/marshalAfterUnexport/MarshalAfterUnexport_Stub.java index 15022b4d04e..535fffa00e1 100644 --- a/jdk/test/java/rmi/server/UnicastRemoteObject/marshalAfterUnexport/MarshalAfterUnexport_Stub.java +++ b/jdk/test/java/rmi/server/UnicastRemoteObject/marshalAfterUnexport/MarshalAfterUnexport_Stub.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -29,37 +29,37 @@ public final class MarshalAfterUnexport_Stub implements Receiver, java.rmi.Remote { private static final long serialVersionUID = 2; - + private static java.lang.reflect.Method $method_receive_0; - + static { - try { - $method_receive_0 = Receiver.class.getMethod("receive", new java.lang.Class[] {java.rmi.Remote.class}); - } catch (java.lang.NoSuchMethodException e) { - throw new java.lang.NoSuchMethodError( - "stub class initialization failed"); - } + try { + $method_receive_0 = Receiver.class.getMethod("receive", new java.lang.Class[] {java.rmi.Remote.class}); + } catch (java.lang.NoSuchMethodException e) { + throw new java.lang.NoSuchMethodError( + "stub class initialization failed"); + } } - + // constructors public MarshalAfterUnexport_Stub(java.rmi.server.RemoteRef ref) { - super(ref); + super(ref); } - + // methods from remote interfaces - + // implementation of receive(Remote) public void receive(java.rmi.Remote $param_Remote_1) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { - try { - ref.invoke(this, $method_receive_0, new java.lang.Object[] {$param_Remote_1}, 5876293363550629411L); - } catch (java.lang.RuntimeException e) { - throw e; - } catch (java.rmi.RemoteException e) { - throw e; - } catch (java.lang.Exception e) { - throw new java.rmi.UnexpectedException("undeclared checked exception", e); - } + try { + ref.invoke(this, $method_receive_0, new java.lang.Object[] {$param_Remote_1}, 5876293363550629411L); + } catch (java.lang.RuntimeException e) { + throw e; + } catch (java.rmi.RemoteException e) { + throw e; + } catch (java.lang.Exception e) { + throw new java.rmi.UnexpectedException("undeclared checked exception", e); + } } } diff --git a/jdk/test/java/rmi/server/UnicastRemoteObject/unexportObject/Ping.java b/jdk/test/java/rmi/server/UnicastRemoteObject/unexportObject/Ping.java index 2e88ab924cf..682915cfcf2 100644 --- a/jdk/test/java/rmi/server/UnicastRemoteObject/unexportObject/Ping.java +++ b/jdk/test/java/rmi/server/UnicastRemoteObject/unexportObject/Ping.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -26,4 +26,3 @@ import java.rmi.*; public interface Ping extends Remote { public void ping() throws RemoteException; } - diff --git a/jdk/test/java/rmi/server/UnicastRemoteObject/unexportObject/UnexportLeak.java b/jdk/test/java/rmi/server/UnicastRemoteObject/unexportObject/UnexportLeak.java index e40f19e50cf..de1cef78188 100644 --- a/jdk/test/java/rmi/server/UnicastRemoteObject/unexportObject/UnexportLeak.java +++ b/jdk/test/java/rmi/server/UnicastRemoteObject/unexportObject/UnexportLeak.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -24,7 +24,7 @@ /* @test * @bug 4331349 * @summary synopsis: unexporting doesn't guarantee that DGC will - * let go of remote object + * let go of remote object * * @author Ann Wollrath * @@ -40,36 +40,36 @@ import java.rmi.server.*; import java.rmi.registry.*; public class UnexportLeak implements Ping { - + private static int PORT = 2006; public void ping() { } public static void main(String[] args) { - try { - System.err.println("\nRegression test for bug 4331349\n"); - LocateRegistry.createRegistry(PORT); - Remote obj = new UnexportLeak(); - WeakReference wr = new WeakReference(obj); - UnicastRemoteObject.exportObject(obj); - LocateRegistry.getRegistry(PORT).rebind("UnexportLeak", obj); - UnicastRemoteObject.unexportObject(obj, true); - obj = null; - flushRefs(); - if (wr.get() != null) { - System.err.println("FAILED: unexported object not collected"); - throw new RuntimeException( - "FAILED: unexported object not collected"); - } else { - System.err.println("PASSED: unexported object collected"); - } - } catch (RemoteException e) { - System.err.println( - "FAILED: RemoteException encountered: " + e.getMessage()); - e.printStackTrace(); - throw new RuntimeException("FAILED: RemoteException encountered"); - } + try { + System.err.println("\nRegression test for bug 4331349\n"); + LocateRegistry.createRegistry(PORT); + Remote obj = new UnexportLeak(); + WeakReference wr = new WeakReference(obj); + UnicastRemoteObject.exportObject(obj); + LocateRegistry.getRegistry(PORT).rebind("UnexportLeak", obj); + UnicastRemoteObject.unexportObject(obj, true); + obj = null; + flushRefs(); + if (wr.get() != null) { + System.err.println("FAILED: unexported object not collected"); + throw new RuntimeException( + "FAILED: unexported object not collected"); + } else { + System.err.println("PASSED: unexported object collected"); + } + } catch (RemoteException e) { + System.err.println( + "FAILED: RemoteException encountered: " + e.getMessage()); + e.printStackTrace(); + throw new RuntimeException("FAILED: RemoteException encountered"); + } } /** @@ -77,15 +77,13 @@ public class UnexportLeak implements Ping { * will be cleared. */ private static void flushRefs() { - java.util.Vector chain = new java.util.Vector(); - try { - while (true) { - int[] hungry = new int[65536]; - chain.addElement(hungry); - } - } catch (OutOfMemoryError e) { - } + java.util.Vector chain = new java.util.Vector(); + try { + while (true) { + int[] hungry = new int[65536]; + chain.addElement(hungry); + } + } catch (OutOfMemoryError e) { + } } } - - diff --git a/jdk/test/java/rmi/server/UnicastRemoteObject/unexportObject/UnexportLeak_Stub.java b/jdk/test/java/rmi/server/UnicastRemoteObject/unexportObject/UnexportLeak_Stub.java index 1f7ab308c20..56102aa54fe 100644 --- a/jdk/test/java/rmi/server/UnicastRemoteObject/unexportObject/UnexportLeak_Stub.java +++ b/jdk/test/java/rmi/server/UnicastRemoteObject/unexportObject/UnexportLeak_Stub.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -29,37 +29,37 @@ public final class UnexportLeak_Stub implements Ping { private static final long serialVersionUID = 2; - + private static java.lang.reflect.Method $method_ping_0; - + static { - try { - $method_ping_0 = Ping.class.getMethod("ping", new java.lang.Class[] {}); - } catch (java.lang.NoSuchMethodException e) { - throw new java.lang.NoSuchMethodError( - "stub class initialization failed"); - } + try { + $method_ping_0 = Ping.class.getMethod("ping", new java.lang.Class[] {}); + } catch (java.lang.NoSuchMethodException e) { + throw new java.lang.NoSuchMethodError( + "stub class initialization failed"); + } } - + // constructors public UnexportLeak_Stub(java.rmi.server.RemoteRef ref) { - super(ref); + super(ref); } - + // methods from remote interfaces - + // implementation of ping() public void ping() - throws java.rmi.RemoteException + throws java.rmi.RemoteException { - try { - ref.invoke(this, $method_ping_0, null, 5866401369815527589L); - } catch (java.lang.RuntimeException e) { - throw e; - } catch (java.rmi.RemoteException e) { - throw e; - } catch (java.lang.Exception e) { - throw new java.rmi.UnexpectedException("undeclared checked exception", e); - } + try { + ref.invoke(this, $method_ping_0, null, 5866401369815527589L); + } catch (java.lang.RuntimeException e) { + throw e; + } catch (java.rmi.RemoteException e) { + throw e; + } catch (java.lang.Exception e) { + throw new java.rmi.UnexpectedException("undeclared checked exception", e); + } } } diff --git a/jdk/test/java/rmi/server/UnicastRemoteObject/useDynamicProxies/UseDynamicProxies.java b/jdk/test/java/rmi/server/UnicastRemoteObject/useDynamicProxies/UseDynamicProxies.java index bec4e954f80..62b0ae9339b 100644 --- a/jdk/test/java/rmi/server/UnicastRemoteObject/useDynamicProxies/UseDynamicProxies.java +++ b/jdk/test/java/rmi/server/UnicastRemoteObject/useDynamicProxies/UseDynamicProxies.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 2003 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -43,75 +43,75 @@ public class UseDynamicProxies implements RemoteInterface { public Object passObject(Object obj) { - return obj; + return obj; } public int passInt(int x) { - return x; + return x; } public String passString(String string) { - return string; + return string; } public static void main(String[] args) throws Exception { - - RemoteInterface server = null; - RemoteInterface proxy = null; - - try { - System.setProperty("java.rmi.server.ignoreStubClasses", args[0]); - boolean ignoreStubClasses = Boolean.parseBoolean(args[0]); - if (System.getSecurityManager() == null) { - System.setSecurityManager(new SecurityManager()); - } + RemoteInterface server = null; + RemoteInterface proxy = null; - System.err.println("export object"); - server = new UseDynamicProxies(); - proxy = - (RemoteInterface) UnicastRemoteObject.exportObject(server, 0); + try { + System.setProperty("java.rmi.server.ignoreStubClasses", args[0]); + boolean ignoreStubClasses = Boolean.parseBoolean(args[0]); - System.err.println("proxy = " + proxy); - if (ignoreStubClasses) { - if (!Proxy.isProxyClass(proxy.getClass())) { - throw new RuntimeException( - "server proxy is not a dynamic proxy"); - } - if (!(Proxy.getInvocationHandler(proxy) instanceof - RemoteObjectInvocationHandler)) - { - throw new RuntimeException("invalid invocation handler"); - } - - } else if (!(proxy instanceof RemoteStub)) { - throw new RuntimeException( - "server proxy is not a RemoteStub"); - } + if (System.getSecurityManager() == null) { + System.setSecurityManager(new SecurityManager()); + } - System.err.println("invoke methods"); - Object obj = proxy.passObject(proxy); - if (!proxy.equals(obj)) { - throw new RuntimeException("returned proxy not equal"); - } + System.err.println("export object"); + server = new UseDynamicProxies(); + proxy = + (RemoteInterface) UnicastRemoteObject.exportObject(server, 0); - int x = proxy.passInt(53); - if (x != 53) { - throw new RuntimeException("returned int not equal"); - } + System.err.println("proxy = " + proxy); + if (ignoreStubClasses) { + if (!Proxy.isProxyClass(proxy.getClass())) { + throw new RuntimeException( + "server proxy is not a dynamic proxy"); + } + if (!(Proxy.getInvocationHandler(proxy) instanceof + RemoteObjectInvocationHandler)) + { + throw new RuntimeException("invalid invocation handler"); + } - String string = proxy.passString("test"); - if (!string.equals("test")) { - throw new RuntimeException("returned string not equal"); - } - - System.err.println("TEST PASSED"); - - } finally { - if (proxy != null) { - UnicastRemoteObject.unexportObject(server, true); - } - } + } else if (!(proxy instanceof RemoteStub)) { + throw new RuntimeException( + "server proxy is not a RemoteStub"); + } + + System.err.println("invoke methods"); + Object obj = proxy.passObject(proxy); + if (!proxy.equals(obj)) { + throw new RuntimeException("returned proxy not equal"); + } + + int x = proxy.passInt(53); + if (x != 53) { + throw new RuntimeException("returned int not equal"); + } + + String string = proxy.passString("test"); + if (!string.equals("test")) { + throw new RuntimeException("returned string not equal"); + } + + System.err.println("TEST PASSED"); + + } finally { + if (proxy != null) { + UnicastRemoteObject.unexportObject(server, true); + } + } } } diff --git a/jdk/test/java/rmi/server/UnicastRemoteObject/useDynamicProxies/UseDynamicProxies_Stub.java b/jdk/test/java/rmi/server/UnicastRemoteObject/useDynamicProxies/UseDynamicProxies_Stub.java index 549c2396ab8..b567c29ebd6 100644 --- a/jdk/test/java/rmi/server/UnicastRemoteObject/useDynamicProxies/UseDynamicProxies_Stub.java +++ b/jdk/test/java/rmi/server/UnicastRemoteObject/useDynamicProxies/UseDynamicProxies_Stub.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 2003 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -29,74 +29,74 @@ public final class UseDynamicProxies_Stub implements RemoteInterface { private static final long serialVersionUID = 2; - + private static java.lang.reflect.Method $method_passInt_0; private static java.lang.reflect.Method $method_passObject_1; private static java.lang.reflect.Method $method_passString_2; - + static { - try { - $method_passInt_0 = RemoteInterface.class.getMethod("passInt", new java.lang.Class[] {int.class}); - $method_passObject_1 = RemoteInterface.class.getMethod("passObject", new java.lang.Class[] {java.lang.Object.class}); - $method_passString_2 = RemoteInterface.class.getMethod("passString", new java.lang.Class[] {java.lang.String.class}); - } catch (java.lang.NoSuchMethodException e) { - throw new java.lang.NoSuchMethodError( - "stub class initialization failed"); - } + try { + $method_passInt_0 = RemoteInterface.class.getMethod("passInt", new java.lang.Class[] {int.class}); + $method_passObject_1 = RemoteInterface.class.getMethod("passObject", new java.lang.Class[] {java.lang.Object.class}); + $method_passString_2 = RemoteInterface.class.getMethod("passString", new java.lang.Class[] {java.lang.String.class}); + } catch (java.lang.NoSuchMethodException e) { + throw new java.lang.NoSuchMethodError( + "stub class initialization failed"); + } } - + // constructors public UseDynamicProxies_Stub(java.rmi.server.RemoteRef ref) { - super(ref); + super(ref); } - + // methods from remote interfaces - + // implementation of passInt(int) public int passInt(int $param_int_1) - throws java.io.IOException + throws java.io.IOException { - try { - Object $result = ref.invoke(this, $method_passInt_0, new java.lang.Object[] {new java.lang.Integer($param_int_1)}, 8655249712495061761L); - return ((java.lang.Integer) $result).intValue(); - } catch (java.lang.RuntimeException e) { - throw e; - } catch (java.io.IOException e) { - throw e; - } catch (java.lang.Exception e) { - throw new java.rmi.UnexpectedException("undeclared checked exception", e); - } + try { + Object $result = ref.invoke(this, $method_passInt_0, new java.lang.Object[] {new java.lang.Integer($param_int_1)}, 8655249712495061761L); + return ((java.lang.Integer) $result).intValue(); + } catch (java.lang.RuntimeException e) { + throw e; + } catch (java.io.IOException e) { + throw e; + } catch (java.lang.Exception e) { + throw new java.rmi.UnexpectedException("undeclared checked exception", e); + } } - + // implementation of passObject(Object) public java.lang.Object passObject(java.lang.Object $param_Object_1) - throws java.io.IOException + throws java.io.IOException { - try { - Object $result = ref.invoke(this, $method_passObject_1, new java.lang.Object[] {$param_Object_1}, 3074202549763602823L); - return ((java.lang.Object) $result); - } catch (java.lang.RuntimeException e) { - throw e; - } catch (java.io.IOException e) { - throw e; - } catch (java.lang.Exception e) { - throw new java.rmi.UnexpectedException("undeclared checked exception", e); - } + try { + Object $result = ref.invoke(this, $method_passObject_1, new java.lang.Object[] {$param_Object_1}, 3074202549763602823L); + return ((java.lang.Object) $result); + } catch (java.lang.RuntimeException e) { + throw e; + } catch (java.io.IOException e) { + throw e; + } catch (java.lang.Exception e) { + throw new java.rmi.UnexpectedException("undeclared checked exception", e); + } } - + // implementation of passString(String) public java.lang.String passString(java.lang.String $param_String_1) - throws java.io.IOException + throws java.io.IOException { - try { - Object $result = ref.invoke(this, $method_passString_2, new java.lang.Object[] {$param_String_1}, 6627880292288702000L); - return ((java.lang.String) $result); - } catch (java.lang.RuntimeException e) { - throw e; - } catch (java.io.IOException e) { - throw e; - } catch (java.lang.Exception e) { - throw new java.rmi.UnexpectedException("undeclared checked exception", e); - } + try { + Object $result = ref.invoke(this, $method_passString_2, new java.lang.Object[] {$param_String_1}, 6627880292288702000L); + return ((java.lang.String) $result); + } catch (java.lang.RuntimeException e) { + throw e; + } catch (java.io.IOException e) { + throw e; + } catch (java.lang.Exception e) { + throw new java.rmi.UnexpectedException("undeclared checked exception", e); + } } } diff --git a/jdk/test/java/rmi/server/Unmarshal/checkUnmarshalOnStopThread/CheckUnmarshalOnStopThread.java b/jdk/test/java/rmi/server/Unmarshal/checkUnmarshalOnStopThread/CheckUnmarshalOnStopThread.java index e4634841305..a12af61e4d7 100644 --- a/jdk/test/java/rmi/server/Unmarshal/checkUnmarshalOnStopThread/CheckUnmarshalOnStopThread.java +++ b/jdk/test/java/rmi/server/Unmarshal/checkUnmarshalOnStopThread/CheckUnmarshalOnStopThread.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1998-1999 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -22,7 +22,7 @@ */ /* @test - * @bug 4118600 + * @bug 4118600 * @summary RMI UnmarshallException, interaction on stopping a thread. * * @bug 4177704 @@ -35,7 +35,7 @@ * @build CheckUnmarshall PoisonPill RuntimeExceptionParameter * @build CheckUnmarshalOnStopThread * @build CheckUnmarshalOnStopThread_Stub - * @run main/othervm/timeout=480 CheckUnmarshalOnStopThread + * @run main/othervm/timeout=480 CheckUnmarshalOnStopThread */ import java.rmi.*; @@ -44,7 +44,7 @@ import java.io.*; import java.rmi.registry.*; /** - * Description for 4118600: + * Description for 4118600: * * If an rmi call thread is stopped while unmarshalling a return * value), java.lang.ThreadDeath will be thrown during @@ -77,8 +77,8 @@ import java.rmi.registry.*; * occur. This test is only written to track UnmarshalExceptions; * success/failure does not depend on other types of problems. * - * Description for 4177704: - * + * Description for 4177704: + * * Similar situation as for 4177704 except that instead of just * ensuring that RMI properly handles Errors, the second part of the * test ensures that RMI deals with RuntimeExceptions correctly. @@ -88,110 +88,110 @@ import java.rmi.registry.*; * parameters. An object that throws a RuntimeException in its * writeObject method helps to carry out this part of the test. */ -public class CheckUnmarshalOnStopThread - extends UnicastRemoteObject - implements CheckUnmarshal +public class CheckUnmarshalOnStopThread + extends UnicastRemoteObject + implements CheckUnmarshal { final static int RUNTIME_PILL = 1; public static int typeToThrow = 0; /* - * remote object implementation + * remote object implementation */ CheckUnmarshalOnStopThread() throws RemoteException { } public PoisonPill getPoisonPill() throws RemoteException { - return new PoisonPill(new Integer(0)); + return new PoisonPill(new Integer(0)); } public Object ping() throws RemoteException { - return (Object) new Integer(0); + return (Object) new Integer(0); } public void passRuntimeExceptionParameter( - RuntimeExceptionParameter rep) throws RemoteException + RuntimeExceptionParameter rep) throws RemoteException { - // will never be called + // will never be called } public static void main(String [] args) { - Object dummy = new Object(); - CheckUnmarshal cu = null; - CheckUnmarshalOnStopThread cuonst = null; + Object dummy = new Object(); + CheckUnmarshal cu = null; + CheckUnmarshalOnStopThread cuonst = null; - System.err.println("\nregression test for bugs: " + - "4118600 and 4177704\n"); + System.err.println("\nregression test for bugs: " + + "4118600 and 4177704\n"); - try { - cuonst = new CheckUnmarshalOnStopThread(); - cu = (CheckUnmarshal) UnicastRemoteObject.toStub(cuonst); + try { + cuonst = new CheckUnmarshalOnStopThread(); + cu = (CheckUnmarshal) UnicastRemoteObject.toStub(cuonst); - // make sure that RMI will free connections appropriately - // under several situations: + // make sure that RMI will free connections appropriately + // under several situations: - // when Errors are thrown during parameter unmarshalling - System.err.println("testing to see if RMI will handle errors"); - ensureConnectionsAreFreed(cu, true); + // when Errors are thrown during parameter unmarshalling + System.err.println("testing to see if RMI will handle errors"); + ensureConnectionsAreFreed(cu, true); - // when RuntimeExceptions are thrown during parameter unmarshalling - System.err.println("testing to see if RMI will handle " + - "runtime exceptions"); - typeToThrow = RUNTIME_PILL; - ensureConnectionsAreFreed(cu, true); + // when RuntimeExceptions are thrown during parameter unmarshalling + System.err.println("testing to see if RMI will handle " + + "runtime exceptions"); + typeToThrow = RUNTIME_PILL; + ensureConnectionsAreFreed(cu, true); - // when RuntimeExceptions are thrown during parameter marshalling - System.err.println("testing to see if RMI will handle " + - "runtime exceptions thrown during " + - "parameter marshalling"); - ensureConnectionsAreFreed(cu, false); + // when RuntimeExceptions are thrown during parameter marshalling + System.err.println("testing to see if RMI will handle " + + "runtime exceptions thrown during " + + "parameter marshalling"); + ensureConnectionsAreFreed(cu, false); - System.err.println - ("\nsuccess: CheckUnmarshalOnStopThread test passed "); + System.err.println + ("\nsuccess: CheckUnmarshalOnStopThread test passed "); - } catch (Exception e) { - TestLibrary.bomb(e); - } finally { - cu = null; - deactivate(cuonst); - } + } catch (Exception e) { + TestLibrary.bomb(e); + } finally { + cu = null; + deactivate(cuonst); + } } - - static void ensureConnectionsAreFreed(CheckUnmarshal cu, boolean getPill) - throws Exception + + static void ensureConnectionsAreFreed(CheckUnmarshal cu, boolean getPill) + throws Exception { - // invoke a remote call that will corrupt a call connection - // that will not be freed (if the bug is not fixed) + // invoke a remote call that will corrupt a call connection + // that will not be freed (if the bug is not fixed) - for (int i = 0 ; i < 250 ; i++) { - try { - Object test = cu.ping(); - if (getPill) { - cu.getPoisonPill(); - } else { - cu.passRuntimeExceptionParameter( - new RuntimeExceptionParameter()); - } - } catch (Error e) { - // expect an Error from call unmarshalling, ignore it - } catch (RuntimeException e) { - // " RuntimeException " - } - } + for (int i = 0 ; i < 250 ; i++) { + try { + Object test = cu.ping(); + if (getPill) { + cu.getPoisonPill(); + } else { + cu.passRuntimeExceptionParameter( + new RuntimeExceptionParameter()); + } + } catch (Error e) { + // expect an Error from call unmarshalling, ignore it + } catch (RuntimeException e) { + // " RuntimeException " + } + } - System.err.println("remote calls passed, received no " + - "unmarshal exceptions\n\n"); + System.err.println("remote calls passed, received no " + + "unmarshal exceptions\n\n"); } static void deactivate(RemoteServer r) { - // make sure that the object goes away - try { - System.err.println("deactivating object."); - UnicastRemoteObject.unexportObject(r, true); - } catch (Exception e) { - e.getMessage(); - e.printStackTrace(); - } + // make sure that the object goes away + try { + System.err.println("deactivating object."); + UnicastRemoteObject.unexportObject(r, true); + } catch (Exception e) { + e.getMessage(); + e.printStackTrace(); + } } } diff --git a/jdk/test/java/rmi/server/Unmarshal/checkUnmarshalOnStopThread/CheckUnmarshalOnStopThread_Stub.java b/jdk/test/java/rmi/server/Unmarshal/checkUnmarshalOnStopThread/CheckUnmarshalOnStopThread_Stub.java index 1fa93b17883..612fe5db494 100644 --- a/jdk/test/java/rmi/server/Unmarshal/checkUnmarshalOnStopThread/CheckUnmarshalOnStopThread_Stub.java +++ b/jdk/test/java/rmi/server/Unmarshal/checkUnmarshalOnStopThread/CheckUnmarshalOnStopThread_Stub.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1998-1999 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -29,138 +29,138 @@ public final class CheckUnmarshalOnStopThread_Stub implements CheckUnmarshal, java.rmi.Remote { private static final java.rmi.server.Operation[] operations = { - new java.rmi.server.Operation("PoisonPill getPoisonPill()"), - new java.rmi.server.Operation("void passRuntimeExceptionParameter(RuntimeExceptionParameter)"), - new java.rmi.server.Operation("java.lang.Object ping()") + new java.rmi.server.Operation("PoisonPill getPoisonPill()"), + new java.rmi.server.Operation("void passRuntimeExceptionParameter(RuntimeExceptionParameter)"), + new java.rmi.server.Operation("java.lang.Object ping()") }; - + private static final long interfaceHash = -5923540687975666490L; - + private static final long serialVersionUID = 2; - + private static boolean useNewInvoke; private static java.lang.reflect.Method $method_getPoisonPill_0; private static java.lang.reflect.Method $method_passRuntimeExceptionParameter_1; private static java.lang.reflect.Method $method_ping_2; - + static { - try { - java.rmi.server.RemoteRef.class.getMethod("invoke", - new java.lang.Class[] { - java.rmi.Remote.class, - java.lang.reflect.Method.class, - java.lang.Object[].class, - long.class - }); - useNewInvoke = true; - $method_getPoisonPill_0 = CheckUnmarshal.class.getMethod("getPoisonPill", new java.lang.Class[] {}); - $method_passRuntimeExceptionParameter_1 = CheckUnmarshal.class.getMethod("passRuntimeExceptionParameter", new java.lang.Class[] {RuntimeExceptionParameter.class}); - $method_ping_2 = CheckUnmarshal.class.getMethod("ping", new java.lang.Class[] {}); - } catch (java.lang.NoSuchMethodException e) { - useNewInvoke = false; - } + try { + java.rmi.server.RemoteRef.class.getMethod("invoke", + new java.lang.Class[] { + java.rmi.Remote.class, + java.lang.reflect.Method.class, + java.lang.Object[].class, + long.class + }); + useNewInvoke = true; + $method_getPoisonPill_0 = CheckUnmarshal.class.getMethod("getPoisonPill", new java.lang.Class[] {}); + $method_passRuntimeExceptionParameter_1 = CheckUnmarshal.class.getMethod("passRuntimeExceptionParameter", new java.lang.Class[] {RuntimeExceptionParameter.class}); + $method_ping_2 = CheckUnmarshal.class.getMethod("ping", new java.lang.Class[] {}); + } catch (java.lang.NoSuchMethodException e) { + useNewInvoke = false; + } } - + // constructors public CheckUnmarshalOnStopThread_Stub() { - super(); + super(); } public CheckUnmarshalOnStopThread_Stub(java.rmi.server.RemoteRef ref) { - super(ref); + super(ref); } - + // methods from remote interfaces - + // implementation of getPoisonPill() public PoisonPill getPoisonPill() - throws java.rmi.RemoteException + throws java.rmi.RemoteException { - try { - if (useNewInvoke) { - Object $result = ref.invoke(this, $method_getPoisonPill_0, null, 5776441251039617360L); - return ((PoisonPill) $result); - } else { - java.rmi.server.RemoteCall call = ref.newCall((java.rmi.server.RemoteObject) this, operations, 0, interfaceHash); - ref.invoke(call); - PoisonPill $result; - try { - java.io.ObjectInput in = call.getInputStream(); - $result = (PoisonPill) in.readObject(); - } catch (java.io.IOException e) { - throw new java.rmi.UnmarshalException("error unmarshalling return", e); - } catch (java.lang.ClassNotFoundException e) { - throw new java.rmi.UnmarshalException("error unmarshalling return", e); - } finally { - ref.done(call); - } - return $result; - } - } catch (java.lang.RuntimeException e) { - throw e; - } catch (java.rmi.RemoteException e) { - throw e; - } catch (java.lang.Exception e) { - throw new java.rmi.UnexpectedException("undeclared checked exception", e); - } + try { + if (useNewInvoke) { + Object $result = ref.invoke(this, $method_getPoisonPill_0, null, 5776441251039617360L); + return ((PoisonPill) $result); + } else { + java.rmi.server.RemoteCall call = ref.newCall((java.rmi.server.RemoteObject) this, operations, 0, interfaceHash); + ref.invoke(call); + PoisonPill $result; + try { + java.io.ObjectInput in = call.getInputStream(); + $result = (PoisonPill) in.readObject(); + } catch (java.io.IOException e) { + throw new java.rmi.UnmarshalException("error unmarshalling return", e); + } catch (java.lang.ClassNotFoundException e) { + throw new java.rmi.UnmarshalException("error unmarshalling return", e); + } finally { + ref.done(call); + } + return $result; + } + } catch (java.lang.RuntimeException e) { + throw e; + } catch (java.rmi.RemoteException e) { + throw e; + } catch (java.lang.Exception e) { + throw new java.rmi.UnexpectedException("undeclared checked exception", e); + } } - + // implementation of passRuntimeExceptionParameter(RuntimeExceptionParameter) public void passRuntimeExceptionParameter(RuntimeExceptionParameter $param_RuntimeExceptionParameter_1) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { - try { - if (useNewInvoke) { - ref.invoke(this, $method_passRuntimeExceptionParameter_1, new java.lang.Object[] {$param_RuntimeExceptionParameter_1}, -4427599990679364365L); - } else { - java.rmi.server.RemoteCall call = ref.newCall((java.rmi.server.RemoteObject) this, operations, 1, interfaceHash); - try { - java.io.ObjectOutput out = call.getOutputStream(); - out.writeObject($param_RuntimeExceptionParameter_1); - } catch (java.io.IOException e) { - throw new java.rmi.MarshalException("error marshalling arguments", e); - } - ref.invoke(call); - ref.done(call); - } - } catch (java.lang.RuntimeException e) { - throw e; - } catch (java.rmi.RemoteException e) { - throw e; - } catch (java.lang.Exception e) { - throw new java.rmi.UnexpectedException("undeclared checked exception", e); - } + try { + if (useNewInvoke) { + ref.invoke(this, $method_passRuntimeExceptionParameter_1, new java.lang.Object[] {$param_RuntimeExceptionParameter_1}, -4427599990679364365L); + } else { + java.rmi.server.RemoteCall call = ref.newCall((java.rmi.server.RemoteObject) this, operations, 1, interfaceHash); + try { + java.io.ObjectOutput out = call.getOutputStream(); + out.writeObject($param_RuntimeExceptionParameter_1); + } catch (java.io.IOException e) { + throw new java.rmi.MarshalException("error marshalling arguments", e); + } + ref.invoke(call); + ref.done(call); + } + } catch (java.lang.RuntimeException e) { + throw e; + } catch (java.rmi.RemoteException e) { + throw e; + } catch (java.lang.Exception e) { + throw new java.rmi.UnexpectedException("undeclared checked exception", e); + } } - + // implementation of ping() public java.lang.Object ping() - throws java.rmi.RemoteException + throws java.rmi.RemoteException { - try { - if (useNewInvoke) { - Object $result = ref.invoke(this, $method_ping_2, null, 7635508643486276040L); - return ((java.lang.Object) $result); - } else { - java.rmi.server.RemoteCall call = ref.newCall((java.rmi.server.RemoteObject) this, operations, 2, interfaceHash); - ref.invoke(call); - java.lang.Object $result; - try { - java.io.ObjectInput in = call.getInputStream(); - $result = (java.lang.Object) in.readObject(); - } catch (java.io.IOException e) { - throw new java.rmi.UnmarshalException("error unmarshalling return", e); - } catch (java.lang.ClassNotFoundException e) { - throw new java.rmi.UnmarshalException("error unmarshalling return", e); - } finally { - ref.done(call); - } - return $result; - } - } catch (java.lang.RuntimeException e) { - throw e; - } catch (java.rmi.RemoteException e) { - throw e; - } catch (java.lang.Exception e) { - throw new java.rmi.UnexpectedException("undeclared checked exception", e); - } + try { + if (useNewInvoke) { + Object $result = ref.invoke(this, $method_ping_2, null, 7635508643486276040L); + return ((java.lang.Object) $result); + } else { + java.rmi.server.RemoteCall call = ref.newCall((java.rmi.server.RemoteObject) this, operations, 2, interfaceHash); + ref.invoke(call); + java.lang.Object $result; + try { + java.io.ObjectInput in = call.getInputStream(); + $result = (java.lang.Object) in.readObject(); + } catch (java.io.IOException e) { + throw new java.rmi.UnmarshalException("error unmarshalling return", e); + } catch (java.lang.ClassNotFoundException e) { + throw new java.rmi.UnmarshalException("error unmarshalling return", e); + } finally { + ref.done(call); + } + return $result; + } + } catch (java.lang.RuntimeException e) { + throw e; + } catch (java.rmi.RemoteException e) { + throw e; + } catch (java.lang.Exception e) { + throw new java.rmi.UnexpectedException("undeclared checked exception", e); + } } } diff --git a/jdk/test/java/rmi/server/Unmarshal/checkUnmarshalOnStopThread/CheckUnmarshall.java b/jdk/test/java/rmi/server/Unmarshal/checkUnmarshalOnStopThread/CheckUnmarshall.java index b1156581976..327081c9d8a 100644 --- a/jdk/test/java/rmi/server/Unmarshal/checkUnmarshalOnStopThread/CheckUnmarshall.java +++ b/jdk/test/java/rmi/server/Unmarshal/checkUnmarshalOnStopThread/CheckUnmarshall.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -20,7 +20,7 @@ * CA 95054 USA or visit www.sun.com if you need additional information or * have any questions. */ - + /** * */ @@ -37,4 +37,3 @@ import java.rmi.RemoteException; RuntimeExceptionParameter rep) throws RemoteException; } - diff --git a/jdk/test/java/rmi/server/Unmarshal/checkUnmarshalOnStopThread/PoisonPill.java b/jdk/test/java/rmi/server/Unmarshal/checkUnmarshalOnStopThread/PoisonPill.java index f9c488797af..3c885926c1f 100644 --- a/jdk/test/java/rmi/server/Unmarshal/checkUnmarshalOnStopThread/PoisonPill.java +++ b/jdk/test/java/rmi/server/Unmarshal/checkUnmarshalOnStopThread/PoisonPill.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -45,7 +45,7 @@ public class PoisonPill implements Serializable { throws IOException { if (CheckUnmarshalOnStopThread.typeToThrow != - CheckUnmarshalOnStopThread.RUNTIME_PILL) { + CheckUnmarshalOnStopThread.RUNTIME_PILL) { throw new Error("Wrote a test object whos readObject " + "method always throws an Error"); diff --git a/jdk/test/java/rmi/server/Unmarshal/checkUnmarshalOnStopThread/RuntimeExceptionParameter.java b/jdk/test/java/rmi/server/Unmarshal/checkUnmarshalOnStopThread/RuntimeExceptionParameter.java index efaaee82657..8d8f5e94c17 100644 --- a/jdk/test/java/rmi/server/Unmarshal/checkUnmarshalOnStopThread/RuntimeExceptionParameter.java +++ b/jdk/test/java/rmi/server/Unmarshal/checkUnmarshalOnStopThread/RuntimeExceptionParameter.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -38,7 +38,6 @@ class RuntimeExceptionParameter implements Serializable { { throw new RuntimeException("wrote a parameter whos writeObject " + "method always throws a RuntimeException" - ); + ); } } - diff --git a/jdk/test/java/rmi/server/Unreferenced/finiteGCLatency/FiniteGCLatency.java b/jdk/test/java/rmi/server/Unreferenced/finiteGCLatency/FiniteGCLatency.java index b171c827024..05f30142bee 100644 --- a/jdk/test/java/rmi/server/Unreferenced/finiteGCLatency/FiniteGCLatency.java +++ b/jdk/test/java/rmi/server/Unreferenced/finiteGCLatency/FiniteGCLatency.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -54,69 +54,69 @@ public class FiniteGCLatency implements Remote, Unreferenced { private boolean unreferencedInvoked = false; public void unreferenced() { - System.err.println("unreferenced() method invoked"); - synchronized (lock) { - unreferencedInvoked = true; - lock.notify(); - } + System.err.println("unreferenced() method invoked"); + synchronized (lock) { + unreferencedInvoked = true; + lock.notify(); + } } public static void main(String[] args) { - System.err.println("\nRegression test for bug 4164696\n"); + System.err.println("\nRegression test for bug 4164696\n"); - /* - * Set the interval that RMI will request for GC latency (before RMI - * gets initialized and this property is read) to an unrealistically - * small value, so that this test shouldn't have to wait too long. - */ - System.setProperty("sun.rmi.dgc.client.gcInterval", - String.valueOf(GC_INTERVAL)); + /* + * Set the interval that RMI will request for GC latency (before RMI + * gets initialized and this property is read) to an unrealistically + * small value, so that this test shouldn't have to wait too long. + */ + System.setProperty("sun.rmi.dgc.client.gcInterval", + String.valueOf(GC_INTERVAL)); - FiniteGCLatency obj = new FiniteGCLatency(); + FiniteGCLatency obj = new FiniteGCLatency(); - try { - UnicastRemoteObject.exportObject(obj); - System.err.println("exported remote object"); + try { + UnicastRemoteObject.exportObject(obj); + System.err.println("exported remote object"); - LocateRegistry.createRegistry(TestLibrary.REGISTRY_PORT); - System.err.println("created registry"); + LocateRegistry.createRegistry(TestLibrary.REGISTRY_PORT); + System.err.println("created registry"); - Registry registry = LocateRegistry.getRegistry("", TestLibrary.REGISTRY_PORT); - registry.bind(BINDING, obj); - System.err.println("bound remote object in registry"); + Registry registry = LocateRegistry.getRegistry("", TestLibrary.REGISTRY_PORT); + registry.bind(BINDING, obj); + System.err.println("bound remote object in registry"); - synchronized (obj.lock) { - registry.unbind(BINDING); - System.err.println("unbound remote object from registry; " + - "waiting for unreferenced() callback..."); - obj.lock.wait(TIMEOUT); + synchronized (obj.lock) { + registry.unbind(BINDING); + System.err.println("unbound remote object from registry; " + + "waiting for unreferenced() callback..."); + obj.lock.wait(TIMEOUT); - if (obj.unreferencedInvoked) { - System.err.println("TEST PASSED: unreferenced() invoked"); - } else { - throw new RuntimeException( - "TEST FAILED: unrefereced() not invoked after " + - ((double) TIMEOUT / 1000.0) + " seconds"); - } - } + if (obj.unreferencedInvoked) { + System.err.println("TEST PASSED: unreferenced() invoked"); + } else { + throw new RuntimeException( + "TEST FAILED: unrefereced() not invoked after " + + ((double) TIMEOUT / 1000.0) + " seconds"); + } + } - } catch (Exception e) { - if (e instanceof RuntimeException) { - throw (RuntimeException) e; - } else { - throw new RuntimeException( - "TEST FAILED: unexpected exception: " + e.toString()); - } - } finally { - /* - * When all is said and done, try to unexport the remote object - * so that the VM has a chance to exit. - */ - try { - UnicastRemoteObject.unexportObject(obj, true); - } catch (RemoteException e) { - } - } + } catch (Exception e) { + if (e instanceof RuntimeException) { + throw (RuntimeException) e; + } else { + throw new RuntimeException( + "TEST FAILED: unexpected exception: " + e.toString()); + } + } finally { + /* + * When all is said and done, try to unexport the remote object + * so that the VM has a chance to exit. + */ + try { + UnicastRemoteObject.unexportObject(obj, true); + } catch (RemoteException e) { + } + } } } diff --git a/jdk/test/java/rmi/server/Unreferenced/finiteGCLatency/FiniteGCLatency_Stub.java b/jdk/test/java/rmi/server/Unreferenced/finiteGCLatency/FiniteGCLatency_Stub.java index 4acb848188d..97c275b4fd0 100644 --- a/jdk/test/java/rmi/server/Unreferenced/finiteGCLatency/FiniteGCLatency_Stub.java +++ b/jdk/test/java/rmi/server/Unreferenced/finiteGCLatency/FiniteGCLatency_Stub.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -29,10 +29,10 @@ public final class FiniteGCLatency_Stub implements java.rmi.Remote { private static final long serialVersionUID = 2; - + // constructors public FiniteGCLatency_Stub(java.rmi.server.RemoteRef ref) { - super(ref); + super(ref); } - + } diff --git a/jdk/test/java/rmi/server/Unreferenced/leaseCheckInterval/LeaseCheckInterval.java b/jdk/test/java/rmi/server/Unreferenced/leaseCheckInterval/LeaseCheckInterval.java index 4458b3c5a05..6687b9202a8 100644 --- a/jdk/test/java/rmi/server/Unreferenced/leaseCheckInterval/LeaseCheckInterval.java +++ b/jdk/test/java/rmi/server/Unreferenced/leaseCheckInterval/LeaseCheckInterval.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -62,71 +62,71 @@ public class LeaseCheckInterval implements Remote, Unreferenced { private boolean unreferencedInvoked = false; public void unreferenced() { - System.err.println("unreferenced() method invoked"); - synchronized (lock) { - unreferencedInvoked = true; - lock.notify(); - } + System.err.println("unreferenced() method invoked"); + synchronized (lock) { + unreferencedInvoked = true; + lock.notify(); + } } public static void main(String[] args) throws Exception { - System.err.println("\nRegression test for bug 4285878\n"); + System.err.println("\nRegression test for bug 4285878\n"); - /* - * Set the duration of leases granted to a very small value, so that - * we can test if expirations are detected in a roughly comparable - * time. - */ - System.setProperty("java.rmi.dgc.leaseValue", - String.valueOf(LEASE_VALUE)); + /* + * Set the duration of leases granted to a very small value, so that + * we can test if expirations are detected in a roughly comparable + * time. + */ + System.setProperty("java.rmi.dgc.leaseValue", + String.valueOf(LEASE_VALUE)); - LeaseCheckInterval obj = new LeaseCheckInterval(); + LeaseCheckInterval obj = new LeaseCheckInterval(); - try { - UnicastRemoteObject.exportObject(obj); - System.err.println("exported remote object"); + try { + UnicastRemoteObject.exportObject(obj); + System.err.println("exported remote object"); - Registry localRegistry = - LocateRegistry.createRegistry(TestLibrary.REGISTRY_PORT); - System.err.println("created local registry"); + Registry localRegistry = + LocateRegistry.createRegistry(TestLibrary.REGISTRY_PORT); + System.err.println("created local registry"); - localRegistry.bind(BINDING, obj); - System.err.println("bound remote object in local registry"); + localRegistry.bind(BINDING, obj); + System.err.println("bound remote object in local registry"); - synchronized (obj.lock) { - System.err.println("starting remote client VM..."); - (new JavaVM("SelfTerminator")).start(); + synchronized (obj.lock) { + System.err.println("starting remote client VM..."); + (new JavaVM("SelfTerminator")).start(); - System.err.println("waiting for unreferenced() callback..."); - obj.lock.wait(TIMEOUT); + System.err.println("waiting for unreferenced() callback..."); + obj.lock.wait(TIMEOUT); - if (obj.unreferencedInvoked) { - System.err.println("TEST PASSED: " + - "unreferenced() invoked in timely fashion"); - } else { - throw new RuntimeException( - "TEST FAILED: unreferenced() not invoked after " + - ((double) TIMEOUT / 1000.0) + " seconds"); - } - } + if (obj.unreferencedInvoked) { + System.err.println("TEST PASSED: " + + "unreferenced() invoked in timely fashion"); + } else { + throw new RuntimeException( + "TEST FAILED: unreferenced() not invoked after " + + ((double) TIMEOUT / 1000.0) + " seconds"); + } + } - } catch (Exception e) { - if (e instanceof RuntimeException) { - throw (RuntimeException) e; - } else { - throw new RuntimeException( - "TEST FAILED: unexpected exception: " + e.toString()); - } - } finally { - /* - * When all is said and done, try to unexport the remote object - * so that the VM has a chance to exit. - */ - try { - UnicastRemoteObject.unexportObject(obj, true); - } catch (RemoteException e) { - } - } + } catch (Exception e) { + if (e instanceof RuntimeException) { + throw (RuntimeException) e; + } else { + throw new RuntimeException( + "TEST FAILED: unexpected exception: " + e.toString()); + } + } finally { + /* + * When all is said and done, try to unexport the remote object + * so that the VM has a chance to exit. + */ + try { + UnicastRemoteObject.unexportObject(obj, true); + } catch (RemoteException e) { + } + } } } diff --git a/jdk/test/java/rmi/server/Unreferenced/leaseCheckInterval/LeaseCheckInterval_Stub.java b/jdk/test/java/rmi/server/Unreferenced/leaseCheckInterval/LeaseCheckInterval_Stub.java index 5f258fbfb40..950e30982a3 100644 --- a/jdk/test/java/rmi/server/Unreferenced/leaseCheckInterval/LeaseCheckInterval_Stub.java +++ b/jdk/test/java/rmi/server/Unreferenced/leaseCheckInterval/LeaseCheckInterval_Stub.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -29,10 +29,10 @@ public final class LeaseCheckInterval_Stub implements java.rmi.Remote { private static final long serialVersionUID = 2; - + // constructors public LeaseCheckInterval_Stub(java.rmi.server.RemoteRef ref) { - super(ref); + super(ref); } - + } diff --git a/jdk/test/java/rmi/server/Unreferenced/leaseCheckInterval/SelfTerminator.java b/jdk/test/java/rmi/server/Unreferenced/leaseCheckInterval/SelfTerminator.java index 98d632fbca1..65e65f3e0b3 100644 --- a/jdk/test/java/rmi/server/Unreferenced/leaseCheckInterval/SelfTerminator.java +++ b/jdk/test/java/rmi/server/Unreferenced/leaseCheckInterval/SelfTerminator.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -32,13 +32,13 @@ import java.rmi.registry.Registry; public class SelfTerminator { public static void main(String[] args) { - try { - Registry registry = - LocateRegistry.getRegistry("", TestLibrary.REGISTRY_PORT); - Remote stub = registry.lookup(LeaseCheckInterval.BINDING); - Runtime.getRuntime().halt(0); - } catch (Exception e) { - e.printStackTrace(); - } + try { + Registry registry = + LocateRegistry.getRegistry("", TestLibrary.REGISTRY_PORT); + Remote stub = registry.lookup(LeaseCheckInterval.BINDING); + Runtime.getRuntime().halt(0); + } catch (Exception e) { + e.printStackTrace(); + } } } diff --git a/jdk/test/java/rmi/server/Unreferenced/marshalledObjectGet/MarshalledObjectGet.java b/jdk/test/java/rmi/server/Unreferenced/marshalledObjectGet/MarshalledObjectGet.java index 2b918b6ea7b..ea3a25d2945 100644 --- a/jdk/test/java/rmi/server/Unreferenced/marshalledObjectGet/MarshalledObjectGet.java +++ b/jdk/test/java/rmi/server/Unreferenced/marshalledObjectGet/MarshalledObjectGet.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 2000-2001 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -51,72 +51,72 @@ public class MarshalledObjectGet implements Remote, Unreferenced { private boolean unreferencedInvoked; public void unreferenced() { - System.err.println("unreferenced() method invoked"); - synchronized (lock) { - unreferencedInvoked = true; - lock.notify(); - } + System.err.println("unreferenced() method invoked"); + synchronized (lock) { + unreferencedInvoked = true; + lock.notify(); + } } public static void main(String[] args) { - System.err.println( - "\nTest to verify correction interaction of " + - "MarshalledObject.get and DGC registration\n"); + System.err.println( + "\nTest to verify correction interaction of " + + "MarshalledObject.get and DGC registration\n"); - /* - * Set the interval that RMI will request for GC latency (before RMI - * gets initialized and this property is read) to an unrealistically - * small value, so that this test shouldn't have to wait too long. - */ - System.setProperty("sun.rmi.dgc.client.gcInterval", - String.valueOf(GC_INTERVAL)); + /* + * Set the interval that RMI will request for GC latency (before RMI + * gets initialized and this property is read) to an unrealistically + * small value, so that this test shouldn't have to wait too long. + */ + System.setProperty("sun.rmi.dgc.client.gcInterval", + String.valueOf(GC_INTERVAL)); - MarshalledObjectGet obj = new MarshalledObjectGet(); + MarshalledObjectGet obj = new MarshalledObjectGet(); - try { - Remote stub = UnicastRemoteObject.exportObject(obj); - System.err.println("exported remote object"); + try { + Remote stub = UnicastRemoteObject.exportObject(obj); + System.err.println("exported remote object"); - MarshalledObject mobj = new MarshalledObject(stub); - Remote unmarshalledStub = (Remote) mobj.get(); - System.err.println("unmarshalled stub from marshalled object"); + MarshalledObject mobj = new MarshalledObject(stub); + Remote unmarshalledStub = (Remote) mobj.get(); + System.err.println("unmarshalled stub from marshalled object"); - synchronized (obj.lock) { - obj.unreferencedInvoked = false; + synchronized (obj.lock) { + obj.unreferencedInvoked = false; - unmarshalledStub = null; - System.gc(); - System.err.println("cleared unmarshalled stub"); - System.err.println("waiting for unreferenced() callback " + - "(SHOULD happen)..."); - obj.lock.wait(TIMEOUT); + unmarshalledStub = null; + System.gc(); + System.err.println("cleared unmarshalled stub"); + System.err.println("waiting for unreferenced() callback " + + "(SHOULD happen)..."); + obj.lock.wait(TIMEOUT); - if (obj.unreferencedInvoked) { - // TEST PASSED - } else { - throw new RuntimeException( - "TEST FAILED: unrefereced() not invoked after " + - ((double) TIMEOUT / 1000.0) + " seconds"); - } - } + if (obj.unreferencedInvoked) { + // TEST PASSED + } else { + throw new RuntimeException( + "TEST FAILED: unrefereced() not invoked after " + + ((double) TIMEOUT / 1000.0) + " seconds"); + } + } - System.err.println("TEST PASSED"); + System.err.println("TEST PASSED"); - } catch (Exception e) { - if (e instanceof RuntimeException) { - throw (RuntimeException) e; - } else { - throw new RuntimeException( - "TEST FAILED: unexpected exception: " + e.toString()); - } - } finally { - if (obj != null) { - try { - UnicastRemoteObject.unexportObject(obj, true); - } catch (Exception e) { - } - } - } + } catch (Exception e) { + if (e instanceof RuntimeException) { + throw (RuntimeException) e; + } else { + throw new RuntimeException( + "TEST FAILED: unexpected exception: " + e.toString()); + } + } finally { + if (obj != null) { + try { + UnicastRemoteObject.unexportObject(obj, true); + } catch (Exception e) { + } + } + } } } diff --git a/jdk/test/java/rmi/server/Unreferenced/marshalledObjectGet/MarshalledObjectGet_Stub.java b/jdk/test/java/rmi/server/Unreferenced/marshalledObjectGet/MarshalledObjectGet_Stub.java index e6bbe1fa5b6..55189cad77a 100644 --- a/jdk/test/java/rmi/server/Unreferenced/marshalledObjectGet/MarshalledObjectGet_Stub.java +++ b/jdk/test/java/rmi/server/Unreferenced/marshalledObjectGet/MarshalledObjectGet_Stub.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -29,10 +29,10 @@ public final class MarshalledObjectGet_Stub implements java.rmi.Remote { private static final long serialVersionUID = 2; - + // constructors public MarshalledObjectGet_Stub(java.rmi.server.RemoteRef ref) { - super(ref); + super(ref); } - + } diff --git a/jdk/test/java/rmi/server/Unreferenced/unreferencedContext/UnreferencedContext.java b/jdk/test/java/rmi/server/Unreferenced/unreferencedContext/UnreferencedContext.java index f9566c0245e..eafb5e041a0 100644 --- a/jdk/test/java/rmi/server/Unreferenced/unreferencedContext/UnreferencedContext.java +++ b/jdk/test/java/rmi/server/Unreferenced/unreferencedContext/UnreferencedContext.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1998-1999 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -32,12 +32,12 @@ * * @bug 4214123 * @summary Unreferenced.unreferenced(...) threads should run in the nonSystem group. - * To complete the fix for, 4182104, RMI unreferenced threads should also + * To complete the fix for, 4182104, RMI unreferenced threads should also * run in the nonSystem so that they do not need permissions to modify the * system thread group. * * @author Laird Dornin - * + * * @library ../../../testlibrary * @build UnreferencedContext * @build UnreferencedContext_Stub @@ -60,127 +60,127 @@ public class UnreferencedContext implements Remote, Unreferenced, Runnable { private ClassLoader unreferencedContext; public void run() { - System.err.println("unreferenced method created thread succesfully"); + System.err.println("unreferenced method created thread succesfully"); } public void unreferenced() { - // turn on security to ensure that the action below will not - // require extra permissions - System.setSecurityManager(new java.rmi.RMISecurityManager()); + // turn on security to ensure that the action below will not + // require extra permissions + System.setSecurityManager(new java.rmi.RMISecurityManager()); - // exercise functionality prohibited by 4214123 - (new Thread(this)).start(); + // exercise functionality prohibited by 4214123 + (new Thread(this)).start(); - System.err.println("unreferenced() method invoked"); - synchronized (lock) { - unreferencedInvoked = true; - unreferencedContext = - Thread.currentThread().getContextClassLoader(); - lock.notify(); - } + System.err.println("unreferenced() method invoked"); + synchronized (lock) { + unreferencedInvoked = true; + unreferencedContext = + Thread.currentThread().getContextClassLoader(); + lock.notify(); + } } public static void main(String[] args) { - System.err.println("\nRegression test for bug 4171278\n"); + System.err.println("\nRegression test for bug 4171278\n"); - /* - * Set the interval that RMI will request for GC latency (before RMI - * gets initialized and this property is read) to an unrealistically - * small value, so that this test shouldn't have to wait too long. - */ - System.setProperty("sun.rmi.dgc.client.gcInterval", - String.valueOf(GC_INTERVAL)); + /* + * Set the interval that RMI will request for GC latency (before RMI + * gets initialized and this property is read) to an unrealistically + * small value, so that this test shouldn't have to wait too long. + */ + System.setProperty("sun.rmi.dgc.client.gcInterval", + String.valueOf(GC_INTERVAL)); - UnreferencedContext obj = new UnreferencedContext(); + UnreferencedContext obj = new UnreferencedContext(); - try { - /* - * This little trick is necessary to make sure that the RMI server - * threads for objects created on the default port get created - * before we set our special context class loader, so that they - * don't *accidentally* inherit it when making the unreferenced() - * callback. - */ - UnicastRemoteObject.exportObject(obj); - UnicastRemoteObject.unexportObject(obj, true); + try { + /* + * This little trick is necessary to make sure that the RMI server + * threads for objects created on the default port get created + * before we set our special context class loader, so that they + * don't *accidentally* inherit it when making the unreferenced() + * callback. + */ + UnicastRemoteObject.exportObject(obj); + UnicastRemoteObject.unexportObject(obj, true); - /* - * Now create special context class loader before exporting the - * remote object for real, so that it should be set when the - * object's unreferenced() method is called. - */ - ClassLoader intendedContext = new URLClassLoader(new URL[0]); - Thread.currentThread().setContextClassLoader(intendedContext); - System.err.println( - "created and set intended context class loader: " + - intendedContext); + /* + * Now create special context class loader before exporting the + * remote object for real, so that it should be set when the + * object's unreferenced() method is called. + */ + ClassLoader intendedContext = new URLClassLoader(new URL[0]); + Thread.currentThread().setContextClassLoader(intendedContext); + System.err.println( + "created and set intended context class loader: " + + intendedContext); - UnicastRemoteObject.exportObject(obj); - System.err.println("exported remote object"); + UnicastRemoteObject.exportObject(obj); + System.err.println("exported remote object"); - LocateRegistry.createRegistry(TestLibrary.REGISTRY_PORT); - System.err.println("created registry"); + LocateRegistry.createRegistry(TestLibrary.REGISTRY_PORT); + System.err.println("created registry"); - Registry registry = LocateRegistry.getRegistry("", TestLibrary.REGISTRY_PORT); - registry.bind(BINDING, obj); - System.err.println("bound remote object in registry"); + Registry registry = LocateRegistry.getRegistry("", TestLibrary.REGISTRY_PORT); + registry.bind(BINDING, obj); + System.err.println("bound remote object in registry"); - synchronized (obj.lock) { - registry.unbind(BINDING); - System.err.println("unbound remote object from registry; " + - "waiting for unreferenced() callback..."); - /* - * This incantation seems sufficient to work around the - * ramifications of 4164696, so that this test will actually - * prove something useful about 1.2Beta4 or 1.2FCS before - * 4171278 was fixed. - */ - for (int i = 0; i < 10; i++) { - System.gc(); - obj.lock.wait(TIMEOUT / 10); - if (obj.unreferencedInvoked) { - break; - } - } + synchronized (obj.lock) { + registry.unbind(BINDING); + System.err.println("unbound remote object from registry; " + + "waiting for unreferenced() callback..."); + /* + * This incantation seems sufficient to work around the + * ramifications of 4164696, so that this test will actually + * prove something useful about 1.2Beta4 or 1.2FCS before + * 4171278 was fixed. + */ + for (int i = 0; i < 10; i++) { + System.gc(); + obj.lock.wait(TIMEOUT / 10); + if (obj.unreferencedInvoked) { + break; + } + } - if (obj.unreferencedInvoked) { - System.err.println( - "invoked with context class loader: " + - obj.unreferencedContext); + if (obj.unreferencedInvoked) { + System.err.println( + "invoked with context class loader: " + + obj.unreferencedContext); - if (obj.unreferencedContext == intendedContext) { - System.err.println( - "TEST PASSED: unreferenced() invoked" + - " with intended context class loader"); - } else { - throw new RuntimeException( - "TEST FAILED: unreferenced() invoked" + - " with incorrect context class loader"); - } - } else { - throw new RuntimeException( - "TEST FAILED: unreferenced() not invoked after " + - ((double) TIMEOUT / 1000.0) + " seconds or unreferenced failed to create a thread"); - } - } + if (obj.unreferencedContext == intendedContext) { + System.err.println( + "TEST PASSED: unreferenced() invoked" + + " with intended context class loader"); + } else { + throw new RuntimeException( + "TEST FAILED: unreferenced() invoked" + + " with incorrect context class loader"); + } + } else { + throw new RuntimeException( + "TEST FAILED: unreferenced() not invoked after " + + ((double) TIMEOUT / 1000.0) + " seconds or unreferenced failed to create a thread"); + } + } - } catch (Exception e) { - if (e instanceof RuntimeException) { - throw (RuntimeException) e; - } else { - throw new RuntimeException( - "TEST FAILED: unexpected exception: " + e.toString()); - } - } finally { - /* - * When all is said and done, try to unexport the remote object - * so that the VM has a chance to exit. - */ - try { - UnicastRemoteObject.unexportObject(obj, true); - } catch (RemoteException e) { - } - } + } catch (Exception e) { + if (e instanceof RuntimeException) { + throw (RuntimeException) e; + } else { + throw new RuntimeException( + "TEST FAILED: unexpected exception: " + e.toString()); + } + } finally { + /* + * When all is said and done, try to unexport the remote object + * so that the VM has a chance to exit. + */ + try { + UnicastRemoteObject.unexportObject(obj, true); + } catch (RemoteException e) { + } + } } } diff --git a/jdk/test/java/rmi/server/Unreferenced/unreferencedContext/UnreferencedContext_Stub.java b/jdk/test/java/rmi/server/Unreferenced/unreferencedContext/UnreferencedContext_Stub.java index 2ff7499e605..0e35db25c19 100644 --- a/jdk/test/java/rmi/server/Unreferenced/unreferencedContext/UnreferencedContext_Stub.java +++ b/jdk/test/java/rmi/server/Unreferenced/unreferencedContext/UnreferencedContext_Stub.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -29,10 +29,10 @@ public final class UnreferencedContext_Stub implements java.rmi.Remote { private static final long serialVersionUID = 2; - + // constructors public UnreferencedContext_Stub(java.rmi.server.RemoteRef ref) { - super(ref); + super(ref); } - + } diff --git a/jdk/test/java/rmi/transport/acceptLoop/CloseServerSocketOnTermination.java b/jdk/test/java/rmi/transport/acceptLoop/CloseServerSocketOnTermination.java index b8a2cbfc897..02bb3d7f459 100644 --- a/jdk/test/java/rmi/transport/acceptLoop/CloseServerSocketOnTermination.java +++ b/jdk/test/java/rmi/transport/acceptLoop/CloseServerSocketOnTermination.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 2005 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -51,75 +51,75 @@ public class CloseServerSocketOnTermination { private static long TIMEOUT = 5000; public static void main(String[] args) throws Exception { - System.err.println("\nRegression test for bug 4924577\n"); + System.err.println("\nRegression test for bug 4924577\n"); - RMISocketFactory.setFailureHandler(new RMIFailureHandler() { - public boolean failure(Exception e) { return false; } - }); + RMISocketFactory.setFailureHandler(new RMIFailureHandler() { + public boolean failure(Exception e) { return false; } + }); - tryWith(new IOException()); - tryWith(new NullPointerException()); - tryWith(new OutOfMemoryError()); - tryWith(new NoClassDefFoundError()); - tryWith(new InternalError()); - tryWith(new Throwable()); + tryWith(new IOException()); + tryWith(new NullPointerException()); + tryWith(new OutOfMemoryError()); + tryWith(new NoClassDefFoundError()); + tryWith(new InternalError()); + tryWith(new Throwable()); - System.err.println("TEST PASSED"); + System.err.println("TEST PASSED"); } private static void tryWith(Throwable t) throws Exception { - Remote impl = new Remote() { }; - try { - CountDownLatch latch = new CountDownLatch(1); - UnicastRemoteObject.exportObject(impl, 0, null, new SSF(t, latch)); - if (!latch.await(TIMEOUT, TimeUnit.MILLISECONDS)) { - throw new Error("server socket not closed"); - } - } finally { - UnicastRemoteObject.unexportObject(impl, true); - } + Remote impl = new Remote() { }; + try { + CountDownLatch latch = new CountDownLatch(1); + UnicastRemoteObject.exportObject(impl, 0, null, new SSF(t, latch)); + if (!latch.await(TIMEOUT, TimeUnit.MILLISECONDS)) { + throw new Error("server socket not closed"); + } + } finally { + UnicastRemoteObject.unexportObject(impl, true); + } } private static class SSF implements RMIServerSocketFactory { - private final Throwable acceptFailure; - private final CountDownLatch closedLatch; - SSF(Throwable acceptFailure, CountDownLatch closedLatch) { - this.acceptFailure = acceptFailure; - this.closedLatch = closedLatch; - } - public ServerSocket createServerSocket(int port) throws IOException { - return new ServerSocket(port) { - private int acceptInvocations = 0; - public synchronized Socket accept() throws IOException { - if (acceptInvocations++ == 0) { - throwException(acceptFailure); - } - return super.accept(); - } - public void close() throws IOException { - closedLatch.countDown(); - super.close(); - } - }; - } + private final Throwable acceptFailure; + private final CountDownLatch closedLatch; + SSF(Throwable acceptFailure, CountDownLatch closedLatch) { + this.acceptFailure = acceptFailure; + this.closedLatch = closedLatch; + } + public ServerSocket createServerSocket(int port) throws IOException { + return new ServerSocket(port) { + private int acceptInvocations = 0; + public synchronized Socket accept() throws IOException { + if (acceptInvocations++ == 0) { + throwException(acceptFailure); + } + return super.accept(); + } + public void close() throws IOException { + closedLatch.countDown(); + super.close(); + } + }; + } - // hack to throw an arbitrary (possibly checked) Throwable - private static void throwException(Throwable t) { - try { - toThrow.set(t); - Thrower.class.newInstance(); - } catch (IllegalAccessException e) { - throw new AssertionError(); - } catch (InstantiationException e) { - throw new AssertionError(); - } finally { - toThrow.remove(); - } - } - private static ThreadLocal toThrow = - new ThreadLocal(); - private static class Thrower { - Thrower() throws Throwable { throw toThrow.get(); } - } + // hack to throw an arbitrary (possibly checked) Throwable + private static void throwException(Throwable t) { + try { + toThrow.set(t); + Thrower.class.newInstance(); + } catch (IllegalAccessException e) { + throw new AssertionError(); + } catch (InstantiationException e) { + throw new AssertionError(); + } finally { + toThrow.remove(); + } + } + private static ThreadLocal toThrow = + new ThreadLocal(); + private static class Thrower { + Thrower() throws Throwable { throw toThrow.get(); } + } } } diff --git a/jdk/test/java/rmi/transport/checkFQDN/CheckFQDN.java b/jdk/test/java/rmi/transport/checkFQDN/CheckFQDN.java index 3cd17696cab..00dadb2f338 100644 --- a/jdk/test/java/rmi/transport/checkFQDN/CheckFQDN.java +++ b/jdk/test/java/rmi/transport/checkFQDN/CheckFQDN.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1998-1999 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -34,15 +34,15 @@ * * @library ../../testlibrary * @build CheckFQDN CheckFQDNClient CheckFQDN_Stub TellServerName - * @run main/othervm/timeout=120 CheckFQDN + * @run main/othervm/timeout=120 CheckFQDN */ -/** +/** * Get the hostname used by rmi using different rmi properities: * * if set java.rmi.server.hostname, hostname should equal this * property. - * + * * if set java.rmi.server.useLocalHostname, hostname must contain a '.' * * if set no properties hostname should be an ipaddress. @@ -58,118 +58,118 @@ import java.rmi.server.*; import java.io.*; /** - * Export a remote object through which the exec'ed client vm can + * Export a remote object through which the exec'ed client vm can * inform the main test what its host name is. */ -public class CheckFQDN extends UnicastRemoteObject +public class CheckFQDN extends UnicastRemoteObject implements TellServerName { - + static String propertyBeingTested = null; static String propertyBeingTestedValue = null; public static void main(String args[]) { - Object dummy = new Object(); - CheckFQDN checkFQDN = null; - try { - checkFQDN = new CheckFQDN(); + Object dummy = new Object(); + CheckFQDN checkFQDN = null; + try { + checkFQDN = new CheckFQDN(); - System.err.println - ("\nRegression test for bug/rfe 4115683\n"); - - Registry registry = java.rmi.registry.LocateRegistry. - createRegistry(TestLibrary.REGISTRY_PORT); - registry.bind("CheckFQDN", checkFQDN); - - /* test the host name scheme in different environments.*/ - testProperty("java.rmi.server.useLocalHostname", "true", ""); - testProperty("java.rmi.server.hostname", "thisIsJustAnRMITest", ""); - testProperty("java.rmi.server.hostname", "thisIsJustAnRMITest", - " -Djava.rmi.server.useLocalHostname=true "); - testProperty("", "", ""); + System.err.println + ("\nRegression test for bug/rfe 4115683\n"); - } catch (Exception e) { - TestLibrary.bomb(e); - } finally { - if (checkFQDN != null) { - TestLibrary.unexport(checkFQDN); - } - } - System.err.println("\nTest for bug/ref 4115683 passed.\n"); + Registry registry = java.rmi.registry.LocateRegistry. + createRegistry(TestLibrary.REGISTRY_PORT); + registry.bind("CheckFQDN", checkFQDN); + + /* test the host name scheme in different environments.*/ + testProperty("java.rmi.server.useLocalHostname", "true", ""); + testProperty("java.rmi.server.hostname", "thisIsJustAnRMITest", ""); + testProperty("java.rmi.server.hostname", "thisIsJustAnRMITest", + " -Djava.rmi.server.useLocalHostname=true "); + testProperty("", "", ""); + + } catch (Exception e) { + TestLibrary.bomb(e); + } finally { + if (checkFQDN != null) { + TestLibrary.unexport(checkFQDN); + } + } + System.err.println("\nTest for bug/ref 4115683 passed.\n"); } - /** + /** * Spawn a vm and feed it a property which sets the client's rmi * hostname. */ - public static void testProperty(String property, - String propertyValue, - String extraProp) + public static void testProperty(String property, + String propertyValue, + String extraProp) { - try { - String propOption = ""; - String equal = ""; - if (!property.equals("")) { - propOption = " -D"; - equal = "="; - } + try { + String propOption = ""; + String equal = ""; + if (!property.equals("")) { + propOption = " -D"; + equal = "="; + } - JavaVM jvm = new JavaVM("CheckFQDNClient", - propOption + property + - equal + - propertyValue + extraProp, - ""); - - propertyBeingTested=property; - propertyBeingTestedValue=propertyValue; + JavaVM jvm = new JavaVM("CheckFQDNClient", + propOption + property + + equal + + propertyValue + extraProp, + ""); - // create a client to tell checkFQDN what its rmi name is. */ - jvm.start(); + propertyBeingTested=property; + propertyBeingTestedValue=propertyValue; - if (jvm.getVM().waitFor() != 0 ) { - TestLibrary.bomb("Test failed, error in client."); - } - - } catch (Exception e) { - TestLibrary.bomb(e); - } + // create a client to tell checkFQDN what its rmi name is. */ + jvm.start(); + + if (jvm.getVM().waitFor() != 0 ) { + TestLibrary.bomb("Test failed, error in client."); + } + + } catch (Exception e) { + TestLibrary.bomb(e); + } } CheckFQDN() throws RemoteException { } - /** - * Remote method to allow client vm to tell the main test what its + /** + * Remote method to allow client vm to tell the main test what its * host name is . */ - public void tellServerName(String serverName) - throws RemoteException { + public void tellServerName(String serverName) + throws RemoteException { - if (propertyBeingTested.equals("java.rmi.server.hostname")) { - if ( !propertyBeingTestedValue.equals(serverName)) { - TestLibrary.bomb(propertyBeingTested + - ":\n Client rmi server name does " + - "not equal the one specified " + - "by java.rmi.server.hostname: " + - serverName +" != " + - propertyBeingTestedValue); - } + if (propertyBeingTested.equals("java.rmi.server.hostname")) { + if ( !propertyBeingTestedValue.equals(serverName)) { + TestLibrary.bomb(propertyBeingTested + + ":\n Client rmi server name does " + + "not equal the one specified " + + "by java.rmi.server.hostname: " + + serverName +" != " + + propertyBeingTestedValue); + } - /** use local host name, must contain a '.' */ - } else if (propertyBeingTested.equals - ("java.rmi.server.useLocalHostname")) { - if (serverName.indexOf('.') < 0) { - TestLibrary.bomb(propertyBeingTested + - ":\nThe client servername contains no '.'"); - } - } else { - // no propety set, must be ip address - if ((serverName.indexOf('.') < 0) || - (!Character.isDigit(serverName.charAt(0)))) { - TestLibrary.bomb("Default name scheme:\n"+ - " The client servername contains no '.'"+ - "or is not an ip address"); - } - } - System.err.println("Servername used: " + serverName); + /** use local host name, must contain a '.' */ + } else if (propertyBeingTested.equals + ("java.rmi.server.useLocalHostname")) { + if (serverName.indexOf('.') < 0) { + TestLibrary.bomb(propertyBeingTested + + ":\nThe client servername contains no '.'"); + } + } else { + // no propety set, must be ip address + if ((serverName.indexOf('.') < 0) || + (!Character.isDigit(serverName.charAt(0)))) { + TestLibrary.bomb("Default name scheme:\n"+ + " The client servername contains no '.'"+ + "or is not an ip address"); + } + } + System.err.println("Servername used: " + serverName); } } diff --git a/jdk/test/java/rmi/transport/checkFQDN/CheckFQDNClient.java b/jdk/test/java/rmi/transport/checkFQDN/CheckFQDNClient.java index 203413b9d00..ef644b197be 100644 --- a/jdk/test/java/rmi/transport/checkFQDN/CheckFQDNClient.java +++ b/jdk/test/java/rmi/transport/checkFQDN/CheckFQDNClient.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -25,7 +25,7 @@ * * * Client that will run in its own vm and tell the main CheckFQDN test - * program what its rmi host name is, name obtained from TCPEndpoint. + * program what its rmi host name is, name obtained from TCPEndpoint. */ import java.rmi.*; @@ -40,72 +40,72 @@ import sun.rmi.transport.tcp.TCPEndpoint; public class CheckFQDNClient implements Runnable { final static int NAME_SERVICE_TIME_OUT = 12000; - + static TCPEndpoint ep = null; - /** + /** * main, lookup remote object and tell it the rmi * hostname of this client vm. */ public static void main (String args[]) { - - // start a registry and register a copy of this in it. - TellServerName tell; - String hostname = null; - - try { - hostname = retrieveServerName(); - System.err.println("Client host name: " + - hostname); - tell = (TellServerName) Naming.lookup("rmi://:" + - TestLibrary.REGISTRY_PORT - + "/CheckFQDN"); - tell.tellServerName(hostname); - System.err.println("client has exited"); + // start a registry and register a copy of this in it. + TellServerName tell; + String hostname = null; - } catch (Exception e ) { - throw new RuntimeException(e.getMessage()); - } - System.exit(0); + try { + hostname = retrieveServerName(); + System.err.println("Client host name: " + + hostname); + + tell = (TellServerName) Naming.lookup("rmi://:" + + TestLibrary.REGISTRY_PORT + + "/CheckFQDN"); + tell.tellServerName(hostname); + System.err.println("client has exited"); + + } catch (Exception e ) { + throw new RuntimeException(e.getMessage()); + } + System.exit(0); } - + /* what is the rmi hostname for this vm? */ public static String retrieveServerName () { - try { + try { - CheckFQDNClient chk = new CheckFQDNClient(); - - synchronized(chk) { - (new Thread (chk)).start(); - chk.wait(NAME_SERVICE_TIME_OUT); - } - - if (ep == null) { - throw new RuntimeException - ("Timeout getting the local endpoint."); - } - - // this is the name used by rmi for the client hostname - return ep.getHost(); - - }catch (Exception e){ - throw new RuntimeException (e.getMessage()); - } + CheckFQDNClient chk = new CheckFQDNClient(); + + synchronized(chk) { + (new Thread (chk)).start(); + chk.wait(NAME_SERVICE_TIME_OUT); + } + + if (ep == null) { + throw new RuntimeException + ("Timeout getting the local endpoint."); + } + + // this is the name used by rmi for the client hostname + return ep.getHost(); + + }catch (Exception e){ + throw new RuntimeException (e.getMessage()); + } } /* thread to geth the rmi hostname of this vm */ public void run () { - try { - synchronized(this) { - ep = TCPEndpoint.getLocalEndpoint(0); - } - } catch (Exception e) { - throw new RuntimeException(); - } finally { - synchronized(this) { - this.notify(); - } - } + try { + synchronized(this) { + ep = TCPEndpoint.getLocalEndpoint(0); + } + } catch (Exception e) { + throw new RuntimeException(); + } finally { + synchronized(this) { + this.notify(); + } + } } } diff --git a/jdk/test/java/rmi/transport/checkFQDN/CheckFQDN_Stub.java b/jdk/test/java/rmi/transport/checkFQDN/CheckFQDN_Stub.java index 93330b17c11..3c318cae946 100644 --- a/jdk/test/java/rmi/transport/checkFQDN/CheckFQDN_Stub.java +++ b/jdk/test/java/rmi/transport/checkFQDN/CheckFQDN_Stub.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -29,66 +29,66 @@ public final class CheckFQDN_Stub implements TellServerName, java.rmi.Remote { private static java.rmi.server.Operation[] operations = { - new java.rmi.server.Operation("void tellServerName(java.lang.String)") + new java.rmi.server.Operation("void tellServerName(java.lang.String)") }; - + private static final long interfaceHash = 4509625981775855367L; - + private static final long serialVersionUID = 2; - + private static boolean useNewInvoke; private static java.lang.reflect.Method $method_tellServerName_0; - + static { - try { - java.rmi.server.RemoteRef.class.getMethod("invoke", - new java.lang.Class[] { - java.rmi.Remote.class, - java.lang.reflect.Method.class, - java.lang.Object[].class, - long.class - }); - useNewInvoke = true; - $method_tellServerName_0 = TellServerName.class.getMethod("tellServerName", new java.lang.Class[] {java.lang.String.class}); - } catch (java.lang.NoSuchMethodException e) { - useNewInvoke = false; - } + try { + java.rmi.server.RemoteRef.class.getMethod("invoke", + new java.lang.Class[] { + java.rmi.Remote.class, + java.lang.reflect.Method.class, + java.lang.Object[].class, + long.class + }); + useNewInvoke = true; + $method_tellServerName_0 = TellServerName.class.getMethod("tellServerName", new java.lang.Class[] {java.lang.String.class}); + } catch (java.lang.NoSuchMethodException e) { + useNewInvoke = false; + } } - + // constructors public CheckFQDN_Stub() { - super(); + super(); } public CheckFQDN_Stub(java.rmi.server.RemoteRef ref) { - super(ref); + super(ref); } - + // methods from remote interfaces - + // implementation of tellServerName(String) public void tellServerName(java.lang.String $param_String_1) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { - try { - if (useNewInvoke) { - ref.invoke(this, $method_tellServerName_0, new java.lang.Object[] {$param_String_1}, -5180633734615762942L); - } else { - java.rmi.server.RemoteCall call = ref.newCall((java.rmi.server.RemoteObject) this, operations, 0, interfaceHash); - try { - java.io.ObjectOutput out = call.getOutputStream(); - out.writeObject($param_String_1); - } catch (java.io.IOException e) { - throw new java.rmi.MarshalException("error marshalling arguments", e); - } - ref.invoke(call); - ref.done(call); - } - } catch (java.lang.RuntimeException e) { - throw e; - } catch (java.rmi.RemoteException e) { - throw e; - } catch (java.lang.Exception e) { - throw new java.rmi.UnexpectedException("undeclared checked exception", e); - } + try { + if (useNewInvoke) { + ref.invoke(this, $method_tellServerName_0, new java.lang.Object[] {$param_String_1}, -5180633734615762942L); + } else { + java.rmi.server.RemoteCall call = ref.newCall((java.rmi.server.RemoteObject) this, operations, 0, interfaceHash); + try { + java.io.ObjectOutput out = call.getOutputStream(); + out.writeObject($param_String_1); + } catch (java.io.IOException e) { + throw new java.rmi.MarshalException("error marshalling arguments", e); + } + ref.invoke(call); + ref.done(call); + } + } catch (java.lang.RuntimeException e) { + throw e; + } catch (java.rmi.RemoteException e) { + throw e; + } catch (java.lang.Exception e) { + throw new java.rmi.UnexpectedException("undeclared checked exception", e); + } } } diff --git a/jdk/test/java/rmi/transport/checkFQDN/TellServerName.java b/jdk/test/java/rmi/transport/checkFQDN/TellServerName.java index 0dbf0c6c300..d5625c5cbdb 100644 --- a/jdk/test/java/rmi/transport/checkFQDN/TellServerName.java +++ b/jdk/test/java/rmi/transport/checkFQDN/TellServerName.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -24,7 +24,7 @@ import java.rmi.*; import java.rmi.server.*; -/** +/** * interface to get server name from an execed vm * I am using an execed vm because I need to set * rmi's hostname serveral times with different properties. @@ -32,4 +32,3 @@ import java.rmi.server.*; interface TellServerName extends Remote { void tellServerName (String serverName) throws RemoteException; } - diff --git a/jdk/test/java/rmi/transport/checkLeaseInfoLeak/CheckLeaseLeak.java b/jdk/test/java/rmi/transport/checkLeaseInfoLeak/CheckLeaseLeak.java index b5823dd5bde..94847ffc01e 100644 --- a/jdk/test/java/rmi/transport/checkLeaseInfoLeak/CheckLeaseLeak.java +++ b/jdk/test/java/rmi/transport/checkLeaseInfoLeak/CheckLeaseLeak.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1998-2005 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -44,7 +44,7 @@ * the remote object. Each vmid needs a seperate LeaseInfo object in * the object table target DGCImpl.leaseTable. If the leak is fixed, * the leaseTable field will contain no objects. We use reflection to - * find the number of objects contained in this table. + * find the number of objects contained in this table. */ import java.rmi.*; @@ -57,13 +57,13 @@ import java.lang.reflect.*; import java.rmi.registry.*; public class CheckLeaseLeak extends UnicastRemoteObject implements LeaseLeak { - + public CheckLeaseLeak() throws RemoteException { } public void ping () throws RemoteException { } /** * Id to fake the DGC_ID, so we can later get a reference to the - * DGCImpl in the object table. + * DGCImpl in the object table. */ private final static int DGC_ID = 2; @@ -71,148 +71,148 @@ public class CheckLeaseLeak extends UnicastRemoteObject implements LeaseLeak { private final static int numberPingCalls = 0; private final static int CHECK_INTERVAL = 400; private final static int LEASE_VALUE = 20; - + public static void main (String[] args) { - CheckLeaseLeak leakServer = null; - int numLeft =0; + CheckLeaseLeak leakServer = null; + int numLeft =0; - /* - * we want DGC to collect leases *quickly* - * decrease the lease check interval - */ - TestLibrary.setInteger("sun.rmi.dgc.checkInterval", - CHECK_INTERVAL); - TestLibrary.setInteger("java.rmi.dgc.leaseValue", - LEASE_VALUE); + /* + * we want DGC to collect leases *quickly* + * decrease the lease check interval + */ + TestLibrary.setInteger("sun.rmi.dgc.checkInterval", + CHECK_INTERVAL); + TestLibrary.setInteger("java.rmi.dgc.leaseValue", + LEASE_VALUE); - try { - Registry registry = - java.rmi.registry.LocateRegistry. - createRegistry(TestLibrary.REGISTRY_PORT); + try { + Registry registry = + java.rmi.registry.LocateRegistry. + createRegistry(TestLibrary.REGISTRY_PORT); - leakServer = new CheckLeaseLeak(); - registry.rebind("/LeaseLeak", leakServer); + leakServer = new CheckLeaseLeak(); + registry.rebind("/LeaseLeak", leakServer); - /* create a bunch of clients in a *different* vm */ - for (int i = 0 ; i < ITERATIONS ; i ++ ) { - System.err.println("Created client: " + i); - - JavaVM jvm = new JavaVM("LeaseLeakClient", - " -Djava.security.policy=" + - TestParams.defaultPolicy, ""); - jvm.start(); + /* create a bunch of clients in a *different* vm */ + for (int i = 0 ; i < ITERATIONS ; i ++ ) { + System.err.println("Created client: " + i); - if (jvm.getVM().waitFor() == 1 ) { - TestLibrary.bomb("Client process failed"); - } - } - numLeft = getDGCLeaseTableSize(); - Thread.sleep(3000); - - } catch(Exception e) { - TestLibrary.bomb("CheckLeaseLeak Error: ", e); - } finally { - if (leakServer != null) { - TestLibrary.unexport(leakServer); - leakServer = null; - } - } + JavaVM jvm = new JavaVM("LeaseLeakClient", + " -Djava.security.policy=" + + TestParams.defaultPolicy, ""); + jvm.start(); - /* numLeft should be 2 - if 11 there is a problem. */ - if (numLeft > 2) { - TestLibrary.bomb("Too many objects in DGCImpl.leaseTable: "+ - numLeft); - } else { - System.err.println("Check leaseInfo leak passed with " + - numLeft - + " object(s) in the leaseTable"); - } + if (jvm.getVM().waitFor() == 1 ) { + TestLibrary.bomb("Client process failed"); + } + } + numLeft = getDGCLeaseTableSize(); + Thread.sleep(3000); + + } catch(Exception e) { + TestLibrary.bomb("CheckLeaseLeak Error: ", e); + } finally { + if (leakServer != null) { + TestLibrary.unexport(leakServer); + leakServer = null; + } + } + + /* numLeft should be 2 - if 11 there is a problem. */ + if (numLeft > 2) { + TestLibrary.bomb("Too many objects in DGCImpl.leaseTable: "+ + numLeft); + } else { + System.err.println("Check leaseInfo leak passed with " + + numLeft + + " object(s) in the leaseTable"); + } } /** * Obtain a reference to the main DGCImpl via reflection. Extract * the DGCImpl using the ObjectTable and the well known ID of the - * DGCImpl. + * DGCImpl. */ private static int getDGCLeaseTableSize () { - int numLeaseInfosLeft = 0; + int numLeaseInfosLeft = 0; - /** - * Will eventually be set to point at the leaseTable inside - * DGCImpl. - */ - Map leaseTable = null; - final Remote[] dgcImpl = new Remote[1]; - Field f; + /** + * Will eventually be set to point at the leaseTable inside + * DGCImpl. + */ + Map leaseTable = null; + final Remote[] dgcImpl = new Remote[1]; + Field f; - try { - f = (Field) java.security.AccessController.doPrivileged - (new java.security.PrivilegedExceptionAction() { - public Object run() throws Exception { + try { + f = (Field) java.security.AccessController.doPrivileged + (new java.security.PrivilegedExceptionAction() { + public Object run() throws Exception { - ObjID dgcID = new ObjID(DGC_ID); - - /* - * Construct an ObjectEndpoint containing DGC's - * ObjID. - */ - Class oeClass = - Class.forName("sun.rmi.transport.ObjectEndpoint"); - Class[] constrParams = - new Class[]{ ObjID.class, Transport.class }; - Constructor oeConstructor = - oeClass.getDeclaredConstructor(constrParams); - oeConstructor.setAccessible(true); - Object oe = - oeConstructor.newInstance( - new Object[]{ dgcID, null }); - - /* - * Get Target that contains DGCImpl in ObjectTable - */ - Class objTableClass = - Class.forName("sun.rmi.transport.ObjectTable"); - Class getTargetParams[] = new Class[] { oeClass }; - Method objTableGetTarget = - objTableClass.getDeclaredMethod("getTarget", - getTargetParams); - objTableGetTarget.setAccessible(true); - Target dgcTarget = (Target) - objTableGetTarget.invoke(null, new Object[]{ oe }); - - /* get the DGCImpl from its Target */ - Method targetGetImpl = - dgcTarget.getClass().getDeclaredMethod - ("getImpl", null); - targetGetImpl.setAccessible(true); - dgcImpl[0] = - (Remote) targetGetImpl.invoke(dgcTarget, null); + ObjID dgcID = new ObjID(DGC_ID); - /* Get the lease table from the DGCImpl. */ - Field reflectedLeaseTable = - dgcImpl[0].getClass().getDeclaredField - ("leaseTable"); - reflectedLeaseTable.setAccessible(true); + /* + * Construct an ObjectEndpoint containing DGC's + * ObjID. + */ + Class oeClass = + Class.forName("sun.rmi.transport.ObjectEndpoint"); + Class[] constrParams = + new Class[]{ ObjID.class, Transport.class }; + Constructor oeConstructor = + oeClass.getDeclaredConstructor(constrParams); + oeConstructor.setAccessible(true); + Object oe = + oeConstructor.newInstance( + new Object[]{ dgcID, null }); - return reflectedLeaseTable; - } - }); + /* + * Get Target that contains DGCImpl in ObjectTable + */ + Class objTableClass = + Class.forName("sun.rmi.transport.ObjectTable"); + Class getTargetParams[] = new Class[] { oeClass }; + Method objTableGetTarget = + objTableClass.getDeclaredMethod("getTarget", + getTargetParams); + objTableGetTarget.setAccessible(true); + Target dgcTarget = (Target) + objTableGetTarget.invoke(null, new Object[]{ oe }); - /** - * This is the leaseTable that will fill up with LeaseInfo - * objects if the LeaseInfo memory leak is not fixed. - */ - leaseTable = (Map) f.get(dgcImpl[0]); + /* get the DGCImpl from its Target */ + Method targetGetImpl = + dgcTarget.getClass().getDeclaredMethod + ("getImpl", null); + targetGetImpl.setAccessible(true); + dgcImpl[0] = + (Remote) targetGetImpl.invoke(dgcTarget, null); - numLeaseInfosLeft = leaseTable.size(); + /* Get the lease table from the DGCImpl. */ + Field reflectedLeaseTable = + dgcImpl[0].getClass().getDeclaredField + ("leaseTable"); + reflectedLeaseTable.setAccessible(true); - } catch(Exception e) { - if (e instanceof java.security.PrivilegedActionException) - e = ((java.security.PrivilegedActionException) e). - getException(); - TestLibrary.bomb(e); - } + return reflectedLeaseTable; + } + }); - return numLeaseInfosLeft; + /** + * This is the leaseTable that will fill up with LeaseInfo + * objects if the LeaseInfo memory leak is not fixed. + */ + leaseTable = (Map) f.get(dgcImpl[0]); + + numLeaseInfosLeft = leaseTable.size(); + + } catch(Exception e) { + if (e instanceof java.security.PrivilegedActionException) + e = ((java.security.PrivilegedActionException) e). + getException(); + TestLibrary.bomb(e); + } + + return numLeaseInfosLeft; } } diff --git a/jdk/test/java/rmi/transport/checkLeaseInfoLeak/CheckLeaseLeak_Stub.java b/jdk/test/java/rmi/transport/checkLeaseInfoLeak/CheckLeaseLeak_Stub.java index 42f6fa901d6..52b5d89a53a 100644 --- a/jdk/test/java/rmi/transport/checkLeaseInfoLeak/CheckLeaseLeak_Stub.java +++ b/jdk/test/java/rmi/transport/checkLeaseInfoLeak/CheckLeaseLeak_Stub.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -29,60 +29,60 @@ public final class CheckLeaseLeak_Stub implements LeaseLeak, java.rmi.Remote { private static java.rmi.server.Operation[] operations = { - new java.rmi.server.Operation("void ping()") + new java.rmi.server.Operation("void ping()") }; - + private static final long interfaceHash = -8409781791984809394L; - + private static final long serialVersionUID = 2; - + private static boolean useNewInvoke; private static java.lang.reflect.Method $method_ping_0; - + static { - try { - java.rmi.server.RemoteRef.class.getMethod("invoke", - new java.lang.Class[] { - java.rmi.Remote.class, - java.lang.reflect.Method.class, - java.lang.Object[].class, - long.class - }); - useNewInvoke = true; - $method_ping_0 = LeaseLeak.class.getMethod("ping", new java.lang.Class[] {}); - } catch (java.lang.NoSuchMethodException e) { - useNewInvoke = false; - } + try { + java.rmi.server.RemoteRef.class.getMethod("invoke", + new java.lang.Class[] { + java.rmi.Remote.class, + java.lang.reflect.Method.class, + java.lang.Object[].class, + long.class + }); + useNewInvoke = true; + $method_ping_0 = LeaseLeak.class.getMethod("ping", new java.lang.Class[] {}); + } catch (java.lang.NoSuchMethodException e) { + useNewInvoke = false; + } } - + // constructors public CheckLeaseLeak_Stub() { - super(); + super(); } public CheckLeaseLeak_Stub(java.rmi.server.RemoteRef ref) { - super(ref); + super(ref); } - + // methods from remote interfaces - + // implementation of ping() public void ping() - throws java.rmi.RemoteException + throws java.rmi.RemoteException { - try { - if (useNewInvoke) { - ref.invoke(this, $method_ping_0, null, 5866401369815527589L); - } else { - java.rmi.server.RemoteCall call = ref.newCall((java.rmi.server.RemoteObject) this, operations, 0, interfaceHash); - ref.invoke(call); - ref.done(call); - } - } catch (java.lang.RuntimeException e) { - throw e; - } catch (java.rmi.RemoteException e) { - throw e; - } catch (java.lang.Exception e) { - throw new java.rmi.UnexpectedException("undeclared checked exception", e); - } + try { + if (useNewInvoke) { + ref.invoke(this, $method_ping_0, null, 5866401369815527589L); + } else { + java.rmi.server.RemoteCall call = ref.newCall((java.rmi.server.RemoteObject) this, operations, 0, interfaceHash); + ref.invoke(call); + ref.done(call); + } + } catch (java.lang.RuntimeException e) { + throw e; + } catch (java.rmi.RemoteException e) { + throw e; + } catch (java.lang.Exception e) { + throw new java.rmi.UnexpectedException("undeclared checked exception", e); + } } } diff --git a/jdk/test/java/rmi/transport/checkLeaseInfoLeak/LeaseLeak.java b/jdk/test/java/rmi/transport/checkLeaseInfoLeak/LeaseLeak.java index d83e2ebc296..de412cda32e 100644 --- a/jdk/test/java/rmi/transport/checkLeaseInfoLeak/LeaseLeak.java +++ b/jdk/test/java/rmi/transport/checkLeaseInfoLeak/LeaseLeak.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1998-2001 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * diff --git a/jdk/test/java/rmi/transport/checkLeaseInfoLeak/LeaseLeakClient.java b/jdk/test/java/rmi/transport/checkLeaseInfoLeak/LeaseLeakClient.java index a9f452e7147..b42f23d2e66 100644 --- a/jdk/test/java/rmi/transport/checkLeaseInfoLeak/LeaseLeakClient.java +++ b/jdk/test/java/rmi/transport/checkLeaseInfoLeak/LeaseLeakClient.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -25,24 +25,24 @@ import java.rmi.*; import java.rmi.server.*; import java.rmi.registry.*; -public class LeaseLeakClient { +public class LeaseLeakClient { public static void main(String args[]) { - TestLibrary.suggestSecurityManager("java.rmi.RMISecurityManager"); - - try { - LeaseLeak leaseLeak = null; - - // put a reference on a remote object. - Registry registry = - java.rmi.registry.LocateRegistry.getRegistry( - TestLibrary.REGISTRY_PORT); - leaseLeak = (LeaseLeak) registry.lookup("/LeaseLeak"); - leaseLeak.ping(); - - } catch(Exception e) { - System.err.println("LeaseLeakClient Error: "+e.getMessage()); - e.printStackTrace(); - throw new RuntimeException(e.getMessage()); - } + TestLibrary.suggestSecurityManager("java.rmi.RMISecurityManager"); + + try { + LeaseLeak leaseLeak = null; + + // put a reference on a remote object. + Registry registry = + java.rmi.registry.LocateRegistry.getRegistry( + TestLibrary.REGISTRY_PORT); + leaseLeak = (LeaseLeak) registry.lookup("/LeaseLeak"); + leaseLeak.ping(); + + } catch(Exception e) { + System.err.println("LeaseLeakClient Error: "+e.getMessage()); + e.printStackTrace(); + throw new RuntimeException(e.getMessage()); + } } } diff --git a/jdk/test/java/rmi/transport/closeServerSocket/CloseServerSocket.java b/jdk/test/java/rmi/transport/closeServerSocket/CloseServerSocket.java index fe0b9accbe0..54ca8fd2a71 100644 --- a/jdk/test/java/rmi/transport/closeServerSocket/CloseServerSocket.java +++ b/jdk/test/java/rmi/transport/closeServerSocket/CloseServerSocket.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 2005 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -50,80 +50,80 @@ public class CloseServerSocket implements Remote { private CloseServerSocket() { } public static void main(String[] args) throws Exception { - System.err.println("\nRegression test for bug 4457683\n"); + System.err.println("\nRegression test for bug 4457683\n"); - verifyPortFree(PORT); - Registry registry = LocateRegistry.createRegistry(PORT); - System.err.println("- exported registry: " + registry); - verifyPortInUse(PORT); - UnicastRemoteObject.unexportObject(registry, true); - System.err.println("- unexported registry"); - Thread.sleep(1); // work around BindException (bug?) - verifyPortFree(PORT); + verifyPortFree(PORT); + Registry registry = LocateRegistry.createRegistry(PORT); + System.err.println("- exported registry: " + registry); + verifyPortInUse(PORT); + UnicastRemoteObject.unexportObject(registry, true); + System.err.println("- unexported registry"); + Thread.sleep(1); // work around BindException (bug?) + verifyPortFree(PORT); - /* - * The follow portion of this test is disabled temporarily - * because 4457683 was partially backed out because of - * 6269166; for now, only server sockets originally opened for - * exports on non-anonymous ports will be closed when all of - * the corresponding remote objects have been exported. A - * separate bug will be filed to represent the remainder of - * 4457683 for anonymous-port exports. - */ + /* + * The follow portion of this test is disabled temporarily + * because 4457683 was partially backed out because of + * 6269166; for now, only server sockets originally opened for + * exports on non-anonymous ports will be closed when all of + * the corresponding remote objects have been exported. A + * separate bug will be filed to represent the remainder of + * 4457683 for anonymous-port exports. + */ -// SSF ssf = new SSF(); -// Remote impl = new CloseServerSocket(); -// Remote stub = UnicastRemoteObject.exportObject(impl, 0, null, ssf); -// System.err.println("- exported object: " + stub); -// UnicastRemoteObject.unexportObject(impl, true); -// System.err.println("- unexported object"); -// synchronized (ssf) { -// if (!ssf.serverSocketClosed) { -// throw new RuntimeException("TEST FAILED: " + -// "server socket not closed"); -// } -// } +// SSF ssf = new SSF(); +// Remote impl = new CloseServerSocket(); +// Remote stub = UnicastRemoteObject.exportObject(impl, 0, null, ssf); +// System.err.println("- exported object: " + stub); +// UnicastRemoteObject.unexportObject(impl, true); +// System.err.println("- unexported object"); +// synchronized (ssf) { +// if (!ssf.serverSocketClosed) { +// throw new RuntimeException("TEST FAILED: " + +// "server socket not closed"); +// } +// } - System.err.println("TEST PASSED"); + System.err.println("TEST PASSED"); } private static void verifyPortFree(int port) throws IOException { - ServerSocket ss = new ServerSocket(PORT); - ss.close(); - System.err.println("- port " + port + " is free"); + ServerSocket ss = new ServerSocket(PORT); + ss.close(); + System.err.println("- port " + port + " is free"); } private static void verifyPortInUse(int port) throws IOException { - try { - verifyPortFree(port); - } catch (BindException e) { - System.err.println("- port " + port + " is in use"); - return; - } + try { + verifyPortFree(port); + } catch (BindException e) { + System.err.println("- port " + port + " is in use"); + return; + } } private static class SSF implements RMIServerSocketFactory { - boolean serverSocketClosed = false; - SSF() { }; + boolean serverSocketClosed = false; + SSF() { }; - public ServerSocket createServerSocket(int port) throws IOException { - return new SS(port); - } + public ServerSocket createServerSocket(int port) throws IOException { + return new SS(port); + } - private class SS extends ServerSocket { - SS(int port) throws IOException { - super(port); - System.err.println("- created server socket: " + this); - }; + private class SS extends ServerSocket { + SS(int port) throws IOException { + super(port); + System.err.println("- created server socket: " + this); + }; - public void close() throws IOException { - synchronized (SSF.this) { - serverSocketClosed = true; - SSF.this.notifyAll(); - } - System.err.println("- closing server socket: " + this); - super.close(); - } - } + public void close() throws IOException { + synchronized (SSF.this) { + serverSocketClosed = true; + SSF.this.notifyAll(); + } + System.err.println("- closing server socket: " + this); + super.close(); + } + } } } diff --git a/jdk/test/java/rmi/transport/dgcDeadLock/DGCDeadLock.java b/jdk/test/java/rmi/transport/dgcDeadLock/DGCDeadLock.java index fd01055ca37..820d4c410dd 100644 --- a/jdk/test/java/rmi/transport/dgcDeadLock/DGCDeadLock.java +++ b/jdk/test/java/rmi/transport/dgcDeadLock/DGCDeadLock.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1998-1999 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -46,7 +46,7 @@ * was attempting to lock. * * This test causes the above conditions to occur and waits to see if - * a given set of remote calls finishes "quickly enough." + * a given set of remote calls finishes "quickly enough." */ import java.rmi.*; @@ -60,98 +60,98 @@ public class DGCDeadLock implements Runnable { static DGCDeadLock test = new DGCDeadLock(); static { - System.setProperty("sun.rmi.transport.cleanInterval", "50"); + System.setProperty("sun.rmi.transport.cleanInterval", "50"); } static public void main(String[] args) { - JavaVM testImplVM = null; - - System.err.println("\nregression test for 4118056\n"); - TestLibrary.suggestSecurityManager("java.rmi.RMISecurityManager"); + JavaVM testImplVM = null; + + System.err.println("\nregression test for 4118056\n"); + TestLibrary.suggestSecurityManager("java.rmi.RMISecurityManager"); try { - String options = " -Djava.security.policy=" + - TestParams.defaultPolicy + - " -Djava.rmi.dgc.leaseValue=500000" + - " -Dsun.rmi.dgc.checkInterval=" + - (HOLD_TARGET_TIME - 5000) + ""; + String options = " -Djava.security.policy=" + + TestParams.defaultPolicy + + " -Djava.rmi.dgc.leaseValue=500000" + + " -Dsun.rmi.dgc.checkInterval=" + + (HOLD_TARGET_TIME - 5000) + ""; - testImplVM = new JavaVM("TestImpl", options, ""); - testImplVM.start(); + testImplVM = new JavaVM("TestImpl", options, ""); + testImplVM.start(); - synchronized (test) { - Thread t = new Thread(test); - t.setDaemon(true); - t.start(); + synchronized (test) { + Thread t = new Thread(test); + t.setDaemon(true); + t.start(); - // wait for the remote calls to take place - test.wait(TEST_FAIL_TIME); - } + // wait for the remote calls to take place + test.wait(TEST_FAIL_TIME); + } - if (!finished) { - TestLibrary.bomb("Test failed, had exception or exercise" + - " routines took too long to " + - "execute"); - } - System.err.println("Test passed, exercises " + - "finished in time."); + if (!finished) { + TestLibrary.bomb("Test failed, had exception or exercise" + + " routines took too long to " + + "execute"); + } + System.err.println("Test passed, exercises " + + "finished in time."); } catch (Exception e) { - testImplVM = null; - TestLibrary.bomb("test failed", e); + testImplVM = null; + TestLibrary.bomb("test failed", e); } } public void run() { - try { - String echo = null; + try { + String echo = null; - // give the test remote object time to initialize. - Thread.currentThread().sleep(8000); + // give the test remote object time to initialize. + Thread.currentThread().sleep(8000); - // create a test client - Test foo = (Test) Naming.lookup("rmi://:" + - TestLibrary.REGISTRY_PORT + - "/Foo"); - echo = foo.echo("Hello world"); - System.err.println("Test object created."); + // create a test client + Test foo = (Test) Naming.lookup("rmi://:" + + TestLibrary.REGISTRY_PORT + + "/Foo"); + echo = foo.echo("Hello world"); + System.err.println("Test object created."); - /* give TestImpl time to lock the target in the - * object table and any dirtys finish. - */ - Thread.currentThread().sleep(5000); + /* give TestImpl time to lock the target in the + * object table and any dirtys finish. + */ + Thread.currentThread().sleep(5000); - //unreference "Foo" - foo = null; + //unreference "Foo" + foo = null; - //garbage collect and finalize foo - Runtime.getRuntime().gc(); - Runtime.getRuntime().runFinalization(); - - //import "Bar" - Test bar = (Test) Naming.lookup("rmi://:" + - TestLibrary.REGISTRY_PORT + - "/Bar"); - - /* infinite loop to show the liveness of Client, - * if we have deadlock remote call will not return - */ - try { - for (int i = 0; i < 500; i++) { - echo = bar.echo("Remote call" + i); - Thread.sleep(10); - } + //garbage collect and finalize foo + Runtime.getRuntime().gc(); + Runtime.getRuntime().runFinalization(); - // flag exercises finished - finished = true; + //import "Bar" + Test bar = (Test) Naming.lookup("rmi://:" + + TestLibrary.REGISTRY_PORT + + "/Bar"); - } catch (RemoteException e) { - } - - } catch (Exception e) { - TestLibrary.bomb("test failed", e); - } finally { - } + /* infinite loop to show the liveness of Client, + * if we have deadlock remote call will not return + */ + try { + for (int i = 0; i < 500; i++) { + echo = bar.echo("Remote call" + i); + Thread.sleep(10); + } + + // flag exercises finished + finished = true; + + } catch (RemoteException e) { + } + + } catch (Exception e) { + TestLibrary.bomb("test failed", e); + } finally { + } } } diff --git a/jdk/test/java/rmi/transport/dgcDeadLock/Test.java b/jdk/test/java/rmi/transport/dgcDeadLock/Test.java index 4706b3870e8..5fcd90c3884 100644 --- a/jdk/test/java/rmi/transport/dgcDeadLock/Test.java +++ b/jdk/test/java/rmi/transport/dgcDeadLock/Test.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * diff --git a/jdk/test/java/rmi/transport/dgcDeadLock/TestImpl.java b/jdk/test/java/rmi/transport/dgcDeadLock/TestImpl.java index d96fcc21126..0f23ae73a0c 100644 --- a/jdk/test/java/rmi/transport/dgcDeadLock/TestImpl.java +++ b/jdk/test/java/rmi/transport/dgcDeadLock/TestImpl.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1998-2005 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -34,7 +34,7 @@ import java.util.*; import java.rmi.registry.*; import java.rmi.server.*; -public class TestImpl extends UnicastRemoteObject +public class TestImpl extends UnicastRemoteObject implements Test { static Thread locker = null; @@ -46,197 +46,197 @@ public class TestImpl extends UnicastRemoteObject public String echo(String msg) throws RemoteException { - if (locker == null) { - // hold the target if not already held - locker = lockTargetExpireLeases(foo, DGCDeadLock.HOLD_TARGET_TIME); - } + if (locker == null) { + // hold the target if not already held + locker = lockTargetExpireLeases(foo, DGCDeadLock.HOLD_TARGET_TIME); + } return "Message received: " + msg; } static public void main(String[] args) { - Registry registry = null; + Registry registry = null; try { - registry = java.rmi.registry.LocateRegistry. - createRegistry(TestLibrary.REGISTRY_PORT); + registry = java.rmi.registry.LocateRegistry. + createRegistry(TestLibrary.REGISTRY_PORT); - //export "Foo" - foo = new TestImpl(); - Naming.rebind("rmi://:" + - TestLibrary.REGISTRY_PORT - + "/Foo", foo); + //export "Foo" + foo = new TestImpl(); + Naming.rebind("rmi://:" + + TestLibrary.REGISTRY_PORT + + "/Foo", foo); - try { - //export "Bar" after leases have been expired. - bar = new TestImpl(); - Naming.rebind("rmi://localhost:" + - TestLibrary.REGISTRY_PORT - + "/Bar", bar); - } catch (Exception e) { - throw new RemoteException(e.getMessage()); - } - Thread.sleep(DGCDeadLock.TEST_FAIL_TIME); - System.err.println("object vm exiting..."); - System.exit(0); + try { + //export "Bar" after leases have been expired. + bar = new TestImpl(); + Naming.rebind("rmi://localhost:" + + TestLibrary.REGISTRY_PORT + + "/Bar", bar); + } catch (Exception e) { + throw new RemoteException(e.getMessage()); + } + Thread.sleep(DGCDeadLock.TEST_FAIL_TIME); + System.err.println("object vm exiting..."); + System.exit(0); } catch (Exception e) { - System.err.println(e.getMessage()); - e.printStackTrace(); + System.err.println(e.getMessage()); + e.printStackTrace(); } finally { - TestLibrary.unexport(registry); - registry = null; - } + TestLibrary.unexport(registry); + registry = null; + } } static Thread lockTargetExpireLeases(Remote toLock, int timeOut) { - Thread t = new Thread((Runnable) new TargetLocker(toLock, timeOut)); - t.start(); - return t; + Thread t = new Thread((Runnable) new TargetLocker(toLock, timeOut)); + t.start(); + return t; } static class TargetLocker implements Runnable { - Remote toLock = null; - int timeOut = 0; + Remote toLock = null; + int timeOut = 0; - TargetLocker(Remote toLock, int timeOut) { - this.toLock = toLock; - this.timeOut = timeOut; - } + TargetLocker(Remote toLock, int timeOut) { + this.toLock = toLock; + this.timeOut = timeOut; + } - public void run() { - try { - // give dgc dirty calls time to finish. - Thread.currentThread().sleep(4000); + public void run() { + try { + // give dgc dirty calls time to finish. + Thread.currentThread().sleep(4000); - java.security.AccessController. - doPrivileged(new LockTargetCheckLeases(toLock, - timeOut)); + java.security.AccessController. + doPrivileged(new LockTargetCheckLeases(toLock, + timeOut)); - } catch (Exception e) { - System.err.println(e.getMessage()); - e.printStackTrace(); - System.exit(1); - } - } + } catch (Exception e) { + System.err.println(e.getMessage()); + e.printStackTrace(); + System.exit(1); + } + } } - static class LockTargetCheckLeases - implements java.security.PrivilegedAction { + static class LockTargetCheckLeases + implements java.security.PrivilegedAction { - Remote toLock = null; - int timeOut = 0; + Remote toLock = null; + int timeOut = 0; - LockTargetCheckLeases(Remote toLock, int timeOut) { - this.toLock = toLock; - this.timeOut = timeOut; - } + LockTargetCheckLeases(Remote toLock, int timeOut) { + this.toLock = toLock; + this.timeOut = timeOut; + } - public Object run() { - try { - - Class args[] = new Class[1]; - - Class objTableClass = Class.forName - ("sun.rmi.transport.ObjectTable"); - - /* get the Target that corresponds to toLock from the - * ObjectTable - */ - args[0] = Class.forName("java.rmi.Remote"); - Method objTableGetTarget = - objTableClass.getDeclaredMethod("getTarget", args ); - objTableGetTarget.setAccessible(true); - - Target lockTarget = - ((Target) objTableGetTarget.invoke - (null , new Object [] {toLock} )); - - // make sure the lease on this object has expired. - expireLeases(lockTarget); - - // stop other threads from using the target for toLock. - synchronized (lockTarget) { - System.err.println("Locked the relevant target, sleeping " + - timeOut/1000 + " seconds"); - Thread.currentThread().sleep(timeOut); - System.err.println("Target unlocked"); - } + public Object run() { + try { - } catch (Exception e) { - System.err.println(e.getMessage()); - e.printStackTrace(); - System.exit(1); - } - return null; - } + Class args[] = new Class[1]; + + Class objTableClass = Class.forName + ("sun.rmi.transport.ObjectTable"); + + /* get the Target that corresponds to toLock from the + * ObjectTable + */ + args[0] = Class.forName("java.rmi.Remote"); + Method objTableGetTarget = + objTableClass.getDeclaredMethod("getTarget", args ); + objTableGetTarget.setAccessible(true); + + Target lockTarget = + ((Target) objTableGetTarget.invoke + (null , new Object [] {toLock} )); + + // make sure the lease on this object has expired. + expireLeases(lockTarget); + + // stop other threads from using the target for toLock. + synchronized (lockTarget) { + System.err.println("Locked the relevant target, sleeping " + + timeOut/1000 + " seconds"); + Thread.currentThread().sleep(timeOut); + System.err.println("Target unlocked"); + } + + } catch (Exception e) { + System.err.println(e.getMessage()); + e.printStackTrace(); + System.exit(1); + } + return null; + } } /* leases have long values, so no dirty calls which would lock out * a clean call, but the leases need to expire anyway, so we do it - * explicitly. + * explicitly. */ static void expireLeases(Target t) throws Exception { - final Target target = t; + final Target target = t; - java.security.AccessController.doPrivileged( + java.security.AccessController.doPrivileged( - // put this into another class? - new java.security.PrivilegedAction() { - public Object run() { - try { + // put this into another class? + new java.security.PrivilegedAction() { + public Object run() { + try { - Class DGCClass = Class.forName("sun.rmi.transport.DGCImpl"); - Method getDGCImpl = - DGCClass.getDeclaredMethod("getDGCImpl", null ); - getDGCImpl.setAccessible(true); - - // make sure the lease on this object has expired. - DGC dgcImpl = ((DGC) getDGCImpl.invoke(null, null)); - - /* Get the lease table from the DGCImpl. */ - Field reflectedLeaseTable = - dgcImpl.getClass().getDeclaredField("leaseTable"); - reflectedLeaseTable.setAccessible(true); - - Map leaseTable = (Map) reflectedLeaseTable.get(dgcImpl); - - // dont really need this synchronization... - synchronized (leaseTable) { - Iterator en = leaseTable.values().iterator(); - while (en.hasNext()) { - Object info = en.next(); - - /* Get the notifySet in the leaseInfo object. */ - Field notifySetField = - info.getClass().getDeclaredField("notifySet"); - notifySetField.setAccessible(true); - HashSet notifySet = (HashSet) notifySetField.get(info); - - Iterator iter = notifySet.iterator(); - while (iter.hasNext()) { - Target notified = (Target) iter.next(); - - if (notified == target) { - - /* Get and set the expiration field from the info object. */ - Field expirationField = info.getClass(). - getDeclaredField("expiration"); - expirationField.setAccessible(true); - expirationField.setLong(info, 0); - } - } - } - } - } catch (Exception e) { - System.err.println(e.getMessage()); - e.printStackTrace(); - System.exit(1); - } - // no interesting return value for this privileged action - return null; - } - }); + Class DGCClass = Class.forName("sun.rmi.transport.DGCImpl"); + Method getDGCImpl = + DGCClass.getDeclaredMethod("getDGCImpl", null ); + getDGCImpl.setAccessible(true); + + // make sure the lease on this object has expired. + DGC dgcImpl = ((DGC) getDGCImpl.invoke(null, null)); + + /* Get the lease table from the DGCImpl. */ + Field reflectedLeaseTable = + dgcImpl.getClass().getDeclaredField("leaseTable"); + reflectedLeaseTable.setAccessible(true); + + Map leaseTable = (Map) reflectedLeaseTable.get(dgcImpl); + + // dont really need this synchronization... + synchronized (leaseTable) { + Iterator en = leaseTable.values().iterator(); + while (en.hasNext()) { + Object info = en.next(); + + /* Get the notifySet in the leaseInfo object. */ + Field notifySetField = + info.getClass().getDeclaredField("notifySet"); + notifySetField.setAccessible(true); + HashSet notifySet = (HashSet) notifySetField.get(info); + + Iterator iter = notifySet.iterator(); + while (iter.hasNext()) { + Target notified = (Target) iter.next(); + + if (notified == target) { + + /* Get and set the expiration field from the info object. */ + Field expirationField = info.getClass(). + getDeclaredField("expiration"); + expirationField.setAccessible(true); + expirationField.setLong(info, 0); + } + } + } + } + } catch (Exception e) { + System.err.println(e.getMessage()); + e.printStackTrace(); + System.exit(1); + } + // no interesting return value for this privileged action + return null; + } + }); } } diff --git a/jdk/test/java/rmi/transport/dgcDeadLock/TestImpl_Stub.java b/jdk/test/java/rmi/transport/dgcDeadLock/TestImpl_Stub.java index 49ea79e9c10..f82df1fffbb 100644 --- a/jdk/test/java/rmi/transport/dgcDeadLock/TestImpl_Stub.java +++ b/jdk/test/java/rmi/transport/dgcDeadLock/TestImpl_Stub.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -29,78 +29,78 @@ public final class TestImpl_Stub implements Test, java.rmi.Remote { private static final java.rmi.server.Operation[] operations = { - new java.rmi.server.Operation("java.lang.String echo(java.lang.String)") + new java.rmi.server.Operation("java.lang.String echo(java.lang.String)") }; - + private static final long interfaceHash = 8975711176019764637L; - + private static final long serialVersionUID = 2; - + private static boolean useNewInvoke; private static java.lang.reflect.Method $method_echo_0; - + static { - try { - java.rmi.server.RemoteRef.class.getMethod("invoke", - new java.lang.Class[] { - java.rmi.Remote.class, - java.lang.reflect.Method.class, - java.lang.Object[].class, - long.class - }); - useNewInvoke = true; - $method_echo_0 = Test.class.getMethod("echo", new java.lang.Class[] {java.lang.String.class}); - } catch (java.lang.NoSuchMethodException e) { - useNewInvoke = false; - } + try { + java.rmi.server.RemoteRef.class.getMethod("invoke", + new java.lang.Class[] { + java.rmi.Remote.class, + java.lang.reflect.Method.class, + java.lang.Object[].class, + long.class + }); + useNewInvoke = true; + $method_echo_0 = Test.class.getMethod("echo", new java.lang.Class[] {java.lang.String.class}); + } catch (java.lang.NoSuchMethodException e) { + useNewInvoke = false; + } } - + // constructors public TestImpl_Stub() { - super(); + super(); } public TestImpl_Stub(java.rmi.server.RemoteRef ref) { - super(ref); + super(ref); } - + // methods from remote interfaces - + // implementation of echo(String) public java.lang.String echo(java.lang.String $param_String_1) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { - try { - if (useNewInvoke) { - Object $result = ref.invoke(this, $method_echo_0, new java.lang.Object[] {$param_String_1}, 5525131960618330777L); - return ((java.lang.String) $result); - } else { - java.rmi.server.RemoteCall call = ref.newCall((java.rmi.server.RemoteObject) this, operations, 0, interfaceHash); - try { - java.io.ObjectOutput out = call.getOutputStream(); - out.writeObject($param_String_1); - } catch (java.io.IOException e) { - throw new java.rmi.MarshalException("error marshalling arguments", e); - } - ref.invoke(call); - java.lang.String $result; - try { - java.io.ObjectInput in = call.getInputStream(); - $result = (java.lang.String) in.readObject(); - } catch (java.io.IOException e) { - throw new java.rmi.UnmarshalException("error unmarshalling return", e); - } catch (java.lang.ClassNotFoundException e) { - throw new java.rmi.UnmarshalException("error unmarshalling return", e); - } finally { - ref.done(call); - } - return $result; - } - } catch (java.lang.RuntimeException e) { - throw e; - } catch (java.rmi.RemoteException e) { - throw e; - } catch (java.lang.Exception e) { - throw new java.rmi.UnexpectedException("undeclared checked exception", e); - } + try { + if (useNewInvoke) { + Object $result = ref.invoke(this, $method_echo_0, new java.lang.Object[] {$param_String_1}, 5525131960618330777L); + return ((java.lang.String) $result); + } else { + java.rmi.server.RemoteCall call = ref.newCall((java.rmi.server.RemoteObject) this, operations, 0, interfaceHash); + try { + java.io.ObjectOutput out = call.getOutputStream(); + out.writeObject($param_String_1); + } catch (java.io.IOException e) { + throw new java.rmi.MarshalException("error marshalling arguments", e); + } + ref.invoke(call); + java.lang.String $result; + try { + java.io.ObjectInput in = call.getInputStream(); + $result = (java.lang.String) in.readObject(); + } catch (java.io.IOException e) { + throw new java.rmi.UnmarshalException("error unmarshalling return", e); + } catch (java.lang.ClassNotFoundException e) { + throw new java.rmi.UnmarshalException("error unmarshalling return", e); + } finally { + ref.done(call); + } + return $result; + } + } catch (java.lang.RuntimeException e) { + throw e; + } catch (java.rmi.RemoteException e) { + throw e; + } catch (java.lang.Exception e) { + throw new java.rmi.UnexpectedException("undeclared checked exception", e); + } } } diff --git a/jdk/test/java/rmi/transport/handshakeFailure/HandshakeFailure.java b/jdk/test/java/rmi/transport/handshakeFailure/HandshakeFailure.java index 1d26e6769a4..e14de6adc57 100644 --- a/jdk/test/java/rmi/transport/handshakeFailure/HandshakeFailure.java +++ b/jdk/test/java/rmi/transport/handshakeFailure/HandshakeFailure.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -49,85 +49,85 @@ public class HandshakeFailure { public static void main(String[] args) throws Exception { - /* - * Listen on port... - */ - ServerSocket serverSocket = new ServerSocket(PORT); + /* + * Listen on port... + */ + ServerSocket serverSocket = new ServerSocket(PORT); - /* - * (Attempt RMI call to port in separate thread.) - */ - Registry registry = LocateRegistry.getRegistry(PORT); - Connector connector = new Connector(registry); - Thread t = new Thread(connector); - t.setDaemon(true); - t.start(); + /* + * (Attempt RMI call to port in separate thread.) + */ + Registry registry = LocateRegistry.getRegistry(PORT); + Connector connector = new Connector(registry); + Thread t = new Thread(connector); + t.setDaemon(true); + t.start(); - /* - * ...accept one connection from port and send non-JRMP data. - */ - Socket socket = serverSocket.accept(); - socket.getOutputStream().write("Wrong way".getBytes()); - socket.close(); + /* + * ...accept one connection from port and send non-JRMP data. + */ + Socket socket = serverSocket.accept(); + socket.getOutputStream().write("Wrong way".getBytes()); + socket.close(); - /* - * Wait for call attempt to finish, and analyze result. - */ - t.join(TIMEOUT); - synchronized (connector) { - if (connector.success) { - throw new RuntimeException( - "TEST FAILED: remote call succeeded??"); - } - if (connector.exception == null) { - throw new RuntimeException( - "TEST FAILED: remote call did not time out"); - } else { - System.err.println("remote call failed with exception:"); - connector.exception.printStackTrace(); - System.err.println(); + /* + * Wait for call attempt to finish, and analyze result. + */ + t.join(TIMEOUT); + synchronized (connector) { + if (connector.success) { + throw new RuntimeException( + "TEST FAILED: remote call succeeded??"); + } + if (connector.exception == null) { + throw new RuntimeException( + "TEST FAILED: remote call did not time out"); + } else { + System.err.println("remote call failed with exception:"); + connector.exception.printStackTrace(); + System.err.println(); - if (connector.exception instanceof MarshalException) { - System.err.println( - "TEST FAILED: MarshalException thrown, expecting " + - "java.rmi.ConnectException or ConnectIOException"); - } else if (connector.exception instanceof ConnectException || - connector.exception instanceof ConnectIOException) - { - System.err.println( - "TEST PASSED: java.rmi.ConnectException or " + - "ConnectIOException thrown"); - } else { - throw new RuntimeException( - "TEST FAILED: unexpected Exception thrown", - connector.exception); - } - } - } + if (connector.exception instanceof MarshalException) { + System.err.println( + "TEST FAILED: MarshalException thrown, expecting " + + "java.rmi.ConnectException or ConnectIOException"); + } else if (connector.exception instanceof ConnectException || + connector.exception instanceof ConnectIOException) + { + System.err.println( + "TEST PASSED: java.rmi.ConnectException or " + + "ConnectIOException thrown"); + } else { + throw new RuntimeException( + "TEST FAILED: unexpected Exception thrown", + connector.exception); + } + } + } } private static class Connector implements Runnable { - private final Registry registry; + private final Registry registry; - boolean success = false; + boolean success = false; Exception exception = null; - Connector(Registry registry) { - this.registry = registry; - } + Connector(Registry registry) { + this.registry = registry; + } - public void run() { - try { - registry.lookup("Dale Cooper"); - synchronized (this) { - success = true; - } - } catch (Exception e) { - synchronized (this) { - exception = e; - } - } - } + public void run() { + try { + registry.lookup("Dale Cooper"); + synchronized (this) { + success = true; + } + } catch (Exception e) { + synchronized (this) { + exception = e; + } + } + } } } diff --git a/jdk/test/java/rmi/transport/handshakeTimeout/HandshakeTimeout.java b/jdk/test/java/rmi/transport/handshakeTimeout/HandshakeTimeout.java index 43b8e96ad72..c74c021b486 100644 --- a/jdk/test/java/rmi/transport/handshakeTimeout/HandshakeTimeout.java +++ b/jdk/test/java/rmi/transport/handshakeTimeout/HandshakeTimeout.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -51,81 +51,81 @@ public class HandshakeTimeout { public static void main(String[] args) throws Exception { - System.setProperty("sun.rmi.transport.tcp.handshakeTimeout", - String.valueOf(TIMEOUT / 2)); + System.setProperty("sun.rmi.transport.tcp.handshakeTimeout", + String.valueOf(TIMEOUT / 2)); - /* - * Listen on port, but never process connections made to it. - */ - ServerSocket serverSocket = new ServerSocket(PORT); + /* + * Listen on port, but never process connections made to it. + */ + ServerSocket serverSocket = new ServerSocket(PORT); - /* - * Attempt RMI call to port in separate thread. - */ - Registry registry = LocateRegistry.getRegistry(PORT); - Connector connector = new Connector(registry); - Thread t = new Thread(connector); - t.setDaemon(true); - t.start(); + /* + * Attempt RMI call to port in separate thread. + */ + Registry registry = LocateRegistry.getRegistry(PORT); + Connector connector = new Connector(registry); + Thread t = new Thread(connector); + t.setDaemon(true); + t.start(); - /* - * Wait for call attempt to finished, and analyze result. - */ - t.join(TIMEOUT); - synchronized (connector) { - if (connector.success) { - throw new RuntimeException( - "TEST FAILED: remote call succeeded??"); - } - if (connector.exception == null) { - throw new RuntimeException( - "TEST FAILED: remote call did not time out"); - } else { - System.err.println("remote call failed with exception:"); - connector.exception.printStackTrace(); - System.err.println(); + /* + * Wait for call attempt to finished, and analyze result. + */ + t.join(TIMEOUT); + synchronized (connector) { + if (connector.success) { + throw new RuntimeException( + "TEST FAILED: remote call succeeded??"); + } + if (connector.exception == null) { + throw new RuntimeException( + "TEST FAILED: remote call did not time out"); + } else { + System.err.println("remote call failed with exception:"); + connector.exception.printStackTrace(); + System.err.println(); - if (connector.exception instanceof MarshalException) { - System.err.println( - "TEST FAILED: MarshalException thrown, expecting " + - "java.rmi.ConnectException or ConnectIOException"); - } else if (connector.exception instanceof ConnectException || - connector.exception instanceof ConnectIOException) - { - System.err.println( - "TEST PASSED: java.rmi.ConnectException or " + - "ConnectIOException thrown"); - } else { - throw new RuntimeException( - "TEST FAILED: unexpected Exception thrown", - connector.exception); - } - } - } + if (connector.exception instanceof MarshalException) { + System.err.println( + "TEST FAILED: MarshalException thrown, expecting " + + "java.rmi.ConnectException or ConnectIOException"); + } else if (connector.exception instanceof ConnectException || + connector.exception instanceof ConnectIOException) + { + System.err.println( + "TEST PASSED: java.rmi.ConnectException or " + + "ConnectIOException thrown"); + } else { + throw new RuntimeException( + "TEST FAILED: unexpected Exception thrown", + connector.exception); + } + } + } } private static class Connector implements Runnable { - private final Registry registry; + private final Registry registry; - boolean success = false; + boolean success = false; Exception exception = null; - Connector(Registry registry) { - this.registry = registry; - } + Connector(Registry registry) { + this.registry = registry; + } - public void run() { - try { - registry.lookup("Dale Cooper"); - synchronized (this) { - success = true; - } - } catch (Exception e) { - synchronized (this) { - exception = e; - } - } - } + public void run() { + try { + registry.lookup("Dale Cooper"); + synchronized (this) { + success = true; + } + } catch (Exception e) { + synchronized (this) { + exception = e; + } + } + } } } diff --git a/jdk/test/java/rmi/transport/httpSocket/HttpSocketTest.java b/jdk/test/java/rmi/transport/httpSocket/HttpSocketTest.java index 6f26b9b5554..8fbba5460cd 100644 --- a/jdk/test/java/rmi/transport/httpSocket/HttpSocketTest.java +++ b/jdk/test/java/rmi/transport/httpSocket/HttpSocketTest.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1999-2006 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -53,65 +53,60 @@ interface MyRemoteInterface extends Remote { Remote getRemoteObject() throws RemoteException; } -public class HttpSocketTest extends UnicastRemoteObject +public class HttpSocketTest extends UnicastRemoteObject implements MyRemoteInterface { private static final String NAME = "HttpSocketTest"; private static final String REGNAME = - "//:" + TestLibrary.REGISTRY_PORT + "/" + NAME; + "//:" + TestLibrary.REGISTRY_PORT + "/" + NAME; public HttpSocketTest() throws RemoteException{} private Remote ro; public static void main(String[] args) - throws Exception + throws Exception { - - Registry registry = null; - TestLibrary.suggestSecurityManager(null); - - // Set the socket factory. - System.err.println("installing socket factory"); - RMISocketFactory.setSocketFactory(new RMIHttpToPortSocketFactory()); + Registry registry = null; - try { + TestLibrary.suggestSecurityManager(null); + + // Set the socket factory. + System.err.println("installing socket factory"); + RMISocketFactory.setSocketFactory(new RMIHttpToPortSocketFactory()); + + try { System.err.println("Starting registry"); registry = LocateRegistry.createRegistry(TestLibrary.REGISTRY_PORT); } catch (Exception e) { - TestLibrary.bomb(e); - } + TestLibrary.bomb(e); + } - try { + try { - registry.rebind( NAME, new HttpSocketTest() ); - MyRemoteInterface httpTest = - (MyRemoteInterface)Naming.lookup( REGNAME ); - httpTest.setRemoteObject( new HttpSocketTest() ); - Remote r = httpTest.getRemoteObject(); + registry.rebind( NAME, new HttpSocketTest() ); + MyRemoteInterface httpTest = + (MyRemoteInterface)Naming.lookup( REGNAME ); + httpTest.setRemoteObject( new HttpSocketTest() ); + Remote r = httpTest.getRemoteObject(); - } catch (Exception e) { - TestLibrary.bomb(e); - } + } catch (Exception e) { + TestLibrary.bomb(e); + } } public void setRemoteObject( Remote ro ) throws RemoteException { - this.ro = ro; + this.ro = ro; } public Remote getRemoteObject() throws RemoteException { - return( this.ro ); + return( this.ro ); } } - - - - - diff --git a/jdk/test/java/rmi/transport/httpSocket/HttpSocketTest_Stub.java b/jdk/test/java/rmi/transport/httpSocket/HttpSocketTest_Stub.java index d12b389d476..a8b2e342441 100644 --- a/jdk/test/java/rmi/transport/httpSocket/HttpSocketTest_Stub.java +++ b/jdk/test/java/rmi/transport/httpSocket/HttpSocketTest_Stub.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -29,102 +29,102 @@ public final class HttpSocketTest_Stub implements MyRemoteInterface, java.rmi.Remote { private static final java.rmi.server.Operation[] operations = { - new java.rmi.server.Operation("java.rmi.Remote getRemoteObject()"), - new java.rmi.server.Operation("void setRemoteObject(java.rmi.Remote)") + new java.rmi.server.Operation("java.rmi.Remote getRemoteObject()"), + new java.rmi.server.Operation("void setRemoteObject(java.rmi.Remote)") }; - + private static final long interfaceHash = 3775375480010579665L; - + private static final long serialVersionUID = 2; - + private static boolean useNewInvoke; private static java.lang.reflect.Method $method_getRemoteObject_0; private static java.lang.reflect.Method $method_setRemoteObject_1; - + static { - try { - java.rmi.server.RemoteRef.class.getMethod("invoke", - new java.lang.Class[] { - java.rmi.Remote.class, - java.lang.reflect.Method.class, - java.lang.Object[].class, - long.class - }); - useNewInvoke = true; - $method_getRemoteObject_0 = MyRemoteInterface.class.getMethod("getRemoteObject", new java.lang.Class[] {}); - $method_setRemoteObject_1 = MyRemoteInterface.class.getMethod("setRemoteObject", new java.lang.Class[] {java.rmi.Remote.class}); - } catch (java.lang.NoSuchMethodException e) { - useNewInvoke = false; - } + try { + java.rmi.server.RemoteRef.class.getMethod("invoke", + new java.lang.Class[] { + java.rmi.Remote.class, + java.lang.reflect.Method.class, + java.lang.Object[].class, + long.class + }); + useNewInvoke = true; + $method_getRemoteObject_0 = MyRemoteInterface.class.getMethod("getRemoteObject", new java.lang.Class[] {}); + $method_setRemoteObject_1 = MyRemoteInterface.class.getMethod("setRemoteObject", new java.lang.Class[] {java.rmi.Remote.class}); + } catch (java.lang.NoSuchMethodException e) { + useNewInvoke = false; + } } - + // constructors public HttpSocketTest_Stub() { - super(); + super(); } public HttpSocketTest_Stub(java.rmi.server.RemoteRef ref) { - super(ref); + super(ref); } - + // methods from remote interfaces - + // implementation of getRemoteObject() public java.rmi.Remote getRemoteObject() - throws java.rmi.RemoteException + throws java.rmi.RemoteException { - try { - if (useNewInvoke) { - Object $result = ref.invoke(this, $method_getRemoteObject_0, null, -2578437860804964265L); - return ((java.rmi.Remote) $result); - } else { - java.rmi.server.RemoteCall call = ref.newCall((java.rmi.server.RemoteObject) this, operations, 0, interfaceHash); - ref.invoke(call); - java.rmi.Remote $result; - try { - java.io.ObjectInput in = call.getInputStream(); - $result = (java.rmi.Remote) in.readObject(); - } catch (java.io.IOException e) { - throw new java.rmi.UnmarshalException("error unmarshalling return", e); - } catch (java.lang.ClassNotFoundException e) { - throw new java.rmi.UnmarshalException("error unmarshalling return", e); - } finally { - ref.done(call); - } - return $result; - } - } catch (java.lang.RuntimeException e) { - throw e; - } catch (java.rmi.RemoteException e) { - throw e; - } catch (java.lang.Exception e) { - throw new java.rmi.UnexpectedException("undeclared checked exception", e); - } + try { + if (useNewInvoke) { + Object $result = ref.invoke(this, $method_getRemoteObject_0, null, -2578437860804964265L); + return ((java.rmi.Remote) $result); + } else { + java.rmi.server.RemoteCall call = ref.newCall((java.rmi.server.RemoteObject) this, operations, 0, interfaceHash); + ref.invoke(call); + java.rmi.Remote $result; + try { + java.io.ObjectInput in = call.getInputStream(); + $result = (java.rmi.Remote) in.readObject(); + } catch (java.io.IOException e) { + throw new java.rmi.UnmarshalException("error unmarshalling return", e); + } catch (java.lang.ClassNotFoundException e) { + throw new java.rmi.UnmarshalException("error unmarshalling return", e); + } finally { + ref.done(call); + } + return $result; + } + } catch (java.lang.RuntimeException e) { + throw e; + } catch (java.rmi.RemoteException e) { + throw e; + } catch (java.lang.Exception e) { + throw new java.rmi.UnexpectedException("undeclared checked exception", e); + } } - + // implementation of setRemoteObject(Remote) public void setRemoteObject(java.rmi.Remote $param_Remote_1) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { - try { - if (useNewInvoke) { - ref.invoke(this, $method_setRemoteObject_1, new java.lang.Object[] {$param_Remote_1}, -7518632118115022871L); - } else { - java.rmi.server.RemoteCall call = ref.newCall((java.rmi.server.RemoteObject) this, operations, 1, interfaceHash); - try { - java.io.ObjectOutput out = call.getOutputStream(); - out.writeObject($param_Remote_1); - } catch (java.io.IOException e) { - throw new java.rmi.MarshalException("error marshalling arguments", e); - } - ref.invoke(call); - ref.done(call); - } - } catch (java.lang.RuntimeException e) { - throw e; - } catch (java.rmi.RemoteException e) { - throw e; - } catch (java.lang.Exception e) { - throw new java.rmi.UnexpectedException("undeclared checked exception", e); - } + try { + if (useNewInvoke) { + ref.invoke(this, $method_setRemoteObject_1, new java.lang.Object[] {$param_Remote_1}, -7518632118115022871L); + } else { + java.rmi.server.RemoteCall call = ref.newCall((java.rmi.server.RemoteObject) this, operations, 1, interfaceHash); + try { + java.io.ObjectOutput out = call.getOutputStream(); + out.writeObject($param_Remote_1); + } catch (java.io.IOException e) { + throw new java.rmi.MarshalException("error marshalling arguments", e); + } + ref.invoke(call); + ref.done(call); + } + } catch (java.lang.RuntimeException e) { + throw e; + } catch (java.rmi.RemoteException e) { + throw e; + } catch (java.lang.Exception e) { + throw new java.rmi.UnexpectedException("undeclared checked exception", e); + } } } diff --git a/jdk/test/java/rmi/transport/pinClientSocketFactory/PinClientSocketFactory.java b/jdk/test/java/rmi/transport/pinClientSocketFactory/PinClientSocketFactory.java index 23075675a90..8f1bd834b31 100644 --- a/jdk/test/java/rmi/transport/pinClientSocketFactory/PinClientSocketFactory.java +++ b/jdk/test/java/rmi/transport/pinClientSocketFactory/PinClientSocketFactory.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 2005 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -60,109 +60,109 @@ public class PinClientSocketFactory { private static final int SESSIONS = 50; public interface Factory extends Remote { - Session getSession() throws RemoteException; + Session getSession() throws RemoteException; } public interface Session extends Remote { - void ping() throws RemoteException; + void ping() throws RemoteException; } private static class FactoryImpl implements Factory { - FactoryImpl() { } - public Session getSession() throws RemoteException { - Session impl = new SessionImpl(); - UnicastRemoteObject.exportObject(impl, 0, new CSF(), new SSF()); - // return impl instead of stub to work around 4114579 - return impl; - } + FactoryImpl() { } + public Session getSession() throws RemoteException { + Session impl = new SessionImpl(); + UnicastRemoteObject.exportObject(impl, 0, new CSF(), new SSF()); + // return impl instead of stub to work around 4114579 + return impl; + } } private static class SessionImpl implements Session { - SessionImpl() { } - public void ping() { } + SessionImpl() { } + public void ping() { } } public static void main(String[] args) throws Exception { - System.err.println("\nRegression test for bug 4486732\n"); + System.err.println("\nRegression test for bug 4486732\n"); - Factory factoryImpl = new FactoryImpl(); - Factory factoryStub = - (Factory) UnicastRemoteObject.exportObject(factoryImpl, 0); - for (int i = 0; i < SESSIONS; i++) { - Session session = factoryStub.getSession(); - session.ping(); - } - UnicastRemoteObject.unexportObject(factoryImpl, true); + Factory factoryImpl = new FactoryImpl(); + Factory factoryStub = + (Factory) UnicastRemoteObject.exportObject(factoryImpl, 0); + for (int i = 0; i < SESSIONS; i++) { + Session session = factoryStub.getSession(); + session.ping(); + } + UnicastRemoteObject.unexportObject(factoryImpl, true); - Registry registryImpl = LocateRegistry.createRegistry(PORT); - CSF csf = new CSF(); - Reference registryRef = new WeakReference(csf); - Registry registryStub = LocateRegistry.getRegistry("", PORT, csf); - csf = null; - registryStub.list(); - registryStub = null; - UnicastRemoteObject.unexportObject(registryImpl, true); + Registry registryImpl = LocateRegistry.createRegistry(PORT); + CSF csf = new CSF(); + Reference registryRef = new WeakReference(csf); + Registry registryStub = LocateRegistry.getRegistry("", PORT, csf); + csf = null; + registryStub.list(); + registryStub = null; + UnicastRemoteObject.unexportObject(registryImpl, true); - System.gc(); - // allow connections to time out - Thread.sleep(3 * Long.getLong("sun.rmi.transport.connectionTimeout", - 15000)); - System.gc(); + System.gc(); + // allow connections to time out + Thread.sleep(3 * Long.getLong("sun.rmi.transport.connectionTimeout", + 15000)); + System.gc(); - if (CSF.deserializedInstances.size() != SESSIONS) { - throw new Error("unexpected number of deserialized instances: " + - CSF.deserializedInstances.size()); - } + if (CSF.deserializedInstances.size() != SESSIONS) { + throw new Error("unexpected number of deserialized instances: " + + CSF.deserializedInstances.size()); + } - int nonNullCount = 0; - for (Reference ref : CSF.deserializedInstances) { - csf = ref.get(); - if (csf != null) { - System.err.println("non-null deserialized instance: " + csf); - nonNullCount++; - } - } - if (nonNullCount > 0) { - throw new Error("TEST FAILED: " + - nonNullCount + " non-null deserialized instances"); - } + int nonNullCount = 0; + for (Reference ref : CSF.deserializedInstances) { + csf = ref.get(); + if (csf != null) { + System.err.println("non-null deserialized instance: " + csf); + nonNullCount++; + } + } + if (nonNullCount > 0) { + throw new Error("TEST FAILED: " + + nonNullCount + " non-null deserialized instances"); + } - csf = registryRef.get(); - if (csf != null) { - System.err.println("non-null registry instance: " + csf); - throw new Error("TEST FAILED: non-null registry instance"); - } + csf = registryRef.get(); + if (csf != null) { + System.err.println("non-null registry instance: " + csf); + throw new Error("TEST FAILED: non-null registry instance"); + } - System.err.println("TEST PASSED"); + System.err.println("TEST PASSED"); } private static class CSF implements RMIClientSocketFactory, Serializable { - static final List> deserializedInstances = - Collections.synchronizedList(new ArrayList>()); - private static final AtomicInteger count = new AtomicInteger(0); - private int num = count.incrementAndGet(); - CSF() { } - public Socket createSocket(String host, int port) throws IOException { - return new Socket(host, port); - } - public int hashCode() { - return num; - } - public boolean equals(Object obj) { - return obj instanceof CSF && ((CSF) obj).num == num; - } - private void readObject(ObjectInputStream in) - throws IOException, ClassNotFoundException - { - in.defaultReadObject(); - deserializedInstances.add(new WeakReference(this)); - } + static final List> deserializedInstances = + Collections.synchronizedList(new ArrayList>()); + private static final AtomicInteger count = new AtomicInteger(0); + private int num = count.incrementAndGet(); + CSF() { } + public Socket createSocket(String host, int port) throws IOException { + return new Socket(host, port); + } + public int hashCode() { + return num; + } + public boolean equals(Object obj) { + return obj instanceof CSF && ((CSF) obj).num == num; + } + private void readObject(ObjectInputStream in) + throws IOException, ClassNotFoundException + { + in.defaultReadObject(); + deserializedInstances.add(new WeakReference(this)); + } } private static class SSF implements RMIServerSocketFactory { - SSF() { } - public ServerSocket createServerSocket(int port) throws IOException { - return new ServerSocket(port); - } + SSF() { } + public ServerSocket createServerSocket(int port) throws IOException { + return new ServerSocket(port); + } } } diff --git a/jdk/test/java/rmi/transport/pinLastArguments/PinLastArguments.java b/jdk/test/java/rmi/transport/pinLastArguments/PinLastArguments.java index 590a1ce6e91..b85ad3a80c9 100644 --- a/jdk/test/java/rmi/transport/pinLastArguments/PinLastArguments.java +++ b/jdk/test/java/rmi/transport/pinLastArguments/PinLastArguments.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 2005 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -45,45 +45,45 @@ import java.rmi.server.UnicastRemoteObject; public class PinLastArguments { public interface Ping extends Remote { - void ping(Object first, Object second) throws RemoteException; + void ping(Object first, Object second) throws RemoteException; } private static class PingImpl implements Ping { - PingImpl() { } - public void ping(Object first, Object second) { - System.err.println("ping invoked: " + first + ", " + second); - } + PingImpl() { } + public void ping(Object first, Object second) { + System.err.println("ping invoked: " + first + ", " + second); + } } public static void main(String[] args) throws Exception { - System.err.println("\nRegression test for bug 6332349\n"); + System.err.println("\nRegression test for bug 6332349\n"); - Ping impl = new PingImpl(); - Reference ref = new WeakReference(impl); - try { - Ping stub = (Ping) UnicastRemoteObject.exportObject(impl, 0); - Object notSerializable = new Object(); - stub.ping(impl, null); - try { - stub.ping(impl, notSerializable); - } catch (MarshalException e) { - if (e.getCause() instanceof NotSerializableException) { - System.err.println("ping invocation failed as expected"); - } else { - throw e; - } - } - } finally { - UnicastRemoteObject.unexportObject(impl, true); - } - impl = null; + Ping impl = new PingImpl(); + Reference ref = new WeakReference(impl); + try { + Ping stub = (Ping) UnicastRemoteObject.exportObject(impl, 0); + Object notSerializable = new Object(); + stub.ping(impl, null); + try { + stub.ping(impl, notSerializable); + } catch (MarshalException e) { + if (e.getCause() instanceof NotSerializableException) { + System.err.println("ping invocation failed as expected"); + } else { + throw e; + } + } + } finally { + UnicastRemoteObject.unexportObject(impl, true); + } + impl = null; - System.gc(); + System.gc(); - if (ref.get() != null) { - throw new Error("TEST FAILED: impl not garbage collected"); - } + if (ref.get() != null) { + throw new Error("TEST FAILED: impl not garbage collected"); + } - System.err.println("TEST PASSED"); + System.err.println("TEST PASSED"); } } diff --git a/jdk/test/java/rmi/transport/rapidExportUnexport/RapidExportUnexport.java b/jdk/test/java/rmi/transport/rapidExportUnexport/RapidExportUnexport.java index bf74bf847cc..fa810c4437c 100644 --- a/jdk/test/java/rmi/transport/rapidExportUnexport/RapidExportUnexport.java +++ b/jdk/test/java/rmi/transport/rapidExportUnexport/RapidExportUnexport.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 2005 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -46,22 +46,22 @@ public class RapidExportUnexport { private static final long TIMEOUT = 60000; public static void main(String[] args) throws Exception { - System.err.println("\nRegression test for bug 6275081\n"); + System.err.println("\nRegression test for bug 6275081\n"); - Remote impl = new Remote() { }; - long start = System.currentTimeMillis(); - for (int i = 0; i < REPS; i++) { - System.err.println(i); - UnicastRemoteObject.exportObject(impl, PORT); - UnicastRemoteObject.unexportObject(impl, true); - Thread.sleep(1); // work around BindException (bug?) - } - long delta = System.currentTimeMillis() - start; - System.err.println(REPS + " export/unexport operations took " + - delta + "ms"); - if (delta > TIMEOUT) { - throw new Error("TEST FAILED: took over " + TIMEOUT + "ms"); - } - System.err.println("TEST PASSED"); + Remote impl = new Remote() { }; + long start = System.currentTimeMillis(); + for (int i = 0; i < REPS; i++) { + System.err.println(i); + UnicastRemoteObject.exportObject(impl, PORT); + UnicastRemoteObject.unexportObject(impl, true); + Thread.sleep(1); // work around BindException (bug?) + } + long delta = System.currentTimeMillis() - start; + System.err.println(REPS + " export/unexport operations took " + + delta + "ms"); + if (delta > TIMEOUT) { + throw new Error("TEST FAILED: took over " + TIMEOUT + "ms"); + } + System.err.println("TEST PASSED"); } } diff --git a/jdk/test/java/rmi/transport/readTimeout/ReadTimeoutTest.java b/jdk/test/java/rmi/transport/readTimeout/ReadTimeoutTest.java index a9c4d8b595b..0bdd65d5bb8 100644 --- a/jdk/test/java/rmi/transport/readTimeout/ReadTimeoutTest.java +++ b/jdk/test/java/rmi/transport/readTimeout/ReadTimeoutTest.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -50,134 +50,134 @@ import java.net.*; public class ReadTimeoutTest { - private static final int DELAY = 5000; // milliseconds + private static final int DELAY = 5000; // milliseconds public static void main(String[] args) - throws Exception + throws Exception { - // Make trouble for ourselves - if (System.getSecurityManager() == null) - System.setSecurityManager(new RMISecurityManager()); - - // Flaky code alert - hope this is executed before TCPTransport. - System.setProperty("sun.rmi.transport.tcp.readTimeout", Integer.toString(DELAY)); + // Make trouble for ourselves + if (System.getSecurityManager() == null) + System.setSecurityManager(new RMISecurityManager()); - // Set the socket factory. - System.err.println("(installing socket factory)"); - SomeFactory fac = new SomeFactory(); - RMISocketFactory.setSocketFactory(fac); + // Flaky code alert - hope this is executed before TCPTransport. + System.setProperty("sun.rmi.transport.tcp.readTimeout", Integer.toString(DELAY)); - // Create remote object - TestImpl impl = new TestImpl(); + // Set the socket factory. + System.err.println("(installing socket factory)"); + SomeFactory fac = new SomeFactory(); + RMISocketFactory.setSocketFactory(fac); - // Export and get which port. - System.err.println("(exporting remote object)"); - TestIface stub = impl.export(); - Socket DoS = null; - try { - int port = fac.whichPort(); + // Create remote object + TestImpl impl = new TestImpl(); - // Sanity - if (port == 0) - throw new Error("TEST FAILED: export didn't reserve a port(?)"); - - // Now, connect to that port - //Thread.sleep(2000); - System.err.println("(connecting to listening port on 127.0.0.1:" + - port + ")"); - DoS = new Socket("127.0.0.1", port); - InputStream stream = DoS.getInputStream(); + // Export and get which port. + System.err.println("(exporting remote object)"); + TestIface stub = impl.export(); + Socket DoS = null; + try { + int port = fac.whichPort(); - // Read on the socket in the background - boolean[] successful = new boolean[] { false }; - (new SomeReader(stream, successful)).start(); + // Sanity + if (port == 0) + throw new Error("TEST FAILED: export didn't reserve a port(?)"); - // Wait for completion - int nretries = 4; - while (nretries-- > 0) { - if (successful[0]) - break; - Thread.sleep(DELAY); - } + // Now, connect to that port + //Thread.sleep(2000); + System.err.println("(connecting to listening port on 127.0.0.1:" + + port + ")"); + DoS = new Socket("127.0.0.1", port); + InputStream stream = DoS.getInputStream(); - if (successful[0]) { - System.err.println("TEST PASSED."); - } else { - throw new Error("TEST FAILED."); - } + // Read on the socket in the background + boolean[] successful = new boolean[] { false }; + (new SomeReader(stream, successful)).start(); - } finally { - try { - if (DoS != null) - DoS.close(); // aborts the reader if still blocked - impl.unexport(); - } catch (Throwable unmatter) { - } - } + // Wait for completion + int nretries = 4; + while (nretries-- > 0) { + if (successful[0]) + break; + Thread.sleep(DELAY); + } - // Should exit here + if (successful[0]) { + System.err.println("TEST PASSED."); + } else { + throw new Error("TEST FAILED."); + } + + } finally { + try { + if (DoS != null) + DoS.close(); // aborts the reader if still blocked + impl.unexport(); + } catch (Throwable unmatter) { + } + } + + // Should exit here } private static class SomeFactory - extends RMISocketFactory + extends RMISocketFactory { - private int servport = 0; + private int servport = 0; - public Socket createSocket(String h, int p) - throws IOException - { - return (new Socket(h, p)); - } + public Socket createSocket(String h, int p) + throws IOException + { + return (new Socket(h, p)); + } - /** Create a server socket and remember which port it's on. - * Aborts if createServerSocket(0) is called twice, because then - * it doesn't know whether to remember the first or second port. - */ - public ServerSocket createServerSocket(int p) - throws IOException - { - ServerSocket ss; - ss = new ServerSocket(p); - if (p == 0) { - if (servport != 0) { - System.err.println("TEST FAILED: " + - "Duplicate createServerSocket(0)"); - throw new Error("Test aborted (createServerSocket)"); - } - servport = ss.getLocalPort(); - } - return (ss); - } + /** Create a server socket and remember which port it's on. + * Aborts if createServerSocket(0) is called twice, because then + * it doesn't know whether to remember the first or second port. + */ + public ServerSocket createServerSocket(int p) + throws IOException + { + ServerSocket ss; + ss = new ServerSocket(p); + if (p == 0) { + if (servport != 0) { + System.err.println("TEST FAILED: " + + "Duplicate createServerSocket(0)"); + throw new Error("Test aborted (createServerSocket)"); + } + servport = ss.getLocalPort(); + } + return (ss); + } - /** Return which port was reserved by createServerSocket(0). - * If the return value was 0, createServerSocket(0) wasn't called. - */ - public int whichPort() { - return (servport); - } + /** Return which port was reserved by createServerSocket(0). + * If the return value was 0, createServerSocket(0) wasn't called. + */ + public int whichPort() { + return (servport); + } } // end class SomeFactory protected static class SomeReader extends Thread { - private InputStream readon; - private boolean[] vec; + private InputStream readon; + private boolean[] vec; - public SomeReader(InputStream s, boolean[] successvec) { - super(); - this.setDaemon(true); - this.readon = s; - this.vec = successvec; - } + public SomeReader(InputStream s, boolean[] successvec) { + super(); + this.setDaemon(true); + this.readon = s; + this.vec = successvec; + } - public void run() { - try { - int c = this.readon.read(); - if (c != -1) - throw new Error ("Server returned " + c); - this.vec[0] = true; + public void run() { + try { + int c = this.readon.read(); + if (c != -1) + throw new Error ("Server returned " + c); + this.vec[0] = true; - } catch (IOException e) { - e.printStackTrace(); - } - } + } catch (IOException e) { + e.printStackTrace(); + } + } } // end class SomeReader } diff --git a/jdk/test/java/rmi/transport/readTimeout/TestIface.java b/jdk/test/java/rmi/transport/readTimeout/TestIface.java index 793afbba06a..a7096a0b2ca 100644 --- a/jdk/test/java/rmi/transport/readTimeout/TestIface.java +++ b/jdk/test/java/rmi/transport/readTimeout/TestIface.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -27,5 +27,5 @@ public interface TestIface extends Remote { public String testCall(String ign) - throws RemoteException; + throws RemoteException; } diff --git a/jdk/test/java/rmi/transport/readTimeout/TestImpl.java b/jdk/test/java/rmi/transport/readTimeout/TestImpl.java index eae651b5247..3fc6af8b29a 100644 --- a/jdk/test/java/rmi/transport/readTimeout/TestImpl.java +++ b/jdk/test/java/rmi/transport/readTimeout/TestImpl.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -32,19 +32,18 @@ public class TestImpl } public TestIface export() - throws RemoteException + throws RemoteException { - return (TestIface)UnicastRemoteObject.exportObject(this); + return (TestIface)UnicastRemoteObject.exportObject(this); } public void unexport() - throws NoSuchObjectException + throws NoSuchObjectException { - UnicastRemoteObject.unexportObject(this, true); + UnicastRemoteObject.unexportObject(this, true); } public String testCall(String ign) { - return ("OK"); + return ("OK"); } } - diff --git a/jdk/test/java/rmi/transport/readTimeout/TestImpl_Stub.java b/jdk/test/java/rmi/transport/readTimeout/TestImpl_Stub.java index 74c716d9136..223ce7915c5 100644 --- a/jdk/test/java/rmi/transport/readTimeout/TestImpl_Stub.java +++ b/jdk/test/java/rmi/transport/readTimeout/TestImpl_Stub.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -29,38 +29,38 @@ public final class TestImpl_Stub implements TestIface { private static final long serialVersionUID = 2; - + private static java.lang.reflect.Method $method_testCall_0; - + static { - try { - $method_testCall_0 = TestIface.class.getMethod("testCall", new java.lang.Class[] {java.lang.String.class}); - } catch (java.lang.NoSuchMethodException e) { - throw new java.lang.NoSuchMethodError( - "stub class initialization failed"); - } + try { + $method_testCall_0 = TestIface.class.getMethod("testCall", new java.lang.Class[] {java.lang.String.class}); + } catch (java.lang.NoSuchMethodException e) { + throw new java.lang.NoSuchMethodError( + "stub class initialization failed"); + } } - + // constructors public TestImpl_Stub(java.rmi.server.RemoteRef ref) { - super(ref); + super(ref); } - + // methods from remote interfaces - + // implementation of testCall(String) public java.lang.String testCall(java.lang.String $param_String_1) - throws java.rmi.RemoteException + throws java.rmi.RemoteException { - try { - Object $result = ref.invoke(this, $method_testCall_0, new java.lang.Object[] {$param_String_1}, -4495720265115653109L); - return ((java.lang.String) $result); - } catch (java.lang.RuntimeException e) { - throw e; - } catch (java.rmi.RemoteException e) { - throw e; - } catch (java.lang.Exception e) { - throw new java.rmi.UnexpectedException("undeclared checked exception", e); - } + try { + Object $result = ref.invoke(this, $method_testCall_0, new java.lang.Object[] {$param_String_1}, -4495720265115653109L); + return ((java.lang.String) $result); + } catch (java.lang.RuntimeException e) { + throw e; + } catch (java.rmi.RemoteException e) { + throw e; + } catch (java.lang.Exception e) { + throw new java.rmi.UnexpectedException("undeclared checked exception", e); + } } } diff --git a/jdk/test/java/rmi/transport/reuseDefaultPort/ReuseDefaultPort.java b/jdk/test/java/rmi/transport/reuseDefaultPort/ReuseDefaultPort.java index be40e1553a7..cf386280945 100644 --- a/jdk/test/java/rmi/transport/reuseDefaultPort/ReuseDefaultPort.java +++ b/jdk/test/java/rmi/transport/reuseDefaultPort/ReuseDefaultPort.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 2005 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -53,32 +53,32 @@ public class ReuseDefaultPort implements Remote { private ReuseDefaultPort() { } public static void main(String[] args) throws Exception { - System.err.println("\nRegression test for bug 6269166\n"); - RMISocketFactory.setSocketFactory(new SF()); - Remote impl = new ReuseDefaultPort(); - Remote stub = UnicastRemoteObject.exportObject(impl, 0); - System.err.println("- exported object: " + stub); - try { - Registry registry = LocateRegistry.createRegistry(PORT); - System.err.println("- exported registry: " + registry); - System.err.println("TEST PASSED"); - } finally { - UnicastRemoteObject.unexportObject(impl, true); - } + System.err.println("\nRegression test for bug 6269166\n"); + RMISocketFactory.setSocketFactory(new SF()); + Remote impl = new ReuseDefaultPort(); + Remote stub = UnicastRemoteObject.exportObject(impl, 0); + System.err.println("- exported object: " + stub); + try { + Registry registry = LocateRegistry.createRegistry(PORT); + System.err.println("- exported registry: " + registry); + System.err.println("TEST PASSED"); + } finally { + UnicastRemoteObject.unexportObject(impl, true); + } } private static class SF extends RMISocketFactory { - private static RMISocketFactory defaultFactory = - RMISocketFactory.getDefaultSocketFactory(); - SF() { } - public Socket createSocket(String host, int port) throws IOException { - return defaultFactory.createSocket(host, port); - } - public ServerSocket createServerSocket(int port) throws IOException { - if (port == 0) { - port = PORT; - } - return defaultFactory.createServerSocket(port); - } + private static RMISocketFactory defaultFactory = + RMISocketFactory.getDefaultSocketFactory(); + SF() { } + public Socket createSocket(String host, int port) throws IOException { + return defaultFactory.createSocket(host, port); + } + public ServerSocket createServerSocket(int port) throws IOException { + if (port == 0) { + port = PORT; + } + return defaultFactory.createServerSocket(port); + } } } diff --git a/jdk/test/java/rmi/transport/runtimeThreadInheritanceLeak/RuntimeThreadInheritanceLeak.java b/jdk/test/java/rmi/transport/runtimeThreadInheritanceLeak/RuntimeThreadInheritanceLeak.java index a2855ffe4a7..245942ddcd7 100644 --- a/jdk/test/java/rmi/transport/runtimeThreadInheritanceLeak/RuntimeThreadInheritanceLeak.java +++ b/jdk/test/java/rmi/transport/runtimeThreadInheritanceLeak/RuntimeThreadInheritanceLeak.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 2001-2003 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -60,80 +60,80 @@ public class RuntimeThreadInheritanceLeak implements Remote { public static void main(String[] args) { - System.err.println("\nRegression test for bug 4404702\n"); + System.err.println("\nRegression test for bug 4404702\n"); - /* - * HACK: Work around the fact that java.util.logging.LogManager's - * (singleton) construction also has this bug-- it will register a - * "shutdown hook", i.e. a thread, which will inherit and pin the - * current thread's context class loader for the lifetime of the VM-- - * by causing the LogManager to be initialized now, instead of by - * RMI when our special context class loader is set. - */ - java.util.logging.LogManager.getLogManager(); + /* + * HACK: Work around the fact that java.util.logging.LogManager's + * (singleton) construction also has this bug-- it will register a + * "shutdown hook", i.e. a thread, which will inherit and pin the + * current thread's context class loader for the lifetime of the VM-- + * by causing the LogManager to be initialized now, instead of by + * RMI when our special context class loader is set. + */ + java.util.logging.LogManager.getLogManager(); - /* - * HACK: Work around the fact that the non-native, thread-based - * SecureRandom seed generator (ThreadedSeedGenerator) seems to - * have this bug too (which had been causing this test to fail - * when run with jtreg on Windows XP-- see 4910382). - */ - (new java.security.SecureRandom()).nextInt(); + /* + * HACK: Work around the fact that the non-native, thread-based + * SecureRandom seed generator (ThreadedSeedGenerator) seems to + * have this bug too (which had been causing this test to fail + * when run with jtreg on Windows XP-- see 4910382). + */ + (new java.security.SecureRandom()).nextInt(); - RuntimeThreadInheritanceLeak obj = new RuntimeThreadInheritanceLeak(); + RuntimeThreadInheritanceLeak obj = new RuntimeThreadInheritanceLeak(); - try { - ClassLoader loader = URLClassLoader.newInstance(new URL[0]); - ReferenceQueue refQueue = new ReferenceQueue(); - Reference loaderRef = new WeakReference(loader, refQueue); - System.err.println("created loader: " + loader); + try { + ClassLoader loader = URLClassLoader.newInstance(new URL[0]); + ReferenceQueue refQueue = new ReferenceQueue(); + Reference loaderRef = new WeakReference(loader, refQueue); + System.err.println("created loader: " + loader); - Thread.currentThread().setContextClassLoader(loader); - UnicastRemoteObject.exportObject(obj); - Thread.currentThread().setContextClassLoader( - ClassLoader.getSystemClassLoader()); - System.err.println( - "exported remote object with loader as context class loader"); + Thread.currentThread().setContextClassLoader(loader); + UnicastRemoteObject.exportObject(obj); + Thread.currentThread().setContextClassLoader( + ClassLoader.getSystemClassLoader()); + System.err.println( + "exported remote object with loader as context class loader"); - loader = null; - System.err.println("nulled strong reference to loader"); + loader = null; + System.err.println("nulled strong reference to loader"); - UnicastRemoteObject.unexportObject(obj, true); - System.err.println("unexported remote object"); + UnicastRemoteObject.unexportObject(obj, true); + System.err.println("unexported remote object"); - /* - * HACK: Work around the fact that the sun.misc.GC daemon thread - * also has this bug-- it will have inherited our loader as its - * context class loader-- by giving it a chance to pass away. - */ - Thread.sleep(2000); - System.gc(); + /* + * HACK: Work around the fact that the sun.misc.GC daemon thread + * also has this bug-- it will have inherited our loader as its + * context class loader-- by giving it a chance to pass away. + */ + Thread.sleep(2000); + System.gc(); - System.err.println( - "waiting to be notified of loader being weakly reachable..."); - Reference dequeued = refQueue.remove(TIMEOUT); - if (dequeued == null) { - System.err.println( - "TEST FAILED: loader not deteced weakly reachable"); - dumpThreads(); - throw new RuntimeException( - "TEST FAILED: loader not detected weakly reachable"); - } + System.err.println( + "waiting to be notified of loader being weakly reachable..."); + Reference dequeued = refQueue.remove(TIMEOUT); + if (dequeued == null) { + System.err.println( + "TEST FAILED: loader not deteced weakly reachable"); + dumpThreads(); + throw new RuntimeException( + "TEST FAILED: loader not detected weakly reachable"); + } - System.err.println( - "TEST PASSED: loader detected weakly reachable"); - dumpThreads(); + System.err.println( + "TEST PASSED: loader detected weakly reachable"); + dumpThreads(); - } catch (RuntimeException e) { - throw e; - } catch (Exception e) { - throw new RuntimeException("TEST FAILED: unexpected exception", e); - } finally { - try { - UnicastRemoteObject.unexportObject(obj, true); - } catch (RemoteException e) { - } - } + } catch (RuntimeException e) { + throw e; + } catch (Exception e) { + throw new RuntimeException("TEST FAILED: unexpected exception", e); + } finally { + try { + UnicastRemoteObject.unexportObject(obj, true); + } catch (RemoteException e) { + } + } } /** @@ -141,19 +141,19 @@ public class RuntimeThreadInheritanceLeak implements Remote { * including their context class loaders. **/ private static void dumpThreads() { - System.err.println( - "current live threads and their context class loaders:"); - Map threads = Thread.getAllStackTraces(); - for (Iterator iter = threads.entrySet().iterator(); iter.hasNext();) { - Map.Entry e = (Map.Entry) iter.next(); - Thread t = (Thread) e.getKey(); - System.err.println(" thread: " + t); - System.err.println(" context class loader: " + - t.getContextClassLoader()); - StackTraceElement[] trace = (StackTraceElement[]) e.getValue(); - for (int i = 0; i < trace.length; i++) { - System.err.println(" " + trace[i]); - } - } + System.err.println( + "current live threads and their context class loaders:"); + Map threads = Thread.getAllStackTraces(); + for (Iterator iter = threads.entrySet().iterator(); iter.hasNext();) { + Map.Entry e = (Map.Entry) iter.next(); + Thread t = (Thread) e.getKey(); + System.err.println(" thread: " + t); + System.err.println(" context class loader: " + + t.getContextClassLoader()); + StackTraceElement[] trace = (StackTraceElement[]) e.getValue(); + for (int i = 0; i < trace.length; i++) { + System.err.println(" " + trace[i]); + } + } } } diff --git a/jdk/test/java/rmi/transport/runtimeThreadInheritanceLeak/RuntimeThreadInheritanceLeak_Stub.java b/jdk/test/java/rmi/transport/runtimeThreadInheritanceLeak/RuntimeThreadInheritanceLeak_Stub.java index 016142118f9..bc17d11e8db 100644 --- a/jdk/test/java/rmi/transport/runtimeThreadInheritanceLeak/RuntimeThreadInheritanceLeak_Stub.java +++ b/jdk/test/java/rmi/transport/runtimeThreadInheritanceLeak/RuntimeThreadInheritanceLeak_Stub.java @@ -1,4 +1,4 @@ -/* +/* * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -29,10 +29,10 @@ public final class RuntimeThreadInheritanceLeak_Stub implements java.rmi.Remote { private static final long serialVersionUID = 2; - + // constructors public RuntimeThreadInheritanceLeak_Stub(java.rmi.server.RemoteRef ref) { - super(ref); + super(ref); } - + } From 659a8dc7d5553fd0edee1c08a77361c480bb767d Mon Sep 17 00:00:00 2001 From: Vladimir Kozlov Date: Tue, 1 Apr 2008 16:14:18 -0700 Subject: [PATCH 125/258] 6681646: Relocking of a scalar replaced object during deoptimization is broken Relocking of a thread-local object during deoptimization is broken Reviewed-by: kbr, jrose, never --- .../src/share/vm/runtime/deoptimization.cpp | 55 ++++++++++++------- .../src/share/vm/runtime/deoptimization.hpp | 2 +- hotspot/src/share/vm/runtime/vframe.cpp | 2 +- hotspot/src/share/vm/runtime/vframe.hpp | 5 +- hotspot/src/share/vm/runtime/vframe_hp.cpp | 4 +- 5 files changed, 44 insertions(+), 24 deletions(-) diff --git a/hotspot/src/share/vm/runtime/deoptimization.cpp b/hotspot/src/share/vm/runtime/deoptimization.cpp index 444925938be..ccca77a5e13 100644 --- a/hotspot/src/share/vm/runtime/deoptimization.cpp +++ b/hotspot/src/share/vm/runtime/deoptimization.cpp @@ -143,6 +143,7 @@ Deoptimization::UnrollBlock* Deoptimization::fetch_unroll_info_helper(JavaThread // relock objects if synchronization on them was eliminated. if (DoEscapeAnalysis) { if (EliminateAllocations) { + assert (chunk->at(0)->scope() != NULL,"expect only compiled java frames"); GrowableArray* objects = chunk->at(0)->scope()->objects(); bool reallocated = false; if (objects != NULL) { @@ -162,19 +163,26 @@ Deoptimization::UnrollBlock* Deoptimization::fetch_unroll_info_helper(JavaThread } } if (EliminateLocks) { +#ifndef PRODUCT + bool first = true; +#endif for (int i = 0; i < chunk->length(); i++) { - GrowableArray* monitors = chunk->at(i)->scope()->monitors(); - if (monitors != NULL) { - relock_objects(&deoptee, &map, monitors); + compiledVFrame* cvf = chunk->at(i); + assert (cvf->scope() != NULL,"expect only compiled java frames"); + GrowableArray* monitors = cvf->monitors(); + if (monitors->is_nonempty()) { + relock_objects(monitors, thread); #ifndef PRODUCT if (TraceDeoptimization) { ttyLocker ttyl; - tty->print_cr("RELOCK OBJECTS in thread " INTPTR_FORMAT, thread); for (int j = 0; j < monitors->length(); j++) { - MonitorValue* mv = monitors->at(j); - if (mv->eliminated()) { - StackValue* owner = StackValue::create_stack_value(&deoptee, &map, mv->owner()); - tty->print_cr(" object <" INTPTR_FORMAT "> locked", owner->get_obj()()); + MonitorInfo* mi = monitors->at(j); + if (mi->eliminated()) { + if (first) { + first = false; + tty->print_cr("RELOCK OBJECTS in thread " INTPTR_FORMAT, thread); + } + tty->print_cr(" object <" INTPTR_FORMAT "> locked", mi->owner()); } } } @@ -799,18 +807,27 @@ void Deoptimization::reassign_fields(frame* fr, RegisterMap* reg_map, GrowableAr // relock objects for which synchronization was eliminated -void Deoptimization::relock_objects(frame* fr, RegisterMap* reg_map, GrowableArray* monitors) { +void Deoptimization::relock_objects(GrowableArray* monitors, JavaThread* thread) { for (int i = 0; i < monitors->length(); i++) { - MonitorValue* mv = monitors->at(i); - StackValue* owner = StackValue::create_stack_value(fr, reg_map, mv->owner()); - if (mv->eliminated()) { - Handle obj = owner->get_obj(); - assert(obj.not_null(), "reallocation was missed"); - BasicLock* lock = StackValue::resolve_monitor_lock(fr, mv->basic_lock()); - lock->set_displaced_header(obj->mark()); - obj->set_mark((markOop) lock); + MonitorInfo* mon_info = monitors->at(i); + if (mon_info->eliminated()) { + assert(mon_info->owner() != NULL, "reallocation was missed"); + Handle obj = Handle(mon_info->owner()); + markOop mark = obj->mark(); + if (UseBiasedLocking && mark->has_bias_pattern()) { + // New allocated objects may have the mark set to anonymously biased. + // Also the deoptimized method may called methods with synchronization + // where the thread-local object is bias locked to the current thread. + assert(mark->is_biased_anonymously() || + mark->biased_locker() == thread, "should be locked to current thread"); + // Reset mark word to unbiased prototype. + markOop unbiased_prototype = markOopDesc::prototype()->set_age(mark->age()); + obj->set_mark(unbiased_prototype); + } + BasicLock* lock = mon_info->lock(); + ObjectSynchronizer::slow_enter(obj, lock, thread); } - assert(owner->get_obj()->is_locked(), "object must be locked now"); + assert(mon_info->owner()->is_locked(), "object must be locked now"); } } @@ -916,7 +933,7 @@ static void collect_monitors(compiledVFrame* cvf, GrowableArray* objects GrowableArray* monitors = cvf->monitors(); for (int i = 0; i < monitors->length(); i++) { MonitorInfo* mon_info = monitors->at(i); - if (mon_info->owner() != NULL) { + if (mon_info->owner() != NULL && !mon_info->eliminated()) { objects_to_revoke->append(Handle(mon_info->owner())); } } diff --git a/hotspot/src/share/vm/runtime/deoptimization.hpp b/hotspot/src/share/vm/runtime/deoptimization.hpp index 63565704a69..6edb6a08936 100644 --- a/hotspot/src/share/vm/runtime/deoptimization.hpp +++ b/hotspot/src/share/vm/runtime/deoptimization.hpp @@ -105,7 +105,7 @@ class Deoptimization : AllStatic { static void reassign_type_array_elements(frame* fr, RegisterMap* reg_map, ObjectValue* sv, typeArrayOop obj, BasicType type); static void reassign_object_array_elements(frame* fr, RegisterMap* reg_map, ObjectValue* sv, objArrayOop obj); static void reassign_fields(frame* fr, RegisterMap* reg_map, GrowableArray* objects); - static void relock_objects(frame* fr, RegisterMap* reg_map, GrowableArray* monitors); + static void relock_objects(GrowableArray* monitors, JavaThread* thread); NOT_PRODUCT(static void print_objects(GrowableArray* objects);) #endif // COMPILER2 diff --git a/hotspot/src/share/vm/runtime/vframe.cpp b/hotspot/src/share/vm/runtime/vframe.cpp index fdb2864df39..3e9b65bfc03 100644 --- a/hotspot/src/share/vm/runtime/vframe.cpp +++ b/hotspot/src/share/vm/runtime/vframe.cpp @@ -206,7 +206,7 @@ GrowableArray* interpretedVFrame::monitors() const { for (BasicObjectLock* current = (fr().previous_monitor_in_interpreter_frame(fr().interpreter_frame_monitor_begin())); current >= fr().interpreter_frame_monitor_end(); current = fr().previous_monitor_in_interpreter_frame(current)) { - result->push(new MonitorInfo(current->obj(), current->lock())); + result->push(new MonitorInfo(current->obj(), current->lock(), false)); } return result; } diff --git a/hotspot/src/share/vm/runtime/vframe.hpp b/hotspot/src/share/vm/runtime/vframe.hpp index b62a6f76ffb..2b1b827b1fd 100644 --- a/hotspot/src/share/vm/runtime/vframe.hpp +++ b/hotspot/src/share/vm/runtime/vframe.hpp @@ -230,15 +230,18 @@ class MonitorInfo : public ResourceObj { private: oop _owner; // the object owning the monitor BasicLock* _lock; + bool _eliminated; public: // Constructor - MonitorInfo(oop owner, BasicLock* lock) { + MonitorInfo(oop owner, BasicLock* lock, bool eliminated) { _owner = owner; _lock = lock; + _eliminated = eliminated; } // Accessors oop owner() const { return _owner; } BasicLock* lock() const { return _lock; } + bool eliminated() const { return _eliminated; } }; class vframeStreamCommon : StackObj { diff --git a/hotspot/src/share/vm/runtime/vframe_hp.cpp b/hotspot/src/share/vm/runtime/vframe_hp.cpp index 3399e23a5d8..35f0713a23f 100644 --- a/hotspot/src/share/vm/runtime/vframe_hp.cpp +++ b/hotspot/src/share/vm/runtime/vframe_hp.cpp @@ -190,7 +190,7 @@ GrowableArray* compiledVFrame::monitors() const { // Casting away const frame& fr = (frame&) _fr; MonitorInfo* info = new MonitorInfo(fr.compiled_synchronized_native_monitor_owner(nm), - fr.compiled_synchronized_native_monitor(nm)); + fr.compiled_synchronized_native_monitor(nm), false); monitors->push(info); return monitors; } @@ -202,7 +202,7 @@ GrowableArray* compiledVFrame::monitors() const { for (int index = 0; index < monitors->length(); index++) { MonitorValue* mv = monitors->at(index); StackValue *owner_sv = create_stack_value(mv->owner()); // it is an oop - result->push(new MonitorInfo(owner_sv->get_obj()(), resolve_monitor_lock(mv->basic_lock()))); + result->push(new MonitorInfo(owner_sv->get_obj()(), resolve_monitor_lock(mv->basic_lock()), mv->eliminated())); } return result; } From 70bcd151a03823c0034918b74bf8ecc44cefbf89 Mon Sep 17 00:00:00 2001 From: Maurizio Cimadamore Date: Wed, 2 Apr 2008 11:20:52 +0100 Subject: [PATCH 126/258] 6569789: Compiler test lang/TYPE/type153/type15304/type15304.html fails since jdk7 b05 Improved glb on type-inference Reviewed-by: jjg --- .../com/sun/tools/javac/comp/Infer.java | 13 ++++++ .../generics/inference/6569789/T6569789.java | 44 +++++++++++++++++++ 2 files changed, 57 insertions(+) create mode 100644 langtools/test/tools/javac/generics/inference/6569789/T6569789.java diff --git a/langtools/src/share/classes/com/sun/tools/javac/comp/Infer.java b/langtools/src/share/classes/com/sun/tools/javac/comp/Infer.java index 071d2fc60f2..3539a50c9e0 100644 --- a/langtools/src/share/classes/com/sun/tools/javac/comp/Infer.java +++ b/langtools/src/share/classes/com/sun/tools/javac/comp/Infer.java @@ -157,6 +157,19 @@ public class Infer { if (isSubClass(bs.head, that.hibounds)) that.inst = types.fromUnknownFun.apply(bs.head); } + if (that.inst == null) { + int classCount = 0, interfaceCount = 0; + for (Type t : that.hibounds) { + if (t.tag == CLASS) { + if (t.isInterface()) + interfaceCount++; + else + classCount++; + } + } + if ((that.hibounds.size() == classCount + interfaceCount) && classCount == 1) + that.inst = types.makeCompoundType(that.hibounds); + } if (that.inst == null || !types.isSubtypeUnchecked(that.inst, that.hibounds, warn)) throw ambiguousNoInstanceException .setMessage("no.unique.maximal.instance.exists", diff --git a/langtools/test/tools/javac/generics/inference/6569789/T6569789.java b/langtools/test/tools/javac/generics/inference/6569789/T6569789.java new file mode 100644 index 00000000000..d7036ff98f7 --- /dev/null +++ b/langtools/test/tools/javac/generics/inference/6569789/T6569789.java @@ -0,0 +1,44 @@ +/* + * Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* + * @test + * @bug 6569789 + * @summary Compiler test lang/TYPE/type153/type15304/type15304.html fails since jdk7 b05 + * @compile T6569789.java + */ + +class C {} +interface I {} +interface I1 {} +interface I2 {} +class CT extends C implements I, I1, I2 {} + +public class T6569789 { + public static void m() { + CT ct = new CT(); + testMethod(ct); + } + + static void testMethod(T t) {} +} \ No newline at end of file From 8ef814eb9cf39794f4126044b8d699195ba77b2c Mon Sep 17 00:00:00 2001 From: Maurizio Cimadamore Date: Wed, 2 Apr 2008 11:38:16 +0100 Subject: [PATCH 127/258] 6509042: javac rejects class literals in enum constructors Javac now distinguish between enum class literals and static fields Reviewed-by: jjg --- .../com/sun/tools/javac/comp/Attr.java | 14 +++++-- langtools/test/tools/javac/enum/T6509042.java | 41 +++++++++++++++++++ 2 files changed, 51 insertions(+), 4 deletions(-) create mode 100644 langtools/test/tools/javac/enum/T6509042.java diff --git a/langtools/src/share/classes/com/sun/tools/javac/comp/Attr.java b/langtools/src/share/classes/com/sun/tools/javac/comp/Attr.java index f597bc7f3e6..89fa13892f7 100644 --- a/langtools/src/share/classes/com/sun/tools/javac/comp/Attr.java +++ b/langtools/src/share/classes/com/sun/tools/javac/comp/Attr.java @@ -2199,7 +2199,7 @@ public class Attr extends JCTree.Visitor { (env.tree.getTag() != JCTree.ASSIGN || TreeInfo.skipParens(((JCAssign) env.tree).lhs) != tree)) { - if (!onlyWarning || isNonStaticEnumField(v)) { + if (!onlyWarning || isStaticEnumField(v)) { log.error(tree.pos(), "illegal.forward.ref"); } else if (useBeforeDeclarationWarning) { log.warning(tree.pos(), "forward.ref", v); @@ -2233,7 +2233,7 @@ public class Attr extends JCTree.Visitor { // initializer expressions of an enum constant e to refer // to itself or to an enum constant of the same type that // is declared to the right of e." - if (isNonStaticEnumField(v)) { + if (isStaticEnumField(v)) { ClassSymbol enclClass = env.info.scope.owner.enclClass(); if (enclClass == null || enclClass.owner == null) @@ -2254,8 +2254,14 @@ public class Attr extends JCTree.Visitor { } } - private boolean isNonStaticEnumField(VarSymbol v) { - return Flags.isEnum(v.owner) && Flags.isStatic(v) && !Flags.isConstant(v); + /** Is the given symbol a static, non-constant field of an Enum? + * Note: enum literals should not be regarded as such + */ + private boolean isStaticEnumField(VarSymbol v) { + return Flags.isEnum(v.owner) && + Flags.isStatic(v) && + !Flags.isConstant(v) && + v.name != names._class; } /** Can the given symbol be the owner of code which forms part diff --git a/langtools/test/tools/javac/enum/T6509042.java b/langtools/test/tools/javac/enum/T6509042.java new file mode 100644 index 00000000000..53a59bfc74b --- /dev/null +++ b/langtools/test/tools/javac/enum/T6509042.java @@ -0,0 +1,41 @@ +/* + * Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* + * @test + * @bug 6509042 + * + * @summary javac rejects class literals in enum constructors + * @author Maurizio Cimadamore + * + * @compile T6509042.java + */ +enum T6509042 { + A, B; + + Class cl = T6509042.class; + + T6509042() { + Class cl2 = T6509042.class; + } +} From 1be460dbdd9cf0ded00118c01a119489b718cf6e Mon Sep 17 00:00:00 2001 From: Maurizio Cimadamore Date: Wed, 2 Apr 2008 11:44:23 +0100 Subject: [PATCH 128/258] 6531090: Cannot access methods/fields of a captured type belonging to an intersection type Fixed lookup of field/methods on intersection types Reviewed-by: jjg --- .../com/sun/tools/javac/code/Types.java | 7 +- .../com/sun/tools/javac/comp/Resolve.java | 8 +- .../javac/generics/6531090/T6531090a.java | 59 +++++++++++++ .../javac/generics/6531090/T6531090b.java | 82 +++++++++++++++++++ 4 files changed, 152 insertions(+), 4 deletions(-) create mode 100644 langtools/test/tools/javac/generics/6531090/T6531090a.java create mode 100644 langtools/test/tools/javac/generics/6531090/T6531090b.java diff --git a/langtools/src/share/classes/com/sun/tools/javac/code/Types.java b/langtools/src/share/classes/com/sun/tools/javac/code/Types.java index 070bf9d541f..c9cc2cef6be 100644 --- a/langtools/src/share/classes/com/sun/tools/javac/code/Types.java +++ b/langtools/src/share/classes/com/sun/tools/javac/code/Types.java @@ -1298,7 +1298,7 @@ public class Types { return t; Type st = supertype(t); - if (st.tag == CLASS || st.tag == ERROR) { + if (st.tag == CLASS || st.tag == TYPEVAR || st.tag == ERROR) { Type x = asSuper(st, sym); if (x != null) return x; @@ -1320,7 +1320,10 @@ public class Types { @Override public Type visitTypeVar(TypeVar t, Symbol sym) { - return asSuper(t.bound, sym); + if (t.tsym == sym) + return t; + else + return asSuper(t.bound, sym); } @Override diff --git a/langtools/src/share/classes/com/sun/tools/javac/comp/Resolve.java b/langtools/src/share/classes/com/sun/tools/javac/comp/Resolve.java index 1df0bb72571..f567133ddae 100644 --- a/langtools/src/share/classes/com/sun/tools/javac/comp/Resolve.java +++ b/langtools/src/share/classes/com/sun/tools/javac/comp/Resolve.java @@ -407,6 +407,8 @@ public class Resolve { Type site, Name name, TypeSymbol c) { + while (c.type.tag == TYPEVAR) + c = c.type.getUpperBound().tsym; Symbol bestSoFar = varNotFound; Symbol sym; Scope.Entry e = c.members().lookup(name); @@ -418,7 +420,7 @@ public class Resolve { e = e.next(); } Type st = types.supertype(c.type); - if (st != null && st.tag == CLASS) { + if (st != null && (st.tag == CLASS || st.tag == TYPEVAR)) { sym = findField(env, site, name, st.tsym); if (sym.kind < bestSoFar.kind) bestSoFar = sym; } @@ -733,7 +735,9 @@ public class Resolve { boolean allowBoxing, boolean useVarargs, boolean operator) { - for (Type ct = intype; ct.tag == CLASS; ct = types.supertype(ct)) { + for (Type ct = intype; ct.tag == CLASS || ct.tag == TYPEVAR; ct = types.supertype(ct)) { + while (ct.tag == TYPEVAR) + ct = ct.getUpperBound(); ClassSymbol c = (ClassSymbol)ct.tsym; if ((c.flags() & (ABSTRACT | INTERFACE)) == 0) abstractok = false; diff --git a/langtools/test/tools/javac/generics/6531090/T6531090a.java b/langtools/test/tools/javac/generics/6531090/T6531090a.java new file mode 100644 index 00000000000..f00235ebfbe --- /dev/null +++ b/langtools/test/tools/javac/generics/6531090/T6531090a.java @@ -0,0 +1,59 @@ +/* + * Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* + * @test + * @bug 6531090 + * + * @summary Cannot access methods/fields of a captured type belonging to an intersection type + * @author Maurizio Cimadamore + * + */ +public class T6531090a { + + static class E {} + + static class F extends E implements I1 {} + + static interface I {} + + static interface I1 {} + + static class G extends F implements I {} + + static class C { + T field; + } + + public static void main(String... args) { + test(new C()); + } + + static void test(C arg) { + F vf = arg.field; + I vi = arg.field; + I1 vi1 = arg.field; + E ve = arg.field; + W vt = arg.field; + } +} diff --git a/langtools/test/tools/javac/generics/6531090/T6531090b.java b/langtools/test/tools/javac/generics/6531090/T6531090b.java new file mode 100644 index 00000000000..ede819f32d6 --- /dev/null +++ b/langtools/test/tools/javac/generics/6531090/T6531090b.java @@ -0,0 +1,82 @@ +/* + * Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* + * @test + * @bug 6531090 + * + * @summary Cannot access methods/fields of a captured type belonging to an intersection type + * @author Maurizio Cimadamore + * + */ +public class T6531090b { + + static class A { + public void a() {} + public A a; + } + static class B extends A { + public void b(){} + public B b; + } + static interface I{ + void i(); + } + static interface I1{ + void i1(); + } + static class E extends B implements I, I1{ + public void i() {} + public void i1() {} + } + static class C{ + T t; + W w; + C(W w, T t) { + this.w = w; + this.t = t; + } + } + + public static void main(String... args) { + C c = new C(new E(), new E()); + testMemberMethods(c); + testMemberFields(c); + } + + static void testMemberMethods(C arg) { + arg.t.a(); + arg.t.b(); + arg.t.i1(); + arg.w.a(); + arg.w.b(); + arg.w.i1(); + } + + static void testMemberFields(C arg) { + A ta = arg.t.a; + B tb = arg.t.b; + A wa = arg.w.a; + B wb = arg.w.b; + } +} From e95ef5ac2170dd730b7923f7ba2b785fddde00c7 Mon Sep 17 00:00:00 2001 From: Roman Kennke Date: Wed, 2 Apr 2008 17:45:50 +0400 Subject: [PATCH 129/258] 6677332: incorrect signatures for JNI methods in XWindow.c and XlibWrapper.c Int replaced with jint in XWindow.c and WlibWrapper.c, and BOOL replaced with Bool in MouseInfo.c. Reviewed-by: anthony --- jdk/src/solaris/native/sun/awt/MouseInfo.c | 4 ++-- jdk/src/solaris/native/sun/xawt/XWindow.c | 2 +- jdk/src/solaris/native/sun/xawt/XlibWrapper.c | 8 ++++---- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/jdk/src/solaris/native/sun/awt/MouseInfo.c b/jdk/src/solaris/native/sun/awt/MouseInfo.c index 368ccab8cdd..f2716680174 100644 --- a/jdk/src/solaris/native/sun/awt/MouseInfo.c +++ b/jdk/src/solaris/native/sun/awt/MouseInfo.c @@ -54,7 +54,7 @@ Java_sun_awt_DefaultMouseInfoPeer_fillPointWithCoords(JNIEnv *env, jclass cls, int i; int32_t xr, yr, xw, yw; uint32_t keys; - BOOL pointerFound; + Bool pointerFound; AWT_LOCK(); if (pointClass == NULL) { @@ -102,7 +102,7 @@ JNIEXPORT jboolean JNICALL Java_sun_awt_DefaultMouseInfoPeer_isWindowUnderMouse int32_t xr = 0, yr = 0, xw = 0, yw = 0; uint32_t keys = 0; uint32_t nchildren = 0; - BOOL pointerFound = 0; + Bool pointerFound = 0; struct FrameData *wdata = NULL; jobject winPeer = NULL; diff --git a/jdk/src/solaris/native/sun/xawt/XWindow.c b/jdk/src/solaris/native/sun/xawt/XWindow.c index a72187ef3fb..0690e58ad2c 100644 --- a/jdk/src/solaris/native/sun/xawt/XWindow.c +++ b/jdk/src/solaris/native/sun/xawt/XWindow.c @@ -1234,7 +1234,7 @@ Java_sun_awt_X11_XWindow_initIDs } } -JNIEXPORT int JNICALL +JNIEXPORT jint JNICALL Java_sun_awt_X11_XWindow_getKeySymForAWTKeyCode(JNIEnv* env, jclass clazz, jint keycode) { return awt_getX11KeySym(keycode); } diff --git a/jdk/src/solaris/native/sun/xawt/XlibWrapper.c b/jdk/src/solaris/native/sun/xawt/XlibWrapper.c index 01d5def24c4..6884b366f09 100644 --- a/jdk/src/solaris/native/sun/xawt/XlibWrapper.c +++ b/jdk/src/solaris/native/sun/xawt/XlibWrapper.c @@ -359,7 +359,7 @@ JNIEXPORT void JNICALL Java_sun_awt_X11_XlibWrapper_XDestroyWindow XDestroyWindow( (Display *)jlong_to_ptr(display),(Window) window); } -JNIEXPORT int JNICALL Java_sun_awt_X11_XlibWrapper_XGrabPointer +JNIEXPORT jint JNICALL Java_sun_awt_X11_XlibWrapper_XGrabPointer (JNIEnv *env, jclass clazz, jlong display, jlong window, jint owner_events, jint event_mask, jint pointer_mode, jint keyboard_mode, jlong confine_to, jlong cursor, jlong time) @@ -377,7 +377,7 @@ JNIEXPORT void JNICALL Java_sun_awt_X11_XlibWrapper_XUngrabPointer XUngrabPointer( (Display *)jlong_to_ptr(display), (Time) time); } -JNIEXPORT int JNICALL Java_sun_awt_X11_XlibWrapper_XGrabKeyboard +JNIEXPORT jint JNICALL Java_sun_awt_X11_XlibWrapper_XGrabKeyboard (JNIEnv *env, jclass clazz, jlong display, jlong window, jint owner_events, jint pointer_mode, jint keyboard_mode, jlong time) @@ -621,7 +621,7 @@ JNIEXPORT void JNICALL Java_sun_awt_X11_XlibWrapper_XSync } -JNIEXPORT int JNICALL Java_sun_awt_X11_XlibWrapper_XTranslateCoordinates +JNIEXPORT jint JNICALL Java_sun_awt_X11_XlibWrapper_XTranslateCoordinates (JNIEnv *env, jclass clazz, jlong display, jlong src_w, jlong dest_w, jlong src_x, jlong src_y, jlong dest_x_return, jlong dest_y_return, jlong child_return) @@ -634,7 +634,7 @@ JNIEXPORT int JNICALL Java_sun_awt_X11_XlibWrapper_XTranslateCoordinates (Window *) jlong_to_ptr(child_return)); } -JNIEXPORT int JNICALL Java_sun_awt_X11_XlibWrapper_XEventsQueued +JNIEXPORT jint JNICALL Java_sun_awt_X11_XlibWrapper_XEventsQueued (JNIEnv *env, jclass clazz, jlong display, jint mode) { AWT_CHECK_HAVE_LOCK(); From 0d27a8639f0af075d3952984d525c8e139dc7c74 Mon Sep 17 00:00:00 2001 From: John R Rose Date: Wed, 2 Apr 2008 12:09:59 -0700 Subject: [PATCH 130/258] 6667042: PrintAssembly option does not work without special plugin Remove old private plugin interface, simplify, rework old plugin to use unchanged Gnu sources Reviewed-by: kvn, rasbold --- hotspot/.hgignore | 1 + hotspot/build/linux/makefiles/vm.make | 2 + hotspot/build/linux/platform_amd64 | 2 - hotspot/build/linux/platform_i486 | 2 - hotspot/build/linux/platform_sparc | 2 - hotspot/build/solaris/makefiles/vm.make | 2 + hotspot/build/solaris/platform_amd64 | 2 - hotspot/build/solaris/platform_amd64.gcc | 2 - hotspot/build/solaris/platform_i486 | 2 - hotspot/build/solaris/platform_i486.gcc | 2 - hotspot/build/solaris/platform_sparc | 2 - hotspot/build/solaris/platform_sparc.gcc | 2 - hotspot/build/solaris/platform_sparcv9 | 4 +- hotspot/build/solaris/platform_sparcv9.gcc | 4 +- hotspot/build/windows/makefiles/vm.make | 1 + hotspot/build/windows/platform_amd64 | 4 +- hotspot/build/windows/platform_i486 | 5 +- .../src/cpu/sparc/vm/disassembler_sparc.cpp | 230 -------- .../src/cpu/sparc/vm/disassembler_sparc.hpp | 35 +- hotspot/src/cpu/x86/vm/disassembler_x86.cpp | 201 ------- hotspot/src/cpu/x86/vm/disassembler_x86.hpp | 28 +- hotspot/src/share/tools/hsdis/Makefile | 135 +++++ hotspot/src/share/tools/hsdis/README | 95 ++++ hotspot/src/share/tools/hsdis/hsdis-demo.c | 223 ++++++++ hotspot/src/share/tools/hsdis/hsdis.c | 499 ++++++++++++++++++ hotspot/src/share/tools/hsdis/hsdis.h | 67 +++ hotspot/src/share/vm/asm/codeBuffer.cpp | 1 + hotspot/src/share/vm/code/nmethod.cpp | 55 +- hotspot/src/share/vm/code/nmethod.hpp | 8 +- hotspot/src/share/vm/code/vmreg.cpp | 2 - hotspot/src/share/vm/code/vmreg.hpp | 10 +- .../src/share/vm/compiler/disassembler.cpp | 443 ++++++++++++++++ .../src/share/vm/compiler/disassembler.hpp | 59 +++ .../src/share/vm/compiler/disassemblerEnv.hpp | 35 -- hotspot/src/share/vm/compiler/oopMap.cpp | 15 +- hotspot/src/share/vm/compiler/oopMap.hpp | 6 +- hotspot/src/share/vm/includeDB_compiler1 | 2 +- hotspot/src/share/vm/includeDB_core | 42 +- hotspot/src/share/vm/opto/compile.cpp | 10 +- hotspot/src/share/vm/runtime/globals.hpp | 19 +- .../share/vm/runtime/stubCodeGenerator.cpp | 4 - hotspot/src/share/vm/utilities/ostream.cpp | 36 +- hotspot/src/share/vm/utilities/ostream.hpp | 3 +- 43 files changed, 1675 insertions(+), 629 deletions(-) delete mode 100644 hotspot/src/cpu/sparc/vm/disassembler_sparc.cpp delete mode 100644 hotspot/src/cpu/x86/vm/disassembler_x86.cpp create mode 100644 hotspot/src/share/tools/hsdis/Makefile create mode 100644 hotspot/src/share/tools/hsdis/README create mode 100644 hotspot/src/share/tools/hsdis/hsdis-demo.c create mode 100644 hotspot/src/share/tools/hsdis/hsdis.c create mode 100644 hotspot/src/share/tools/hsdis/hsdis.h create mode 100644 hotspot/src/share/vm/compiler/disassembler.cpp create mode 100644 hotspot/src/share/vm/compiler/disassembler.hpp delete mode 100644 hotspot/src/share/vm/compiler/disassemblerEnv.hpp diff --git a/hotspot/.hgignore b/hotspot/.hgignore index 8c4cff4cd1f..6798eb94087 100644 --- a/hotspot/.hgignore +++ b/hotspot/.hgignore @@ -168,3 +168,4 @@ ^build/linux/export-linux-x64/ ^dist/ ^nbproject/private/ +^src/share/tools/hsdis/bin/ diff --git a/hotspot/build/linux/makefiles/vm.make b/hotspot/build/linux/makefiles/vm.make index 567e6779145..72e6dbdd3dc 100644 --- a/hotspot/build/linux/makefiles/vm.make +++ b/hotspot/build/linux/makefiles/vm.make @@ -71,6 +71,7 @@ endif # The following variables are defined in the generated flags.make file. BUILD_VERSION = -DHOTSPOT_RELEASE_VERSION="\"$(HS_BUILD_VER)\"" JRE_VERSION = -DJRE_RELEASE_VERSION="\"$(JRE_RELEASE_VER)\"" +HS_LIB_ARCH = -DHOTSPOT_LIB_ARCH=\"$(LIBARCH)\" BUILD_TARGET = -DHOTSPOT_BUILD_TARGET="\"$(TARGET)\"" BUILD_USER = -DHOTSPOT_BUILD_USER="\"$(HOTSPOT_BUILD_USER)\"" VM_DISTRO = -DHOTSPOT_VM_DISTRO="\"$(HOTSPOT_VM_DISTRO)\"" @@ -81,6 +82,7 @@ CPPFLAGS = \ ${BUILD_VERSION} \ ${BUILD_TARGET} \ ${BUILD_USER} \ + ${HS_LIB_ARCH} \ ${JRE_VERSION} \ ${VM_DISTRO} diff --git a/hotspot/build/linux/platform_amd64 b/hotspot/build/linux/platform_amd64 index 2a76633d259..b612635958e 100644 --- a/hotspot/build/linux/platform_amd64 +++ b/hotspot/build/linux/platform_amd64 @@ -12,6 +12,4 @@ lib_arch = amd64 compiler = gcc -gnu_dis_arch = amd64 - sysdefs = -DLINUX -D_GNU_SOURCE -DAMD64 diff --git a/hotspot/build/linux/platform_i486 b/hotspot/build/linux/platform_i486 index 7f8b111675b..610ac91ce79 100644 --- a/hotspot/build/linux/platform_i486 +++ b/hotspot/build/linux/platform_i486 @@ -12,6 +12,4 @@ lib_arch = i386 compiler = gcc -gnu_dis_arch = i386 - sysdefs = -DLINUX -D_GNU_SOURCE -DIA32 diff --git a/hotspot/build/linux/platform_sparc b/hotspot/build/linux/platform_sparc index 2fda1971bd6..8d9e3ee7201 100644 --- a/hotspot/build/linux/platform_sparc +++ b/hotspot/build/linux/platform_sparc @@ -12,6 +12,4 @@ lib_arch = sparc compiler = gcc -gnu_dis_arch = sparc - sysdefs = -DLINUX -D_GNU_SOURCE -DSPARC diff --git a/hotspot/build/solaris/makefiles/vm.make b/hotspot/build/solaris/makefiles/vm.make index c1fa4643129..4d0df028840 100644 --- a/hotspot/build/solaris/makefiles/vm.make +++ b/hotspot/build/solaris/makefiles/vm.make @@ -63,6 +63,7 @@ endif # The following variables are defined in the generated flags.make file. BUILD_VERSION = -DHOTSPOT_RELEASE_VERSION="\"$(HS_BUILD_VER)\"" JRE_VERSION = -DJRE_RELEASE_VERSION="\"$(JRE_RELEASE_VER)\"" +HS_LIB_ARCH = -DHOTSPOT_LIB_ARCH=\"$(LIBARCH)\" BUILD_TARGET = -DHOTSPOT_BUILD_TARGET="\"$(TARGET)\"" BUILD_USER = -DHOTSPOT_BUILD_USER="\"$(HOTSPOT_BUILD_USER)\"" VM_DISTRO = -DHOTSPOT_VM_DISTRO="\"$(HOTSPOT_VM_DISTRO)\"" @@ -73,6 +74,7 @@ CPPFLAGS = \ ${BUILD_VERSION} \ ${BUILD_TARGET} \ ${BUILD_USER} \ + ${HS_LIB_ARCH} \ ${JRE_VERSION} \ ${VM_DISTRO} diff --git a/hotspot/build/solaris/platform_amd64 b/hotspot/build/solaris/platform_amd64 index 2cfe3d41681..f85242b1d30 100644 --- a/hotspot/build/solaris/platform_amd64 +++ b/hotspot/build/solaris/platform_amd64 @@ -12,6 +12,4 @@ lib_arch = amd64 compiler = sparcWorks -gnu_dis_arch = amd64 - sysdefs = -DSOLARIS -DSPARC_WORKS -DAMD64 diff --git a/hotspot/build/solaris/platform_amd64.gcc b/hotspot/build/solaris/platform_amd64.gcc index 57d25fa6f44..ebd495bca40 100644 --- a/hotspot/build/solaris/platform_amd64.gcc +++ b/hotspot/build/solaris/platform_amd64.gcc @@ -12,6 +12,4 @@ lib_arch = amd64 compiler = gcc -gnu_dis_arch = amd64 - sysdefs = -DSOLARIS -D_GNU_SOURCE -DAMD64 diff --git a/hotspot/build/solaris/platform_i486 b/hotspot/build/solaris/platform_i486 index c6902160b1f..91d4c5e7a64 100644 --- a/hotspot/build/solaris/platform_i486 +++ b/hotspot/build/solaris/platform_i486 @@ -12,6 +12,4 @@ lib_arch = i386 compiler = sparcWorks -gnu_dis_arch = i386 - sysdefs = -DSOLARIS -DSPARC_WORKS -DIA32 diff --git a/hotspot/build/solaris/platform_i486.gcc b/hotspot/build/solaris/platform_i486.gcc index 8d1d57ff596..61d55e1b59e 100644 --- a/hotspot/build/solaris/platform_i486.gcc +++ b/hotspot/build/solaris/platform_i486.gcc @@ -12,6 +12,4 @@ lib_arch = i386 compiler = gcc -gnu_dis_arch = i386 - sysdefs = -DSOLARIS -D_GNU_SOURCE -DIA32 diff --git a/hotspot/build/solaris/platform_sparc b/hotspot/build/solaris/platform_sparc index 4ff94c3ae68..424088ef53f 100644 --- a/hotspot/build/solaris/platform_sparc +++ b/hotspot/build/solaris/platform_sparc @@ -12,6 +12,4 @@ lib_arch = sparc compiler = sparcWorks -gnu_dis_arch = sparc - sysdefs = -DSOLARIS -DSPARC_WORKS -DSPARC diff --git a/hotspot/build/solaris/platform_sparc.gcc b/hotspot/build/solaris/platform_sparc.gcc index 87d42becfa3..9a900f49384 100644 --- a/hotspot/build/solaris/platform_sparc.gcc +++ b/hotspot/build/solaris/platform_sparc.gcc @@ -12,6 +12,4 @@ lib_arch = sparc compiler = gcc -gnu_dis_arch = sparc - sysdefs = -DSOLARIS -D_GNU_SOURCE -DSPARC diff --git a/hotspot/build/solaris/platform_sparcv9 b/hotspot/build/solaris/platform_sparcv9 index 4ff94c3ae68..a17dd08d29d 100644 --- a/hotspot/build/solaris/platform_sparcv9 +++ b/hotspot/build/solaris/platform_sparcv9 @@ -8,10 +8,8 @@ os_arch = solaris_sparc os_arch_model = solaris_sparc -lib_arch = sparc +lib_arch = sparcv9 compiler = sparcWorks -gnu_dis_arch = sparc - sysdefs = -DSOLARIS -DSPARC_WORKS -DSPARC diff --git a/hotspot/build/solaris/platform_sparcv9.gcc b/hotspot/build/solaris/platform_sparcv9.gcc index 87d42becfa3..2824381774b 100644 --- a/hotspot/build/solaris/platform_sparcv9.gcc +++ b/hotspot/build/solaris/platform_sparcv9.gcc @@ -8,10 +8,8 @@ os_arch = solaris_sparc os_arch_model = solaris_sparc -lib_arch = sparc +lib_arch = sparcv9 compiler = gcc -gnu_dis_arch = sparc - sysdefs = -DSOLARIS -D_GNU_SOURCE -DSPARC diff --git a/hotspot/build/windows/makefiles/vm.make b/hotspot/build/windows/makefiles/vm.make index ddfc8729678..c911ab261f0 100644 --- a/hotspot/build/windows/makefiles/vm.make +++ b/hotspot/build/windows/makefiles/vm.make @@ -58,6 +58,7 @@ CPP_FLAGS=$(CPP_FLAGS) /D "COMPILER1" /D "COMPILER2" # The following variables are defined in the generated local.make file. CPP_FLAGS=$(CPP_FLAGS) /D "HOTSPOT_RELEASE_VERSION=\"$(HS_BUILD_VER)\"" CPP_FLAGS=$(CPP_FLAGS) /D "JRE_RELEASE_VERSION=\"$(JRE_RELEASE_VER)\"" +CPP_FLAGS=$(CPP_FLAGS) /D "HOTSPOT_LIB_ARCH=\"$(BUILDARCH)\"" CPP_FLAGS=$(CPP_FLAGS) /D "HOTSPOT_BUILD_TARGET=\"$(BUILD_FLAVOR)\"" CPP_FLAGS=$(CPP_FLAGS) /D "HOTSPOT_BUILD_USER=\"$(BuildUser)\"" CPP_FLAGS=$(CPP_FLAGS) /D "HOTSPOT_VM_DISTRO=\"$(HOTSPOT_VM_DISTRO)\"" diff --git a/hotspot/build/windows/platform_amd64 b/hotspot/build/windows/platform_amd64 index e19b4878163..49a326e5690 100644 --- a/hotspot/build/windows/platform_amd64 +++ b/hotspot/build/windows/platform_amd64 @@ -10,6 +10,6 @@ os_arch = windows_x86 os_arch_model = windows_x86_64 -compiler = visCPP +lib_arch = amd64 -gnu_dis_arch = amd64 +compiler = visCPP diff --git a/hotspot/build/windows/platform_i486 b/hotspot/build/windows/platform_i486 index a426305fb5d..bdb31681038 100644 --- a/hotspot/build/windows/platform_i486 +++ b/hotspot/build/windows/platform_i486 @@ -10,7 +10,6 @@ os_arch = windows_x86 os_arch_model = windows_x86_32 +lib_arch = i386 + compiler = visCPP - -gnu_dis_arch = i386 - diff --git a/hotspot/src/cpu/sparc/vm/disassembler_sparc.cpp b/hotspot/src/cpu/sparc/vm/disassembler_sparc.cpp deleted file mode 100644 index fc7cc059798..00000000000 --- a/hotspot/src/cpu/sparc/vm/disassembler_sparc.cpp +++ /dev/null @@ -1,230 +0,0 @@ -/* - * Copyright 1997-2007 Sun Microsystems, Inc. All Rights Reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - * - */ - -# include "incls/_precompiled.incl" -# include "incls/_disassembler_sparc.cpp.incl" - -#ifndef PRODUCT - -#define SPARC_VERSION (VM_Version::v9_instructions_work()? \ - (VM_Version::v8_instructions_work()? "" : "9") : "8") - -// This routine is in the shared library: -typedef unsigned char* print_insn_sparc_t(unsigned char* start, DisassemblerEnv* env, - const char* sparc_version); - -void* Disassembler::_library = NULL; -dll_func Disassembler::_print_insn_sparc = NULL; - -bool Disassembler::load_library() { - if (_library == NULL) { - char buf[1024]; - char ebuf[1024]; - sprintf(buf, "disassembler%s", os::dll_file_extension()); - _library = hpi::dll_load(buf, ebuf, sizeof ebuf); - if (_library != NULL) { - tty->print_cr("Loaded disassembler"); - _print_insn_sparc = CAST_TO_FN_PTR(dll_func, hpi::dll_lookup(_library, "print_insn_sparc")); - } - } - return (_library != NULL) && (_print_insn_sparc != NULL); -} - - -class sparc_env : public DisassemblerEnv { - private: - nmethod* code; - outputStream* output; - const char* version; - - static void print_address(address value, outputStream* st); - - public: - sparc_env(nmethod* rcode, outputStream* routput) { - code = rcode; - output = routput; - version = SPARC_VERSION; - } - const char* sparc_version() { return version; } - void print_label(intptr_t value); - void print_raw(char* str) { output->print_raw(str); } - void print(char* format, ...); - char* string_for_offset(intptr_t value); - char* string_for_constant(unsigned char* pc, intptr_t value, int is_decimal); -}; - - -void sparc_env::print_address(address adr, outputStream* st) { - if (!Universe::is_fully_initialized()) { - st->print(INTPTR_FORMAT, (intptr_t)adr); - return; - } - if (StubRoutines::contains(adr)) { - StubCodeDesc *desc = StubCodeDesc::desc_for(adr); - if (desc == NULL) - desc = StubCodeDesc::desc_for(adr + frame::pc_return_offset); - if (desc == NULL) - st->print("Unknown stub at " INTPTR_FORMAT, adr); - else { - st->print("Stub::%s", desc->name()); - if (desc->begin() != adr) - st->print("%+d 0x%p",adr - desc->begin(), adr); - else if (WizardMode) st->print(" " INTPTR_FORMAT, adr); - } - } else { - BarrierSet* bs = Universe::heap()->barrier_set(); - if (bs->kind() == BarrierSet::CardTableModRef && - adr == (address)((CardTableModRefBS*)(bs))->byte_map_base) { - st->print("word_map_base"); - if (WizardMode) st->print(" " INTPTR_FORMAT, (intptr_t)adr); - } else { - st->print(INTPTR_FORMAT, (intptr_t)adr); - } - } -} - - -// called by the disassembler to print out jump addresses -void sparc_env::print_label(intptr_t value) { - print_address((address) value, output); -} - -void sparc_env::print(char* format, ...) { - va_list ap; - va_start(ap, format); - output->vprint(format, ap); - va_end(ap); -} - -char* sparc_env::string_for_offset(intptr_t value) { - stringStream st; - print_address((address) value, &st); - return st.as_string(); -} - -char* sparc_env::string_for_constant(unsigned char* pc, intptr_t value, int is_decimal) { - stringStream st; - oop obj; - if (code && (obj = code->embeddedOop_at(pc)) != NULL) { - obj->print_value_on(&st); - } else - { - print_address((address) value, &st); - } - return st.as_string(); -} - - -address Disassembler::decode_instruction(address start, DisassemblerEnv* env) { - const char* version = ((sparc_env*)env)->sparc_version(); - return ((print_insn_sparc_t*) _print_insn_sparc)(start, env, version); -} - - -const int show_bytes = false; // for disassembler debugging - - -void Disassembler::decode(CodeBlob* cb, outputStream* st) { - st = st ? st : tty; - st->print_cr("Decoding CodeBlob " INTPTR_FORMAT, cb); - decode(cb->instructions_begin(), cb->instructions_end(), st); -} - - -void Disassembler::decode(u_char* begin, u_char* end, outputStream* st) { - assert ((((intptr_t)begin | (intptr_t)end) % sizeof(int) == 0), "misaligned insn addr"); - st = st ? st : tty; - if (!load_library()) { - st->print_cr("Could not load disassembler"); - return; - } - sparc_env env(NULL, st); - unsigned char* p = (unsigned char*) begin; - CodeBlob* cb = CodeCache::find_blob_unsafe(begin); - while (p < (unsigned char*) end && p) { - if (cb != NULL) { - cb->print_block_comment(st, (intptr_t)(p - cb->instructions_begin())); - } - - unsigned char* p0 = p; - st->print(INTPTR_FORMAT ": ", p); - p = decode_instruction(p, &env); - if (show_bytes && p) { - st->print("\t\t\t"); - while (p0 < p) { st->print("%08lx ", *(int*)p0); p0 += sizeof(int); } - } - st->cr(); - } -} - - -void Disassembler::decode(nmethod* nm, outputStream* st) { - st = st ? st : tty; - - st->print_cr("Decoding compiled method " INTPTR_FORMAT ":", nm); - st->print("Code:"); - st->cr(); - - if (!load_library()) { - st->print_cr("Could not load disassembler"); - return; - } - sparc_env env(nm, st); - unsigned char* p = nm->instructions_begin(); - unsigned char* end = nm->instructions_end(); - assert ((((intptr_t)p | (intptr_t)end) % sizeof(int) == 0), "misaligned insn addr"); - - unsigned char *p1 = p; - int total_bucket_count = 0; - while (p1 < end && p1) { - unsigned char *p0 = p1; - ++p1; - address bucket_pc = FlatProfiler::bucket_start_for(p1); - if (bucket_pc != NULL && bucket_pc > p0 && bucket_pc <= p1) - total_bucket_count += FlatProfiler::bucket_count_for(p0); - } - - while (p < end && p) { - if (p == nm->entry_point()) st->print_cr("[Entry Point]"); - if (p == nm->verified_entry_point()) st->print_cr("[Verified Entry Point]"); - if (p == nm->exception_begin()) st->print_cr("[Exception Handler]"); - if (p == nm->stub_begin()) st->print_cr("[Stub Code]"); - if (p == nm->consts_begin()) st->print_cr("[Constants]"); - nm->print_block_comment(st, (intptr_t)(p - nm->instructions_begin())); - unsigned char* p0 = p; - st->print(" " INTPTR_FORMAT ": ", p); - p = decode_instruction(p, &env); - nm->print_code_comment_on(st, 40, p0, p); - st->cr(); - // Output pc bucket ticks if we have any - address bucket_pc = FlatProfiler::bucket_start_for(p); - if (bucket_pc != NULL && bucket_pc > p0 && bucket_pc <= p) { - int bucket_count = FlatProfiler::bucket_count_for(p0); - tty->print_cr("%3.1f%% [%d]", bucket_count*100.0/total_bucket_count, bucket_count); - tty->cr(); - } - } -} - -#endif // PRODUCT diff --git a/hotspot/src/cpu/sparc/vm/disassembler_sparc.hpp b/hotspot/src/cpu/sparc/vm/disassembler_sparc.hpp index 827488b8e20..343f96d968d 100644 --- a/hotspot/src/cpu/sparc/vm/disassembler_sparc.hpp +++ b/hotspot/src/cpu/sparc/vm/disassembler_sparc.hpp @@ -1,5 +1,5 @@ /* - * Copyright 1997-1999 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1997-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -22,30 +22,11 @@ * */ -// The disassembler prints out sparc code annotated -// with Java specific information. + static int pd_instruction_alignment() { + return sizeof(int); + } -class Disassembler { -#ifndef PRODUCT - private: - // points to the library. - static void* _library; - // points to the print_insn_sparc function. - static dll_func _print_insn_sparc; - // tries to load library and return whether it succedded. - static bool load_library(); - // decodes one instruction and return the start of the next instruction. - static address decode_instruction(address start, DisassemblerEnv* env); -#endif - public: - static void decode(CodeBlob *cb, outputStream* st = NULL) PRODUCT_RETURN; - static void decode(nmethod* nm, outputStream* st = NULL) PRODUCT_RETURN; - static void decode(u_char* begin, u_char* end, outputStream* st = NULL) PRODUCT_RETURN; -}; - -//Reconciliation History -// 1.9 98/04/29 10:45:51 disassembler_i486.hpp -// 1.10 98/05/11 16:47:20 disassembler_i486.hpp -// 1.12 99/06/22 16:37:37 disassembler_i486.hpp -// 1.13 99/08/06 10:09:04 disassembler_i486.hpp -//End + static const char* pd_cpu_opts() { + return (VM_Version::v9_instructions_work()? + (VM_Version::v8_instructions_work()? "" : "v9only") : "v8only"); + } diff --git a/hotspot/src/cpu/x86/vm/disassembler_x86.cpp b/hotspot/src/cpu/x86/vm/disassembler_x86.cpp deleted file mode 100644 index 9e75de3548a..00000000000 --- a/hotspot/src/cpu/x86/vm/disassembler_x86.cpp +++ /dev/null @@ -1,201 +0,0 @@ -/* - * Copyright 1997-2007 Sun Microsystems, Inc. All Rights Reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - * - */ - -# include "incls/_precompiled.incl" -# include "incls/_disassembler_x86.cpp.incl" - -#ifndef PRODUCT - -void* Disassembler::_library = NULL; -Disassembler::decode_func Disassembler::_decode_instruction = NULL; - -bool Disassembler::load_library() { - if (_library == NULL) { - char buf[1024]; - char ebuf[1024]; - sprintf(buf, "disassembler%s", os::dll_file_extension()); - _library = hpi::dll_load(buf, ebuf, sizeof ebuf); - if (_library != NULL) { - tty->print_cr("Loaded disassembler"); - _decode_instruction = CAST_TO_FN_PTR(Disassembler::decode_func, hpi::dll_lookup(_library, "decode_instruction")); - } - } - return (_library != NULL) && (_decode_instruction != NULL); -} - -class x86_env : public DisassemblerEnv { - private: - nmethod* code; - outputStream* output; - public: - x86_env(nmethod* rcode, outputStream* routput) { - code = rcode; - output = routput; - } - void print_label(intptr_t value); - void print_raw(char* str) { output->print_raw(str); } - void print(char* format, ...); - char* string_for_offset(intptr_t value); - char* string_for_constant(unsigned char* pc, intptr_t value, int is_decimal); -}; - - -void x86_env::print_label(intptr_t value) { - if (!Universe::is_fully_initialized()) { - output->print(INTPTR_FORMAT, value); - return; - } - address adr = (address) value; - if (StubRoutines::contains(adr)) { - StubCodeDesc* desc = StubCodeDesc::desc_for(adr); - const char * desc_name = "unknown stub"; - if (desc != NULL) { - desc_name = desc->name(); - } - output->print("Stub::%s", desc_name); - if (WizardMode) output->print(" " INTPTR_FORMAT, value); - } else { - output->print(INTPTR_FORMAT, value); - } -} - -void x86_env::print(char* format, ...) { - va_list ap; - va_start(ap, format); - output->vprint(format, ap); - va_end(ap); -} - -char* x86_env::string_for_offset(intptr_t value) { - stringStream st; - if (!Universe::is_fully_initialized()) { - st.print(INTX_FORMAT, value); - return st.as_string(); - } - BarrierSet* bs = Universe::heap()->barrier_set(); - BarrierSet::Name bsn = bs->kind(); - if (bs->kind() == BarrierSet::CardTableModRef && - (jbyte*) value == ((CardTableModRefBS*)(bs))->byte_map_base) { - st.print("word_map_base"); - } else { - st.print(INTX_FORMAT, value); - } - return st.as_string(); -} - -char* x86_env::string_for_constant(unsigned char* pc, intptr_t value, int is_decimal) { - stringStream st; - oop obj = NULL; - if (code && ((obj = code->embeddedOop_at(pc)) != NULL)) { - obj->print_value_on(&st); - } else { - if (is_decimal == 1) { - st.print(INTX_FORMAT, value); - } else { - st.print(INTPTR_FORMAT, value); - } - } - return st.as_string(); -} - - - -address Disassembler::decode_instruction(address start, DisassemblerEnv* env) { - return ((decode_func) _decode_instruction)(start, env); -} - - -void Disassembler::decode(CodeBlob* cb, outputStream* st) { - st = st ? st : tty; - st->print_cr("Decoding CodeBlob " INTPTR_FORMAT, cb); - decode(cb->instructions_begin(), cb->instructions_end(), st); -} - - -void Disassembler::decode(u_char* begin, u_char* end, outputStream* st) { - st = st ? st : tty; - - const int show_bytes = false; // for disassembler debugging - - if (!load_library()) { - st->print_cr("Could not load disassembler"); - return; - } - - x86_env env(NULL, st); - unsigned char* p = (unsigned char*) begin; - CodeBlob* cb = CodeCache::find_blob_unsafe(begin); - while (p < (unsigned char*) end) { - if (cb != NULL) { - cb->print_block_comment(st, (intptr_t)(p - cb->instructions_begin())); - } - - unsigned char* p0 = p; - st->print(" " INTPTR_FORMAT ": ", p); - p = decode_instruction(p, &env); - if (show_bytes) { - st->print("\t\t\t"); - while (p0 < p) st->print("%x ", *p0++); - } - st->cr(); - } -} - - -void Disassembler::decode(nmethod* nm, outputStream* st) { - st = st ? st : tty; - - st->print_cr("Decoding compiled method " INTPTR_FORMAT ":", nm); - st->print("Code:"); - st->cr(); - - if (!load_library()) { - st->print_cr("Could not load disassembler"); - return; - } - x86_env env(nm, st); - unsigned char* p = nm->instructions_begin(); - unsigned char* end = nm->instructions_end(); - while (p < end) { - if (p == nm->entry_point()) st->print_cr("[Entry Point]"); - if (p == nm->verified_entry_point()) st->print_cr("[Verified Entry Point]"); - if (p == nm->exception_begin()) st->print_cr("[Exception Handler]"); - if (p == nm->stub_begin()) st->print_cr("[Stub Code]"); - if (p == nm->consts_begin()) st->print_cr("[Constants]"); - nm->print_block_comment(st, (intptr_t)(p - nm->instructions_begin())); - unsigned char* p0 = p; - st->print(" " INTPTR_FORMAT ": ", p); - p = decode_instruction(p, &env); - nm->print_code_comment_on(st, 40, p0, p); - st->cr(); - // Output pc bucket ticks if we have any - address bucket_pc = FlatProfiler::bucket_start_for(p); - if (bucket_pc != NULL && bucket_pc > p0 && bucket_pc <= p) { - int bucket_count = FlatProfiler::bucket_count_for(bucket_pc); - tty->print_cr("[%d]", bucket_count); - } - } -} - -#endif // PRODUCT diff --git a/hotspot/src/cpu/x86/vm/disassembler_x86.hpp b/hotspot/src/cpu/x86/vm/disassembler_x86.hpp index 75da808aedb..bdf7d3500b0 100644 --- a/hotspot/src/cpu/x86/vm/disassembler_x86.hpp +++ b/hotspot/src/cpu/x86/vm/disassembler_x86.hpp @@ -1,5 +1,5 @@ /* - * Copyright 1997-1999 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1997-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -22,24 +22,10 @@ * */ -// The disassembler prints out intel 386 code annotated -// with Java specific information. + static int pd_instruction_alignment() { + return 1; + } -class Disassembler { -#ifndef PRODUCT - private: - typedef address (*decode_func)(address start, DisassemblerEnv* env); - // points the library. - static void* _library; - // points to the decode function. - static decode_func _decode_instruction; - // tries to load library and return whether it succedded. - static bool load_library(); - // decodes one instruction and return the start of the next instruction. - static address decode_instruction(address start, DisassemblerEnv* env); -#endif - public: - static void decode(CodeBlob *cb, outputStream* st = NULL) PRODUCT_RETURN; - static void decode(nmethod* nm, outputStream* st = NULL) PRODUCT_RETURN; - static void decode(u_char* begin, u_char* end, outputStream* st = NULL) PRODUCT_RETURN; -}; + static const char* pd_cpu_opts() { + return ""; + } diff --git a/hotspot/src/share/tools/hsdis/Makefile b/hotspot/src/share/tools/hsdis/Makefile new file mode 100644 index 00000000000..6bdf4b8151c --- /dev/null +++ b/hotspot/src/share/tools/hsdis/Makefile @@ -0,0 +1,135 @@ +# +# Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. +# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. +# +# This code is free software; you can redistribute it and/or modify it +# under the terms of the GNU General Public License version 2 only, as +# published by the Free Software Foundation. +# +# This code is distributed in the hope that it will be useful, but WITHOUT +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +# version 2 for more details (a copy is included in the LICENSE file that +# accompanied this code). +# +# You should have received a copy of the GNU General Public License version +# 2 along with this work; if not, write to the Free Software Foundation, +# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. +# +# Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, +# CA 95054 USA or visit www.sun.com if you need additional information or +# have any questions. +# +# + +# Single gnu makefile for solaris, linux and windows (windows requires mks or +# cygwin). + +ifeq ($(BINUTILS),) +# Pop all the way out of the workspace to look for binutils. +# ...You probably want to override this setting. +BINUTILS = $(shell cd ../../../../..;pwd)/binutils-2.17-$(LIBARCH) +endif + +# Default arch; it is changed below as needed. +ARCH = i386 +OS = $(shell uname) + +CPPFLAGS += -I$(BINUTILS)/include -I$(BINUTILS)/bfd +CPPFLAGS += -DHOTSPOT_LIB_ARCH=\"$(LIBARCH)\" -DLIBARCH_$(LIBARCH) +CPPFLAGS += -DHOTSPOT_OS=\"$(OS)\" -DOS_$(OS) + +## OS = SunOS ## +ifeq ($(OS),SunOS) +ARCH = $(shell uname -p) +OS = solaris +CC = cc +CCFLAGS += -Kpic -g +CCFLAGS/amd64 += -xarch=amd64 +CCFLAGS/sparcv9 += -xarch=v9 +CCFLAGS += $(CCFLAGS/$(LIBARCH)) +DLDFLAGS += -G +OUTFLAGS += -o $@ +LIB_EXT = .so +else +## OS = Linux ## +ifeq ($(OS),Linux) +CPU = $(shell uname -m) +ifeq ($(CPU),ia64) +ARCH = ia64 +else +ifeq ($(CPU),x86_64) +CCFLAGS += -fPIC +endif # x86_64 +endif # ia64 +OS = linux +CC = gcc +CCFLAGS += -O +DLDFLAGS += -shared +OUTFLAGS += -o $@ +LIB_EXT = .so +CPPFLAGS += -Iinclude -Iinclude/$(OS)_$(ARCH)/ +## OS = Windows ## +else # !SunOS, !Linux => Windows +OS = win +CC = cl +#CPPFLAGS += /D"WIN32" /D"_WINDOWS" /D"DEBUG" /D"NDEBUG" +CCFLAGS += /nologo /MD /W3 /WX /O2 /Fo$(@:.dll=.obj) /Gi- +CCFLAGS += -Iinclude -Iinclude/gnu -Iinclude/$(OS)_$(ARCH) +CCFLAGS += /D"HOTSPOT_LIB_ARCH=\"$(LIBARCH)\"" +DLDFLAGS += /dll /subsystem:windows /incremental:no \ + /export:decode_instruction +OUTFLAGS += /link /out:$@ +LIB_EXT = .dll +endif # Linux +endif # SunOS + +LIBARCH = $(ARCH) +ifdef LP64 +LIBARCH64/sparc = sparcv9 +LIBARCH64/i386 = amd64 +LIBARCH64 = $(LIBARCH64/$(ARCH)) +ifneq ($(LIBARCH64),) +LIBARCH = $(LIBARCH64) +endif # LIBARCH64/$(ARCH) +endif # LP64 + +TARGET_DIR = bin/$(OS) +TARGET = $(TARGET_DIR)/hsdis-$(LIBARCH)$(LIB_EXT) + +SOURCE = hsdis.c + +LIBRARIES = $(BINUTILS)/bfd/libbfd.a \ + $(BINUTILS)/opcodes/libopcodes.a \ + $(BINUTILS)/libiberty/libiberty.a + +DEMO_TARGET = $(TARGET_DIR)/hsdis-demo-$(LIBARCH) +DEMO_SOURCE = hsdis-demo.c + +.PHONY: all clean demo both + +all: $(TARGET) demo + +both: all all64 + +%64: + $(MAKE) LP64=1 ${@:%64=%} + +demo: $(TARGET) $(DEMO_TARGET) + +$(LIBRARIES): + @echo "*** Please build binutils first; see ./README: ***" + @sed < ./README '1,/__________/d' | head -20 + @echo "..."; exit 1 + +$(TARGET): $(SOURCE) $(LIBS) $(LIBRARIES) $(TARGET_DIR) + $(CC) $(OUTFLAGS) $(CPPFLAGS) $(CCFLAGS) $(SOURCE) $(DLDFLAGS) $(LIBRARIES) + +$(DEMO_TARGET): $(DEMO_SOURCE) $(TARGET) $(TARGET_DIR) + $(CC) $(OUTFLAGS) $(CPPFLAGS) $(CCFLAGS) $(DEMO_SOURCE) $(LDFLAGS) + +$(TARGET_DIR): + [ -d $@ ] || mkdir -p $@ + +clean: + rm -rf $(TARGET_DIR) diff --git a/hotspot/src/share/tools/hsdis/README b/hotspot/src/share/tools/hsdis/README new file mode 100644 index 00000000000..76c92a44ed8 --- /dev/null +++ b/hotspot/src/share/tools/hsdis/README @@ -0,0 +1,95 @@ +Copyright (c) 2008 Sun Microsystems, Inc. All Rights Reserved. +DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + +This code is free software; you can redistribute it and/or modify it +under the terms of the GNU General Public License version 2 only, as +published by the Free Software Foundation. + +This code is distributed in the hope that it will be useful, but WITHOUT +ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +version 2 for more details (a copy is included in the LICENSE file that +accompanied this code). + +You should have received a copy of the GNU General Public License version +2 along with this work; if not, write to the Free Software Foundation, +Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + +Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, +CA 95054 USA or visit www.sun.com if you need additional information or +have any questions. + +________________________________________________________________________ + +'hsdis': A HotSpot plugin for disassembling dynamically generated code. + +The files in this directory (Makefile, hsdis.[ch], hsdis-demo.c) +are built independently of the HotSpot JVM. + +To use the plugin with a JVM, you need a new version that can load it. +If the product mode of your JVM does not accept -XX:+PrintAssembly, +you do not have a version that is new enough. + +* Building + +To build this project you need a build of Gnu binutils to link against. +It is known to work with binutils 2.17. + +The makefile looks for this build in $BINUTILS, or (if that is not set), +in .../binutils-2.17-$LIBARCH, where LIBARCH (as in HotSpot) is one of +the jre subdirectory keywords i386, amd64, sparc, sparcv9, etc. + +To build Gnu binutils, first download a copy of the software: + http://directory.fsf.org/project/binutils/ + +Unpack the binutils tarball into an empty directory: + chdir ../../../../.. + tar -xzf - < ../binutils-2.17.tar.gz + mv binutils-2.17 binutils-2.17-i386 #or binutils-2.17-sparc + cd binutils-2.17-i386 + +From inside that directory, run configure and make: + ( export CFLAGS='-fPIC' + ./configure i386-pc-elf ) + gnumake + +(Leave out or change the argument to configure if not on an i386 system.) + +Next, untar again into another empty directory for the LP64 version: + chdir .. + tar -xzf - < ../binutils-2.17.tar.gz + mv binutils-2.17 binutils-2.17-amd64 #or binutils-2.17-sparcv9 + cd binutils-2.17-amd64 + +From inside that directory, run configure for LP64 and make: + ( export ac_cv_c_bigendian=no CFLAGS='-m64 -fPIC' LDFLAGS=-m64 + ./configure amd64-pc-elf ) + gnumake + +The -fPIC option is needed because the generated code will be +linked into the hsdid-$LIBARCH.so binary. If you miss the +option, the JVM will fail to load the disassembler. + +You probably want two builds, one for 32 and one for 64 bits. +To build the 64-bit variation of a platforn, add LP64=1 to +the make command line for hsdis. + +So, go back to the hsdis project and build: + chdir .../hsdis + gnumake + gnumake LP64=1 + +* Installing + +Products are named like bin/$OS/hsdis-$LIBARCH.so. +You can install them on your LD_LIBRARY_PATH, +or inside of your JRE next to $LIBARCH/libjvm.so. + +Now test: + export LD_LIBRARY_PATH .../hsdis/bin/solaris:$LD_LIBRARY_PATH + dargs='-XX:+UnlockDiagnosticVMOptions -XX:+PrintAssembly' + dargs=$dargs' -XX:PrintAssemblyOptions=hsdis-print-bytes' + java $dargs -Xbatch CompileCommand=print,*String.hashCode HelloWorld + +If the product mode of the JVM does not accept -XX:+PrintAssembly, +you do not have a version new enough to use the hsdis plugin. diff --git a/hotspot/src/share/tools/hsdis/hsdis-demo.c b/hotspot/src/share/tools/hsdis/hsdis-demo.c new file mode 100644 index 00000000000..adea76e63d7 --- /dev/null +++ b/hotspot/src/share/tools/hsdis/hsdis-demo.c @@ -0,0 +1,223 @@ +/* + * Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + * + */ + +/* hsdis-demo.c -- dump a range of addresses as native instructions + This demonstrates the protocol required by the HotSpot PrintAssembly option. +*/ + +#include "hsdis.h" + +#include "stdio.h" +#include "stdlib.h" +#include "string.h" + +void greet(const char*); +void disassemble(void*, void*); +void end_of_file(); + +const char* options = NULL; +int raw = 0; +int xml = 0; + +int main(int ac, char** av) { + int greeted = 0; + int i; + for (i = 1; i < ac; i++) { + const char* arg = av[i]; + if (arg[0] == '-') { + if (!strcmp(arg, "-xml")) + xml ^= 1; + else if (!strcmp(arg, "-raw")) + raw ^= 1; + else if (!strncmp(arg, "-options=", 9)) + options = arg+9; + else + { printf("Usage: %s [-xml] [name...]\n"); exit(2); } + continue; + } + greet(arg); + greeted = 1; + } + if (!greeted) + greet("world"); + printf("...And now for something completely different:\n"); + disassemble((void*) &main, (void*) &end_of_file); + printf("Cheers!\n"); +} + +void greet(const char* whom) { + printf("Hello, %s!\n", whom); +} + +void end_of_file() { } + +/* don't disassemble after this point... */ + +#include "dlfcn.h" + +#ifdef HOTSPOT_LIB_ARCH +#define LIBARCH HOTSPOT_LIB_ARCH +#endif +#ifdef HOTSPOT_OS +#define OS HOTSPOT_OS +#endif + +#define DECODE_INSTRUCTIONS_NAME "decode_instructions" +#define HSDIS_NAME "hsdis" +static void* decode_instructions_pv = 0; +static const char* hsdis_path[] = { + HSDIS_NAME".so", +#ifdef OS + "bin/"OS"/"HSDIS_NAME".so", +#endif +#ifdef LIBARCH + HSDIS_NAME"-"LIBARCH".so", +#ifdef OS + "bin/"OS"/"HSDIS_NAME"-"LIBARCH".so", +#endif +#endif + NULL +}; + +static const char* load_decode_instructions() { + void* dllib = NULL; + const char* *next_in_path = hsdis_path; + while (1) { + decode_instructions_pv = dlsym(dllib, DECODE_INSTRUCTIONS_NAME); + if (decode_instructions_pv != NULL) + return NULL; + if (dllib != NULL) + return "plugin does not defined "DECODE_INSTRUCTIONS_NAME; + for (dllib = NULL; dllib == NULL; ) { + const char* next_lib = (*next_in_path++); + if (next_lib == NULL) + return "cannot find plugin "HSDIS_NAME".so"; + dllib = dlopen(next_lib, RTLD_LAZY); + } + } +} + + +static const char* lookup(void* addr) { +#define CHECK_NAME(fn) \ + if (addr == (void*) &fn) return #fn; + + CHECK_NAME(main); + CHECK_NAME(greet); + return NULL; +} + +/* does the event match the tag, followed by a null, space, or slash? */ +#define MATCH(event, tag) \ + (!strncmp(event, tag, sizeof(tag)-1) && \ + (!event[sizeof(tag)-1] || strchr(" /", event[sizeof(tag)-1]))) + + +static const char event_cookie[] = "event_cookie"; /* demo placeholder */ +static void* handle_event(void* cookie, const char* event, void* arg) { +#define NS_DEMO "demo:" + if (cookie != event_cookie) + printf("*** bad event cookie %p != %p\n", cookie, event_cookie); + + if (xml) { + /* We could almost do a printf(event, arg), + but for the sake of a better demo, + we dress the result up as valid XML. + */ + const char* fmt = strchr(event, ' '); + int evlen = (fmt ? fmt - event : strlen(event)); + if (!fmt) { + if (event[0] != '/') { + printf("<"NS_DEMO"%.*s>", evlen, event); + } else { + printf("", evlen-1, event+1); + } + } else { + if (event[0] != '/') { + printf("<"NS_DEMO"%.*s", evlen, event); + printf(fmt, arg); + printf(">"); + } else { + printf("<"NS_DEMO"%.*s_done", evlen-1, event+1); + printf(fmt, arg); + printf("/>", evlen-1, event+1); + } + } + } + + if (MATCH(event, "insn")) { + const char* name = lookup(arg); + if (name) printf("%s:\n", name); + + /* basic action for : */ + printf(" %p\t", arg); + + } else if (MATCH(event, "/insn")) { + /* basic action for : + (none, plugin puts the newline for us + */ + + } else if (MATCH(event, "mach")) { + printf("Decoding for CPU '%s'\n", (char*) arg); + + } else if (MATCH(event, "addr")) { + /* basic action for : */ + const char* name = lookup(arg); + if (name) { + printf("&%s (%p)", name, arg); + /* return non-null to notify hsdis not to print the addr */ + return arg; + } + } + + /* null return is always safe; can mean "I ignored it" */ + return NULL; +} + +#define fprintf_callback \ + (decode_instructions_printf_callback_ftype)&fprintf + +void disassemble(void* from, void* to) { + const char* err = load_decode_instructions(); + if (err != NULL) { + printf("%s: %s\n", err, dlerror()); + exit(1); + } + printf("Decoding from %p to %p...\n", from, to); + decode_instructions_ftype decode_instructions + = (decode_instructions_ftype) decode_instructions_pv; + void* res; + if (raw && xml) { + res = (*decode_instructions)(from, to, NULL, stdout, NULL, stdout, options); + } else if (raw) { + res = (*decode_instructions)(from, to, NULL, NULL, NULL, stdout, options); + } else { + res = (*decode_instructions)(from, to, + handle_event, (void*) event_cookie, + fprintf_callback, stdout, + options); + } + if (res != to) + printf("*** Result was %p!\n", res); +} diff --git a/hotspot/src/share/tools/hsdis/hsdis.c b/hotspot/src/share/tools/hsdis/hsdis.c new file mode 100644 index 00000000000..75b7efe2638 --- /dev/null +++ b/hotspot/src/share/tools/hsdis/hsdis.c @@ -0,0 +1,499 @@ +/* + * Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + * + */ + +/* hsdis.c -- dump a range of addresses as native instructions + This implements the plugin protocol required by the + HotSpot PrintAssembly option. +*/ + +#include "hsdis.h" + +#include +#include +#include +#include + +#ifndef bool +#define bool int +#define true 1 +#define false 0 +#endif /*bool*/ + +/* short names for stuff in hsdis.h */ +typedef decode_instructions_event_callback_ftype event_callback_t; +typedef decode_instructions_printf_callback_ftype printf_callback_t; + +/* disassemble_info.application_data object */ +struct hsdis_app_data { + /* the arguments to decode_instructions */ + uintptr_t start; uintptr_t end; + event_callback_t event_callback; void* event_stream; + printf_callback_t printf_callback; void* printf_stream; + bool losing; + + /* the architecture being disassembled */ + const char* arch_name; + const bfd_arch_info_type* arch_info; + + /* the disassembler we are going to use: */ + disassembler_ftype dfn; + struct disassemble_info dinfo; /* the actual struct! */ + + char mach_option[64]; + char insn_options[256]; +}; + +#define DECL_APP_DATA(dinfo) \ + struct hsdis_app_data* app_data = (struct hsdis_app_data*) (dinfo)->application_data + +#define DECL_EVENT_CALLBACK(app_data) \ + event_callback_t event_callback = (app_data)->event_callback; \ + void* event_stream = (app_data)->event_stream + +#define DECL_PRINTF_CALLBACK(app_data) \ + printf_callback_t printf_callback = (app_data)->printf_callback; \ + void* printf_stream = (app_data)->printf_stream + + +static void print_help(struct hsdis_app_data* app_data, + const char* msg, const char* arg); +static void setup_app_data(struct hsdis_app_data* app_data, + const char* options); +static const char* format_insn_close(const char* close, + disassemble_info* dinfo, + char* buf, size_t bufsize); + +void* +#ifdef DLL_ENTRY + DLL_ENTRY +#endif +decode_instructions(void* start_pv, void* end_pv, + event_callback_t event_callback_arg, void* event_stream_arg, + printf_callback_t printf_callback_arg, void* printf_stream_arg, + const char* options) { + struct hsdis_app_data app_data; + memset(&app_data, 0, sizeof(app_data)); + app_data.start = (uintptr_t) start_pv; + app_data.end = (uintptr_t) end_pv; + app_data.event_callback = event_callback_arg; + app_data.event_stream = event_stream_arg; + app_data.printf_callback = printf_callback_arg; + app_data.printf_stream = printf_stream_arg; + + setup_app_data(&app_data, options); + char buf[128]; + + { + /* now reload everything from app_data: */ + DECL_EVENT_CALLBACK(&app_data); + DECL_PRINTF_CALLBACK(&app_data); + uintptr_t start = app_data.start; + uintptr_t end = app_data.end; + uintptr_t p = start; + + (*event_callback)(event_stream, "insns", (void*)start); + + (*event_callback)(event_stream, "mach name='%s'", + (void*) app_data.arch_info->printable_name); + if (app_data.dinfo.bytes_per_line != 0) { + (*event_callback)(event_stream, "format bytes-per-line='%p'/", + (void*)(intptr_t) app_data.dinfo.bytes_per_line); + } + + while (p < end && !app_data.losing) { + (*event_callback)(event_stream, "insn", (void*) p); + + /* reset certain state, so we can read it with confidence */ + app_data.dinfo.insn_info_valid = 0; + app_data.dinfo.branch_delay_insns = 0; + app_data.dinfo.data_size = 0; + app_data.dinfo.insn_type = 0; + + int size = (*app_data.dfn)((bfd_vma) p, &app_data.dinfo); + + if (size > 0) p += size; + else app_data.losing = true; + + const char* insn_close = format_insn_close("/insn", &app_data.dinfo, + buf, sizeof(buf)); + (*event_callback)(event_stream, insn_close, (void*) p); + + /* follow each complete insn by a nice newline */ + (*printf_callback)(printf_stream, "\n"); + } + + (*event_callback)(event_stream, "/insns", (void*) p); + return (void*) p; + } +} + +/* take the address of the function, for luck, and also test the typedef: */ +const decode_instructions_ftype decode_instructions_address = &decode_instructions; + +static const char* format_insn_close(const char* close, + disassemble_info* dinfo, + char* buf, size_t bufsize) { + if (!dinfo->insn_info_valid) + return close; + enum dis_insn_type itype = dinfo->insn_type; + int dsize = dinfo->data_size, delays = dinfo->branch_delay_insns; + if ((itype == dis_nonbranch && (dsize | delays) == 0) + || (strlen(close) + 3*20 > bufsize)) + return close; + + const char* type = "unknown"; + switch (itype) { + case dis_nonbranch: type = NULL; break; + case dis_branch: type = "branch"; break; + case dis_condbranch: type = "condbranch"; break; + case dis_jsr: type = "jsr"; break; + case dis_condjsr: type = "condjsr"; break; + case dis_dref: type = "dref"; break; + case dis_dref2: type = "dref2"; break; + } + + strcpy(buf, close); + char* p = buf; + if (type) sprintf(p += strlen(p), " type='%s'", type); + if (dsize) sprintf(p += strlen(p), " dsize='%d'", dsize); + if (delays) sprintf(p += strlen(p), " delay='%d'", delays); + return buf; +} + +/* handler functions */ + +static int +hsdis_read_memory_func(bfd_vma memaddr, + bfd_byte* myaddr, + unsigned int length, + struct disassemble_info* dinfo) { + uintptr_t memaddr_p = (uintptr_t) memaddr; + DECL_APP_DATA(dinfo); + if (memaddr_p + length > app_data->end) { + /* read is out of bounds */ + return EIO; + } else { + memcpy(myaddr, (bfd_byte*) memaddr_p, length); + return 0; + } +} + +static void +hsdis_print_address_func(bfd_vma vma, struct disassemble_info* dinfo) { + /* the actual value to print: */ + void* addr_value = (void*) (uintptr_t) vma; + DECL_APP_DATA(dinfo); + DECL_EVENT_CALLBACK(app_data); + + /* issue the event: */ + void* result = + (*event_callback)(event_stream, "addr/", addr_value); + if (result == NULL) { + /* event declined */ + generic_print_address(vma, dinfo); + } +} + + +/* configuration */ + +static void set_optional_callbacks(struct hsdis_app_data* app_data); +static void parse_caller_options(struct hsdis_app_data* app_data, + const char* caller_options); +static const char* native_arch_name(); +static enum bfd_endian native_endian(); +static const bfd_arch_info_type* find_arch_info(const char* arch_nane); +static bfd* get_native_bfd(const bfd_arch_info_type* arch_info, + /* to avoid malloc: */ + bfd* empty_bfd, bfd_target* empty_xvec); +static void init_disassemble_info_from_bfd(struct disassemble_info* dinfo, + void *stream, + fprintf_ftype fprintf_func, + bfd* bfd, + char* disassembler_options); +static void parse_fake_insn(disassembler_ftype dfn, + struct disassemble_info* dinfo); + +static void setup_app_data(struct hsdis_app_data* app_data, + const char* caller_options) { + /* Make reasonable defaults for null callbacks. + A non-null stream for a null callback is assumed to be a FILE* for output. + Events are rendered as XML. + */ + set_optional_callbacks(app_data); + + /* Look into caller_options for anything interesting. */ + if (caller_options != NULL) + parse_caller_options(app_data, caller_options); + + /* Discover which architecture we are going to disassemble. */ + app_data->arch_name = &app_data->mach_option[0]; + if (app_data->arch_name[0] == '\0') + app_data->arch_name = native_arch_name(); + app_data->arch_info = find_arch_info(app_data->arch_name); + + /* Make a fake bfd to hold the arch. and byteorder info. */ + struct { + bfd_target empty_xvec; + bfd empty_bfd; + } buf; + bfd* native_bfd = get_native_bfd(app_data->arch_info, + /* to avoid malloc: */ + &buf.empty_bfd, &buf.empty_xvec); + init_disassemble_info_from_bfd(&app_data->dinfo, + app_data->printf_stream, + app_data->printf_callback, + native_bfd, + app_data->insn_options); + + /* Finish linking together the various callback blocks. */ + app_data->dinfo.application_data = (void*) app_data; + app_data->dfn = disassembler(native_bfd); + app_data->dinfo.print_address_func = hsdis_print_address_func; + app_data->dinfo.read_memory_func = hsdis_read_memory_func; + + if (app_data->dfn == NULL) { + const char* bad = app_data->arch_name; + static bool complained; + if (bad == &app_data->mach_option[0]) + print_help(app_data, "bad mach=%s", bad); + else if (!complained) + print_help(app_data, "bad native mach=%s; please port hsdis to this platform", bad); + complained = true; + /* must bail out */ + app_data->losing = true; + return; + } + + parse_fake_insn(app_data->dfn, &app_data->dinfo); +} + + +/* ignore all events, return a null */ +static void* null_event_callback(void* ignore_stream, const char* ignore_event, void* arg) { + return NULL; +} + +/* print all events as XML markup */ +static void* xml_event_callback(void* stream, const char* event, void* arg) { + FILE* fp = (FILE*) stream; +#define NS_PFX "dis:" + if (event[0] != '/') { + /* issue the tag, with or without a formatted argument */ + fprintf(fp, "<"NS_PFX); + fprintf(fp, event, arg); + fprintf(fp, ">"); + } else { + ++event; /* skip slash */ + const char* argp = strchr(event, ' '); + if (argp == NULL) { + /* no arguments; just issue the closing tag */ + fprintf(fp, "", event); + } else { + /* split out the closing attributes as */ + int event_prefix = (argp - event); + fprintf(fp, "<"NS_PFX"%.*s_done", event_prefix, event); + fprintf(fp, argp, arg); + fprintf(fp, "/>", event_prefix, event); + } + } + return NULL; +} + +static void set_optional_callbacks(struct hsdis_app_data* app_data) { + if (app_data->printf_callback == NULL) { + int (*fprintf_callback)(FILE*, const char*, ...) = &fprintf; + FILE* fprintf_stream = stdout; + app_data->printf_callback = (printf_callback_t) fprintf_callback; + if (app_data->printf_stream == NULL) + app_data->printf_stream = (void*) fprintf_stream; + } + if (app_data->event_callback == NULL) { + if (app_data->event_stream == NULL) + app_data->event_callback = &null_event_callback; + else + app_data->event_callback = &xml_event_callback; + } + +} + +static void parse_caller_options(struct hsdis_app_data* app_data, const char* caller_options) { + char* iop_base = app_data->insn_options; + char* iop_limit = iop_base + sizeof(app_data->insn_options) - 1; + char* iop = iop_base; + const char* p; + for (p = caller_options; p != NULL; ) { + const char* q = strchr(p, ','); + size_t plen = (q == NULL) ? strlen(p) : ((q++) - p); + if (plen == 4 && strncmp(p, "help", plen) == 0) { + print_help(app_data, NULL, NULL); + } else if (plen >= 5 && strncmp(p, "mach=", 5) == 0) { + char* mach_option = app_data->mach_option; + size_t mach_size = sizeof(app_data->mach_option); + mach_size -= 1; /*leave room for the null*/ + if (plen > mach_size) plen = mach_size; + strncpy(mach_option, p, plen); + mach_option[plen] = '\0'; + } else if (plen > 6 && strncmp(p, "hsdis-", 6)) { + // do not pass these to the next level + } else { + /* just copy it; {i386,sparc}-dis.c might like to see it */ + if (iop > iop_base && iop < iop_limit) (*iop++) = ','; + if (iop + plen > iop_limit) + plen = iop_limit - iop; + strncpy(iop, p, plen); + iop += plen; + } + p = q; + } +} + +static void print_help(struct hsdis_app_data* app_data, + const char* msg, const char* arg) { + DECL_PRINTF_CALLBACK(app_data); + if (msg != NULL) { + (*printf_callback)(printf_stream, "hsdis: "); + (*printf_callback)(printf_stream, msg, arg); + (*printf_callback)(printf_stream, "\n"); + } + (*printf_callback)(printf_stream, "hsdis output options:\n"); + if (printf_callback == (printf_callback_t) &fprintf) + disassembler_usage((FILE*) printf_stream); + else + disassembler_usage(stderr); /* better than nothing */ + (*printf_callback)(printf_stream, " mach= select disassembly mode\n"); +#if defined(LIBARCH_i386) || defined(LIBARCH_amd64) + (*printf_callback)(printf_stream, " mach=i386 select 32-bit mode\n"); + (*printf_callback)(printf_stream, " mach=x86-64 select 64-bit mode\n"); + (*printf_callback)(printf_stream, " suffix always print instruction suffix\n"); +#endif + (*printf_callback)(printf_stream, " help print this message\n"); +} + + +/* low-level bfd and arch stuff that binutils doesn't do for us */ + +static const bfd_arch_info_type* find_arch_info(const char* arch_name) { + const bfd_arch_info_type* arch_info = bfd_scan_arch(arch_name); + if (arch_info == NULL) { + extern const bfd_arch_info_type bfd_default_arch_struct; + arch_info = &bfd_default_arch_struct; + } + return arch_info; +} + +static const char* native_arch_name() { + const char* res = HOTSPOT_LIB_ARCH; +#ifdef LIBARCH_amd64 + res = "i386:x86-64"; +#endif +#ifdef LIBARCH_sparc + res = "sparc:v8plusb"; +#endif +#ifdef LIBARCH_sparc + res = "sparc:v8plusb"; +#endif +#ifdef LIBARCH_sparcv9 + res = "sparc:v9b"; +#endif + if (res == NULL) + res = "HOTSPOT_LIB_ARCH is not set in Makefile!"; + return res; +} + +static enum bfd_endian native_endian() { + int32_t endian_test = 'x'; + if (*(const char*) &endian_test == 'x') + return BFD_ENDIAN_LITTLE; + else + return BFD_ENDIAN_BIG; +} + +static bfd* get_native_bfd(const bfd_arch_info_type* arch_info, + bfd* empty_bfd, bfd_target* empty_xvec) { + memset(empty_bfd, 0, sizeof(*empty_bfd)); + memset(empty_xvec, 0, sizeof(*empty_xvec)); + empty_xvec->flavour = bfd_target_unknown_flavour; + empty_xvec->byteorder = native_endian(); + empty_bfd->xvec = empty_xvec; + empty_bfd->arch_info = arch_info; + return empty_bfd; +} + +static int read_zero_data_only(bfd_vma ignore_p, + bfd_byte* myaddr, unsigned int length, + struct disassemble_info *ignore_info) { + memset(myaddr, 0, length); + return 0; +} +static int print_to_dev_null(void* ignore_stream, const char* ignore_format, ...) { + return 0; +} + +/* Prime the pump by running the selected disassembler on a null input. + This forces the machine-specific disassembler to divulge invariant + information like bytes_per_line. + */ +static void parse_fake_insn(disassembler_ftype dfn, + struct disassemble_info* dinfo) { + typedef int (*read_memory_ftype) + (bfd_vma memaddr, bfd_byte *myaddr, unsigned int length, + struct disassemble_info *info); + read_memory_ftype read_memory_func = dinfo->read_memory_func; + fprintf_ftype fprintf_func = dinfo->fprintf_func; + + dinfo->read_memory_func = &read_zero_data_only; + dinfo->fprintf_func = &print_to_dev_null; + (*dfn)(0, dinfo); + + // put it back: + dinfo->read_memory_func = read_memory_func; + dinfo->fprintf_func = fprintf_func; +} + +static void init_disassemble_info_from_bfd(struct disassemble_info* dinfo, + void *stream, + fprintf_ftype fprintf_func, + bfd* abfd, + char* disassembler_options) { + init_disassemble_info(dinfo, stream, fprintf_func); + + dinfo->flavour = bfd_get_flavour(abfd); + dinfo->arch = bfd_get_arch(abfd); + dinfo->mach = bfd_get_mach(abfd); + dinfo->disassembler_options = disassembler_options; + dinfo->octets_per_byte = bfd_octets_per_byte (abfd); + dinfo->skip_zeroes = sizeof(void*) * 2; + dinfo->skip_zeroes_at_end = sizeof(void*)-1; + dinfo->disassembler_needs_relocs = FALSE; + + if (bfd_big_endian(abfd)) + dinfo->display_endian = dinfo->endian = BFD_ENDIAN_BIG; + else if (bfd_little_endian(abfd)) + dinfo->display_endian = dinfo->endian = BFD_ENDIAN_LITTLE; + else + dinfo->endian = native_endian(); + + disassemble_init_for_target(dinfo); +} diff --git a/hotspot/src/share/tools/hsdis/hsdis.h b/hotspot/src/share/tools/hsdis/hsdis.h new file mode 100644 index 00000000000..df489ff0513 --- /dev/null +++ b/hotspot/src/share/tools/hsdis/hsdis.h @@ -0,0 +1,67 @@ +/* + * Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + * + */ + +/* decode_instructions -- dump a range of addresses as native instructions + This implements the protocol required by the HotSpot PrintAssembly option. + + The starting and ending addresses are within the current process's address space. + + The option string, if not empty, is interpreted by the disassembler implementation. + + The printf callback is 'fprintf' or any other workalike. + It is called as (*printf_callback)(printf_stream, "some format...", some, format, args). + + The event callback receives an event tag (a string) and an argument (a void*). + It is called as (*event_callback)(event_stream, "tag", arg). + + Events: + begin an instruction, at a given location + end an instruction, at a given location + emit the symbolic value of an address + + A tag format is one of three basic forms: "tag", "/tag", "tag/", + where tag is a simple identifier, signifying (as in XML) a element start, + element end, and standalone element. (To render as XML, add angle brackets.) +*/ +extern +#ifdef DLL_EXPORT + DLL_EXPORT +#endif +void* decode_instructions(void* start, void* end, + void* (*event_callback)(void*, const char*, void*), + void* event_stream, + int (*printf_callback)(void*, const char*, ...), + void* printf_stream, + const char* options); + +/* convenience typedefs */ + +typedef void* (*decode_instructions_event_callback_ftype) (void*, const char*, void*); +typedef int (*decode_instructions_printf_callback_ftype) (void*, const char*, ...); +typedef void* (*decode_instructions_ftype) (void* start, void* end, + decode_instructions_event_callback_ftype event_callback, + void* event_stream, + decode_instructions_printf_callback_ftype printf_callback, + void* printf_stream, + const char* options); diff --git a/hotspot/src/share/vm/asm/codeBuffer.cpp b/hotspot/src/share/vm/asm/codeBuffer.cpp index a8b19abb3a7..0fc53ed45f7 100644 --- a/hotspot/src/share/vm/asm/codeBuffer.cpp +++ b/hotspot/src/share/vm/asm/codeBuffer.cpp @@ -947,6 +947,7 @@ void CodeComments::print_block_comment(outputStream* stream, intptr_t offset) { if (_comments != NULL) { CodeComment* c = _comments->find(offset); while (c && c->offset() == offset) { + stream->bol(); stream->print(" ;; "); stream->print_cr(c->comment()); c = c->next(); diff --git a/hotspot/src/share/vm/code/nmethod.cpp b/hotspot/src/share/vm/code/nmethod.cpp index 518c0ce717d..f09e8a244c0 100644 --- a/hotspot/src/share/vm/code/nmethod.cpp +++ b/hotspot/src/share/vm/code/nmethod.cpp @@ -707,7 +707,9 @@ nmethod::nmethod( " entry points must be same for static methods and vice versa"); } - bool printnmethods = PrintNMethods || CompilerOracle::has_option_string(_method, "PrintNMethods"); + bool printnmethods = PrintNMethods + || CompilerOracle::should_print(_method) + || CompilerOracle::has_option_string(_method, "PrintNMethods"); if (printnmethods || PrintDebugInfo || PrintRelocations || PrintDependencies || PrintExceptionHandlers) { print_nmethod(printnmethods); } @@ -798,7 +800,6 @@ void nmethod::print_on(outputStream* st, const char* title) const { } -#ifndef PRODUCT void nmethod::print_nmethod(bool printmethod) { ttyLocker ttyl; // keep the following output all in one block if (xtty != NULL) { @@ -831,7 +832,6 @@ void nmethod::print_nmethod(bool printmethod) { xtty->tail("print_nmethod"); } } -#endif void nmethod::set_version(int v) { @@ -1870,6 +1870,7 @@ void nmethod::check_store() { } } +#endif // PRODUCT // Printing operations @@ -1948,6 +1949,14 @@ void nmethod::print() const { oops_size()); } +void nmethod::print_code() { + HandleMark hm; + ResourceMark m; + Disassembler::decode(this); +} + + +#ifndef PRODUCT void nmethod::print_scopes() { // Find the first pc desc for all scopes in the code and print it. @@ -1979,13 +1988,6 @@ void nmethod::print_dependencies() { } -void nmethod::print_code() { - HandleMark hm; - ResourceMark m; - Disassembler().decode(this); -} - - void nmethod::print_relocations() { ResourceMark m; // in case methods get printed via the debugger tty->print_cr("relocations:"); @@ -2021,6 +2023,7 @@ void nmethod::print_pcs() { } } +#endif // PRODUCT const char* nmethod::reloc_string_for(u_char* begin, u_char* end) { RelocIterator iter(this, begin, end); @@ -2055,7 +2058,6 @@ const char* nmethod::reloc_string_for(u_char* begin, u_char* end) { return have_one ? "other" : NULL; } - // Return a the last scope in (begin..end] ScopeDesc* nmethod::scope_desc_in(address begin, address end) { PcDesc* p = pc_desc_near(begin+1); @@ -2078,29 +2080,26 @@ void nmethod::print_code_comment_on(outputStream* st, int column, u_char* begin, address pc = base + om->offset(); if (pc > begin) { if (pc <= end) { - st->fill_to(column); - if (st == tty) { - st->print("; OopMap "); - om->print(); - tty->cr(); - } else { - st->print_cr("; OopMap #%d offset:%d", i, om->offset()); - } + st->move_to(column); + st->print("; "); + om->print_on(st); } break; } } } + + // Print any debug info present at this pc. ScopeDesc* sd = scope_desc_in(begin, end); if (sd != NULL) { - st->fill_to(column); + st->move_to(column); if (sd->bci() == SynchronizationEntryBCI) { st->print(";*synchronization entry"); } else { if (sd->method().is_null()) { - tty->print("method is NULL"); + st->print("method is NULL"); } else if (sd->method()->is_native()) { - tty->print("method is native"); + st->print("method is native"); } else { address bcp = sd->method()->bcp_from(sd->bci()); Bytecodes::Code bc = Bytecodes::java_code_at(bcp); @@ -2137,13 +2136,13 @@ void nmethod::print_code_comment_on(outputStream* st, int column, u_char* begin, } } } - st->cr(); + // Print all scopes for (;sd != NULL; sd = sd->sender()) { - st->fill_to(column); + st->move_to(column); st->print("; -"); if (sd->method().is_null()) { - tty->print("method is NULL"); + st->print("method is NULL"); } else { sd->method()->print_short_name(st); } @@ -2161,17 +2160,19 @@ void nmethod::print_code_comment_on(outputStream* st, int column, u_char* begin, const char* str = reloc_string_for(begin, end); if (str != NULL) { if (sd != NULL) st->cr(); - st->fill_to(column); + st->move_to(column); st->print("; {%s}", str); } int cont_offset = ImplicitExceptionTable(this).at(begin - instructions_begin()); if (cont_offset != 0) { - st->fill_to(column); + st->move_to(column); st->print("; implicit exception: dispatches to " INTPTR_FORMAT, instructions_begin() + cont_offset); } } +#ifndef PRODUCT + void nmethod::print_value_on(outputStream* st) const { print_on(st, "nmethod"); } diff --git a/hotspot/src/share/vm/code/nmethod.hpp b/hotspot/src/share/vm/code/nmethod.hpp index 0b1c61977e3..f03ec5434d8 100644 --- a/hotspot/src/share/vm/code/nmethod.hpp +++ b/hotspot/src/share/vm/code/nmethod.hpp @@ -485,8 +485,8 @@ class nmethod : public CodeBlob { void verify_interrupt_point(address interrupt_point); // printing support - void print() const PRODUCT_RETURN; - void print_code() PRODUCT_RETURN; + void print() const; + void print_code(); void print_relocations() PRODUCT_RETURN; void print_pcs() PRODUCT_RETURN; void print_scopes() PRODUCT_RETURN; @@ -495,7 +495,7 @@ class nmethod : public CodeBlob { void print_calls(outputStream* st) PRODUCT_RETURN; void print_handler_table() PRODUCT_RETURN; void print_nul_chk_table() PRODUCT_RETURN; - void print_nmethod(bool print_code) PRODUCT_RETURN; + void print_nmethod(bool print_code); void print_on(outputStream* st, const char* title) const; @@ -505,7 +505,7 @@ class nmethod : public CodeBlob { void log_state_change(int state) const; // Prints a comment for one native instruction (reloc info, pc desc) - void print_code_comment_on(outputStream* st, int column, address begin, address end) PRODUCT_RETURN; + void print_code_comment_on(outputStream* st, int column, address begin, address end); static void print_statistics() PRODUCT_RETURN; // Compiler task identification. Note that all OSR methods diff --git a/hotspot/src/share/vm/code/vmreg.cpp b/hotspot/src/share/vm/code/vmreg.cpp index 22be4b2f390..3d2aa69274d 100644 --- a/hotspot/src/share/vm/code/vmreg.cpp +++ b/hotspot/src/share/vm/code/vmreg.cpp @@ -36,7 +36,6 @@ const int VMRegImpl::register_count = ConcreteRegisterImpl::number_of_registers; // Register names const char *VMRegImpl::regName[ConcreteRegisterImpl::number_of_registers]; -#ifndef PRODUCT void VMRegImpl::print_on(outputStream* st) const { if( is_reg() ) { assert( VMRegImpl::regName[value()], "" ); @@ -48,4 +47,3 @@ void VMRegImpl::print_on(outputStream* st) const { st->print("BAD!"); } } -#endif // PRODUCT diff --git a/hotspot/src/share/vm/code/vmreg.hpp b/hotspot/src/share/vm/code/vmreg.hpp index ab77b265fe3..399cba3497b 100644 --- a/hotspot/src/share/vm/code/vmreg.hpp +++ b/hotspot/src/share/vm/code/vmreg.hpp @@ -96,7 +96,7 @@ public: intptr_t value() const {return (intptr_t) this; } - void print_on(outputStream* st) const PRODUCT_RETURN; + void print_on(outputStream* st) const; void print() const { print_on(tty); } // bias a stack slot. @@ -156,22 +156,22 @@ public: _first = ptr; } // Return true if single register, even if the pair is really just adjacent stack slots - bool is_single_reg() { + bool is_single_reg() const { return (_first->is_valid()) && (_first->value() + 1 == _second->value()); } // Return true if single stack based "register" where the slot alignment matches input alignment - bool is_adjacent_on_stack(int alignment) { + bool is_adjacent_on_stack(int alignment) const { return (_first->is_stack() && (_first->value() + 1 == _second->value()) && ((_first->value() & (alignment-1)) == 0)); } // Return true if single stack based "register" where the slot alignment matches input alignment - bool is_adjacent_aligned_on_stack(int alignment) { + bool is_adjacent_aligned_on_stack(int alignment) const { return (_first->is_stack() && (_first->value() + 1 == _second->value()) && ((_first->value() & (alignment-1)) == 0)); } // Return true if single register but adjacent stack slots do not count - bool is_single_phys_reg() { + bool is_single_phys_reg() const { return (_first->is_reg() && (_first->value() + 1 == _second->value())); } diff --git a/hotspot/src/share/vm/compiler/disassembler.cpp b/hotspot/src/share/vm/compiler/disassembler.cpp new file mode 100644 index 00000000000..3e800e9b9e7 --- /dev/null +++ b/hotspot/src/share/vm/compiler/disassembler.cpp @@ -0,0 +1,443 @@ +/* + * Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + * + */ + +# include "incls/_precompiled.incl" +# include "incls/_disassembler.cpp.incl" + +void* Disassembler::_library = NULL; +bool Disassembler::_tried_to_load_library = false; + +// This routine is in the shared library: +Disassembler::decode_func Disassembler::_decode_instructions = NULL; + +static const char hsdis_library_name[] = "hsdis-"HOTSPOT_LIB_ARCH; +static const char decode_instructions_name[] = "decode_instructions"; + +#define COMMENT_COLUMN 40 LP64_ONLY(+8) /*could be an option*/ +#define BYTES_COMMENT ";..." /* funky byte display comment */ + +bool Disassembler::load_library() { + if (_decode_instructions != NULL) { + // Already succeeded. + return true; + } + if (_tried_to_load_library) { + // Do not try twice. + // To force retry in debugger: assign _tried_to_load_library=0 + return false; + } + // Try to load it. + char ebuf[1024]; + char buf[JVM_MAXPATHLEN]; + os::jvm_path(buf, sizeof(buf)); + int jvm_offset = -1; + { + // Match "jvm[^/]*" in jvm_path. + const char* base = buf; + const char* p = strrchr(buf, '/'); + p = strstr(p ? p : base, "jvm"); + if (p != NULL) jvm_offset = p - base; + } + if (jvm_offset >= 0) { + // Find the disassembler next to libjvm.so. + strcpy(&buf[jvm_offset], hsdis_library_name); + strcat(&buf[jvm_offset], os::dll_file_extension()); + _library = hpi::dll_load(buf, ebuf, sizeof ebuf); + } + if (_library == NULL) { + // Try a free-floating lookup. + strcpy(&buf[0], hsdis_library_name); + strcat(&buf[0], os::dll_file_extension()); + _library = hpi::dll_load(buf, ebuf, sizeof ebuf); + } + if (_library != NULL) { + _decode_instructions = CAST_TO_FN_PTR(Disassembler::decode_func, + hpi::dll_lookup(_library, decode_instructions_name)); + } + _tried_to_load_library = true; + if (_decode_instructions == NULL) { + tty->print_cr("Could not load %s; %s; %s", buf, + ((_library != NULL) + ? "entry point is missing" + : (WizardMode || PrintMiscellaneous) + ? (const char*)ebuf + : "library not loadable"), + "PrintAssembly is disabled"); + return false; + } + + // Success. + tty->print_cr("Loaded disassembler from %s", buf); + return true; +} + + +class decode_env { + private: + nmethod* _nm; + CodeBlob* _code; + outputStream* _output; + address _start, _end; + + char _option_buf[512]; + char _print_raw; + bool _print_pc; + bool _print_bytes; + address _cur_insn; + int _total_ticks; + int _bytes_per_line; // arch-specific formatting option + + static bool match(const char* event, const char* tag) { + size_t taglen = strlen(tag); + if (strncmp(event, tag, taglen) != 0) + return false; + char delim = event[taglen]; + return delim == '\0' || delim == ' ' || delim == '/' || delim == '='; + } + + void collect_options(const char* p) { + if (p == NULL || p[0] == '\0') return; + size_t opt_so_far = strlen(_option_buf); + if (opt_so_far + 1 + strlen(p) + 1 > sizeof(_option_buf)) return; + char* fillp = &_option_buf[opt_so_far]; + if (opt_so_far > 0) *fillp++ = ','; + strcat(fillp, p); + // replace white space by commas: + char* q = fillp; + while ((q = strpbrk(q, " \t\n")) != NULL) + *q++ = ','; + // Note that multiple PrintAssemblyOptions flags accumulate with \n, + // which we want to be changed to a comma... + } + + void print_insn_labels(); + void print_insn_bytes(address pc0, address pc); + void print_address(address value); + + public: + decode_env(CodeBlob* code, outputStream* output); + + address decode_instructions(address start, address end); + + void start_insn(address pc) { + _cur_insn = pc; + output()->bol(); + print_insn_labels(); + } + + void end_insn(address pc) { + address pc0 = cur_insn(); + outputStream* st = output(); + if (_print_bytes && pc > pc0) + print_insn_bytes(pc0, pc); + if (_nm != NULL) + _nm->print_code_comment_on(st, COMMENT_COLUMN, pc0, pc); + + // Output pc bucket ticks if we have any + if (total_ticks() != 0) { + address bucket_pc = FlatProfiler::bucket_start_for(pc); + if (bucket_pc != NULL && bucket_pc > pc0 && bucket_pc <= pc) { + int bucket_count = FlatProfiler::bucket_count_for(pc0); + if (bucket_count != 0) { + st->bol(); + st->print_cr("%3.1f%% [%d]", bucket_count*100.0/total_ticks(), bucket_count); + } + } + } + } + + address handle_event(const char* event, address arg); + + outputStream* output() { return _output; } + address cur_insn() { return _cur_insn; } + int total_ticks() { return _total_ticks; } + void set_total_ticks(int n) { _total_ticks = n; } + const char* options() { return _option_buf; } +}; + +decode_env::decode_env(CodeBlob* code, outputStream* output) { + memset(this, 0, sizeof(*this)); + _output = output ? output : tty; + _code = code; + if (code != NULL && code->is_nmethod()) + _nm = (nmethod*) code; + + // by default, output pc but not bytes: + _print_pc = true; + _print_bytes = false; + _bytes_per_line = Disassembler::pd_instruction_alignment(); + + // parse the global option string: + collect_options(Disassembler::pd_cpu_opts()); + collect_options(PrintAssemblyOptions); + + if (strstr(options(), "hsdis-")) { + if (strstr(options(), "hsdis-print-raw")) + _print_raw = (strstr(options(), "xml") ? 2 : 1); + if (strstr(options(), "hsdis-print-pc")) + _print_pc = !_print_pc; + if (strstr(options(), "hsdis-print-bytes")) + _print_bytes = !_print_bytes; + } + if (strstr(options(), "help")) { + tty->print_cr("PrintAssemblyOptions help:"); + tty->print_cr(" hsdis-print-raw test plugin by requesting raw output"); + tty->print_cr(" hsdis-print-raw-xml test plugin by requesting raw xml"); + tty->print_cr(" hsdis-print-pc turn off PC printing (on by default)"); + tty->print_cr(" hsdis-print-bytes turn on instruction byte output"); + tty->print_cr("combined options: %s", options()); + } +} + +address decode_env::handle_event(const char* event, address arg) { + if (match(event, "insn")) { + start_insn(arg); + } else if (match(event, "/insn")) { + end_insn(arg); + } else if (match(event, "addr")) { + if (arg != NULL) { + print_address(arg); + return arg; + } + } else if (match(event, "mach")) { + output()->print_cr("[Disassembling for mach='%s']", arg); + } else if (match(event, "format bytes-per-line")) { + _bytes_per_line = (int) (intptr_t) arg; + } else { + // ignore unrecognized markup + } + return NULL; +} + +// called by the disassembler to print out jump targets and data addresses +void decode_env::print_address(address adr) { + outputStream* st = _output; + + if (adr == NULL) { + st->print("NULL"); + return; + } + + int small_num = (int)(intptr_t)adr; + if ((intptr_t)adr == (intptr_t)small_num + && -1 <= small_num && small_num <= 9) { + st->print("%d", small_num); + return; + } + + if (Universe::is_fully_initialized()) { + if (StubRoutines::contains(adr)) { + StubCodeDesc* desc = StubCodeDesc::desc_for(adr); + if (desc == NULL) + desc = StubCodeDesc::desc_for(adr + frame::pc_return_offset); + if (desc != NULL) { + st->print("Stub::%s", desc->name()); + if (desc->begin() != adr) + st->print("%+d 0x%p",adr - desc->begin(), adr); + else if (WizardMode) st->print(" " INTPTR_FORMAT, adr); + return; + } + st->print("Stub:: " INTPTR_FORMAT, adr); + return; + } + + BarrierSet* bs = Universe::heap()->barrier_set(); + if (bs->kind() == BarrierSet::CardTableModRef && + adr == (address)((CardTableModRefBS*)(bs))->byte_map_base) { + st->print("word_map_base"); + if (WizardMode) st->print(" " INTPTR_FORMAT, (intptr_t)adr); + return; + } + + oop obj; + if (_nm != NULL + && (obj = _nm->embeddedOop_at(cur_insn())) != NULL + && (address) obj == adr) { + obj->print_value_on(st); + return; + } + } + + // Fall through to a simple numeral. + st->print(INTPTR_FORMAT, (intptr_t)adr); +} + +void decode_env::print_insn_labels() { + address p = cur_insn(); + outputStream* st = output(); + nmethod* nm = _nm; + if (nm != NULL) { + if (p == nm->entry_point()) st->print_cr("[Entry Point]"); + if (p == nm->verified_entry_point()) st->print_cr("[Verified Entry Point]"); + if (p == nm->exception_begin()) st->print_cr("[Exception Handler]"); + if (p == nm->stub_begin()) st->print_cr("[Stub Code]"); + if (p == nm->consts_begin()) st->print_cr("[Constants]"); + } + CodeBlob* cb = _code; + if (cb != NULL) { + cb->print_block_comment(st, (intptr_t)(p - cb->instructions_begin())); + } + if (_print_pc) { + st->print(" " INTPTR_FORMAT ": ", (intptr_t) p); + } +} + +void decode_env::print_insn_bytes(address pc, address pc_limit) { + outputStream* st = output(); + size_t incr = 1; + size_t perline = _bytes_per_line; + if ((size_t) Disassembler::pd_instruction_alignment() >= sizeof(int) + && !((uintptr_t)pc % sizeof(int)) + && !((uintptr_t)pc_limit % sizeof(int))) { + incr = sizeof(int); + if (perline % incr) perline += incr - (perline % incr); + } + while (pc < pc_limit) { + // tab to the desired column: + st->move_to(COMMENT_COLUMN); + address pc0 = pc; + address pc1 = pc + perline; + if (pc1 > pc_limit) pc1 = pc_limit; + for (; pc < pc1; pc += incr) { + if (pc == pc0) + st->print(BYTES_COMMENT); + else if ((uint)(pc - pc0) % sizeof(int) == 0) + st->print(" "); // put out a space on word boundaries + if (incr == sizeof(int)) + st->print("%08lx", *(int*)pc); + else st->print("%02x", (*pc)&0xFF); + } + st->cr(); + } +} + + +static void* event_to_env(void* env_pv, const char* event, void* arg) { + decode_env* env = (decode_env*) env_pv; + return env->handle_event(event, (address) arg); +} + +static int printf_to_env(void* env_pv, const char* format, ...) { + decode_env* env = (decode_env*) env_pv; + outputStream* st = env->output(); + size_t flen = strlen(format); + const char* raw = NULL; + if (flen == 0) return 0; + if (flen == 1 && format[0] == '\n') { st->bol(); return 1; } + if (flen < 2 || + strchr(format, '%') == NULL) { + raw = format; + } else if (format[0] == '%' && format[1] == '%' && + strchr(format+2, '%') == NULL) { + // happens a lot on machines with names like %foo + flen--; + raw = format+1; + } + if (raw != NULL) { + st->print_raw(raw, (int) flen); + return (int) flen; + } + va_list ap; + va_start(ap, format); + julong cnt0 = st->count(); + st->vprint(format, ap); + julong cnt1 = st->count(); + va_end(ap); + return (int)(cnt1 - cnt0); +} + +address decode_env::decode_instructions(address start, address end) { + _start = start; _end = end; + + assert((((intptr_t)start | (intptr_t)end) % Disassembler::pd_instruction_alignment() == 0), "misaligned insn addr"); + + const int show_bytes = false; // for disassembler debugging + + //_version = Disassembler::pd_cpu_version(); + + if (!Disassembler::can_decode()) { + return NULL; + } + + // decode a series of instructions and return the end of the last instruction + + if (_print_raw) { + // Print whatever the library wants to print, w/o fancy callbacks. + // This is mainly for debugging the library itself. + FILE* out = stdout; + FILE* xmlout = (_print_raw > 1 ? out : NULL); + return (address) + (*Disassembler::_decode_instructions)(start, end, + NULL, (void*) xmlout, + NULL, (void*) out, + options()); + } + + return (address) + (*Disassembler::_decode_instructions)(start, end, + &event_to_env, (void*) this, + &printf_to_env, (void*) this, + options()); +} + + +void Disassembler::decode(CodeBlob* cb, outputStream* st) { + if (!load_library()) return; + decode_env env(cb, st); + env.output()->print_cr("Decoding CodeBlob " INTPTR_FORMAT, cb); + env.decode_instructions(cb->instructions_begin(), cb->instructions_end()); +} + + +void Disassembler::decode(address start, address end, outputStream* st) { + if (!load_library()) return; + decode_env env(CodeCache::find_blob_unsafe(start), st); + env.decode_instructions(start, end); +} + +void Disassembler::decode(nmethod* nm, outputStream* st) { + if (!load_library()) return; + decode_env env(nm, st); + env.output()->print_cr("Decoding compiled method " INTPTR_FORMAT ":", nm); + env.output()->print_cr("Code:"); + + unsigned char* p = nm->instructions_begin(); + unsigned char* end = nm->instructions_end(); + + // If there has been profiling, print the buckets. + if (FlatProfiler::bucket_start_for(p) != NULL) { + unsigned char* p1 = p; + int total_bucket_count = 0; + while (p1 < end) { + unsigned char* p0 = p1; + p1 += pd_instruction_alignment(); + address bucket_pc = FlatProfiler::bucket_start_for(p1); + if (bucket_pc != NULL && bucket_pc > p0 && bucket_pc <= p1) + total_bucket_count += FlatProfiler::bucket_count_for(p0); + } + env.set_total_ticks(total_bucket_count); + } + + env.decode_instructions(p, end); +} diff --git a/hotspot/src/share/vm/compiler/disassembler.hpp b/hotspot/src/share/vm/compiler/disassembler.hpp new file mode 100644 index 00000000000..670355f070d --- /dev/null +++ b/hotspot/src/share/vm/compiler/disassembler.hpp @@ -0,0 +1,59 @@ +/* + * Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + * + */ + +class decode_env; + +// The disassembler prints out assembly code annotated +// with Java specific information. + +class Disassembler { + friend class decode_env; + private: + // this is the type of the dll entry point: + typedef void* (*decode_func)(void* start, void* end, + void* (*event_callback)(void*, const char*, void*), + void* event_stream, + int (*printf_callback)(void*, const char*, ...), + void* printf_stream, + const char* options); + // points to the library. + static void* _library; + // bailout + static bool _tried_to_load_library; + // points to the decode function. + static decode_func _decode_instructions; + // tries to load library and return whether it succedded. + static bool load_library(); + + // Machine dependent stuff + #include "incls/_disassembler_pd.hpp.incl" + + public: + static bool can_decode() { + return (_decode_instructions != NULL) || load_library(); + } + static void decode(CodeBlob *cb, outputStream* st = NULL); + static void decode(nmethod* nm, outputStream* st = NULL); + static void decode(address begin, address end, outputStream* st = NULL); +}; diff --git a/hotspot/src/share/vm/compiler/disassemblerEnv.hpp b/hotspot/src/share/vm/compiler/disassemblerEnv.hpp deleted file mode 100644 index 69bb38f77c1..00000000000 --- a/hotspot/src/share/vm/compiler/disassemblerEnv.hpp +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright 1997-2002 Sun Microsystems, Inc. All Rights Reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - * - */ - -// Call-back interface for external disassembler -class DisassemblerEnv { - public: - // printing - virtual void print_label(intptr_t value) = 0; - virtual void print_raw(char* str) = 0; - virtual void print(char* format, ...) = 0; - // helpers - virtual char* string_for_offset(intptr_t value) = 0; - virtual char* string_for_constant(unsigned char* pc, intptr_t value, int is_decimal) = 0; -}; diff --git a/hotspot/src/share/vm/compiler/oopMap.cpp b/hotspot/src/share/vm/compiler/oopMap.cpp index b4a85f787f8..9f5a1ada4d6 100644 --- a/hotspot/src/share/vm/compiler/oopMap.cpp +++ b/hotspot/src/share/vm/compiler/oopMap.cpp @@ -505,8 +505,13 @@ bool OopMap::has_derived_pointer() const { #endif // COMPILER2 } +#endif //PRODUCT -static void print_register_type(OopMapValue::oop_types x, VMReg optional, outputStream* st) { +// Printing code is present in product build for -XX:+PrintAssembly. + +static +void print_register_type(OopMapValue::oop_types x, VMReg optional, + outputStream* st) { switch( x ) { case OopMapValue::oop_value: st->print("Oop"); @@ -544,10 +549,12 @@ void OopMapValue::print_on(outputStream* st) const { void OopMap::print_on(outputStream* st) const { OopMapValue omv; + st->print("OopMap{"); for(OopMapStream oms((OopMap*)this); !oms.is_done(); oms.next()) { omv = oms.current(); omv.print_on(st); } + st->print("off=%d}", (int) offset()); } @@ -558,12 +565,12 @@ void OopMapSet::print_on(outputStream* st) const { for( i = 0; i < len; i++) { OopMap* m = at(i); - st->print_cr("OopMap #%d offset:%p",i,m->offset()); + st->print_cr("#%d ",i); m->print_on(st); - st->print_cr("\n"); + st->cr(); } } -#endif // !PRODUCT + //------------------------------DerivedPointerTable--------------------------- diff --git a/hotspot/src/share/vm/compiler/oopMap.hpp b/hotspot/src/share/vm/compiler/oopMap.hpp index 8b678368247..5c9c8c42ff9 100644 --- a/hotspot/src/share/vm/compiler/oopMap.hpp +++ b/hotspot/src/share/vm/compiler/oopMap.hpp @@ -129,7 +129,7 @@ public: return reg()->reg2stack(); } - void print_on(outputStream* st) const PRODUCT_RETURN; + void print_on(outputStream* st) const; void print() const { print_on(tty); } }; @@ -193,7 +193,7 @@ class OopMap: public ResourceObj { } // Printing - void print_on(outputStream* st) const PRODUCT_RETURN; + void print_on(outputStream* st) const; void print() const { print_on(tty); } }; @@ -248,7 +248,7 @@ class OopMapSet : public ResourceObj { OopClosure* value_fn, OopClosure* dead_fn); // Printing - void print_on(outputStream* st) const PRODUCT_RETURN; + void print_on(outputStream* st) const; void print() const { print_on(tty); } }; diff --git a/hotspot/src/share/vm/includeDB_compiler1 b/hotspot/src/share/vm/includeDB_compiler1 index 37bb58ccc32..ae500d2f6d7 100644 --- a/hotspot/src/share/vm/includeDB_compiler1 +++ b/hotspot/src/share/vm/includeDB_compiler1 @@ -323,7 +323,7 @@ c1_Runtime1.cpp collectedHeap.hpp c1_Runtime1.cpp compilationPolicy.hpp c1_Runtime1.cpp compiledIC.hpp c1_Runtime1.cpp copy.hpp -c1_Runtime1.cpp disassembler_.hpp +c1_Runtime1.cpp disassembler.hpp c1_Runtime1.cpp events.hpp c1_Runtime1.cpp interfaceSupport.hpp c1_Runtime1.cpp interpreter.hpp diff --git a/hotspot/src/share/vm/includeDB_core b/hotspot/src/share/vm/includeDB_core index 17404cec658..06eb247de6d 100644 --- a/hotspot/src/share/vm/includeDB_core +++ b/hotspot/src/share/vm/includeDB_core @@ -244,7 +244,7 @@ assembler.hpp vm_version_.hpp assembler.inline.hpp assembler.hpp assembler.inline.hpp codeBuffer.hpp -assembler.inline.hpp disassembler_.hpp +assembler.inline.hpp disassembler.hpp assembler.inline.hpp threadLocalStorage.hpp assembler_.cpp assembler_.inline.hpp @@ -946,7 +946,7 @@ codeBlob.cpp allocation.inline.hpp codeBlob.cpp bytecode.hpp codeBlob.cpp codeBlob.hpp codeBlob.cpp codeCache.hpp -codeBlob.cpp disassembler_.hpp +codeBlob.cpp disassembler.hpp codeBlob.cpp forte.hpp codeBlob.cpp handles.inline.hpp codeBlob.cpp heap.hpp @@ -968,7 +968,7 @@ codeBlob.hpp oopMap.hpp codeBuffer.cpp codeBuffer.hpp codeBuffer.cpp copy.hpp -codeBuffer.cpp disassembler_.hpp +codeBuffer.cpp disassembler.hpp codeBuffer.hpp assembler.hpp codeBuffer.hpp oopRecorder.hpp @@ -1323,7 +1323,7 @@ debug.cpp codeCache.hpp debug.cpp collectedHeap.hpp debug.cpp compileBroker.hpp debug.cpp defaultStream.hpp -debug.cpp disassembler_.hpp +debug.cpp disassembler.hpp debug.cpp events.hpp debug.cpp frame.hpp debug.cpp heapDumper.hpp @@ -1442,7 +1442,7 @@ deoptimization.hpp allocation.hpp deoptimization.hpp frame.inline.hpp depChecker_.cpp depChecker_.hpp -depChecker_.cpp disassembler_.hpp +depChecker_.cpp disassembler.hpp depChecker_.cpp hpi.hpp dependencies.cpp ciArrayKlass.hpp @@ -1472,21 +1472,21 @@ dictionary.hpp instanceKlass.hpp dictionary.hpp oop.hpp dictionary.hpp systemDictionary.hpp -disassemblerEnv.hpp globals.hpp +disassembler_.hpp generate_platform_dependent_include -disassembler_.cpp cardTableModRefBS.hpp -disassembler_.cpp codeCache.hpp -disassembler_.cpp collectedHeap.hpp -disassembler_.cpp depChecker_.hpp -disassembler_.cpp disassembler_.hpp -disassembler_.cpp fprofiler.hpp -disassembler_.cpp handles.inline.hpp -disassembler_.cpp hpi.hpp -disassembler_.cpp stubCodeGenerator.hpp -disassembler_.cpp stubRoutines.hpp +disassembler.cpp cardTableModRefBS.hpp +disassembler.cpp codeCache.hpp +disassembler.cpp collectedHeap.hpp +disassembler.cpp depChecker_.hpp +disassembler.cpp disassembler.hpp +disassembler.cpp fprofiler.hpp +disassembler.cpp handles.inline.hpp +disassembler.cpp hpi.hpp +disassembler.cpp stubCodeGenerator.hpp +disassembler.cpp stubRoutines.hpp -disassembler_.hpp disassemblerEnv.hpp -disassembler_.hpp os_.inline.hpp +disassembler.hpp globals.hpp +disassembler.hpp os_.inline.hpp dtraceAttacher.cpp codeCache.hpp dtraceAttacher.cpp deoptimization.hpp @@ -2909,7 +2909,7 @@ nmethod.cpp codeCache.hpp nmethod.cpp compileLog.hpp nmethod.cpp compiledIC.hpp nmethod.cpp compilerOracle.hpp -nmethod.cpp disassembler_.hpp +nmethod.cpp disassembler.hpp nmethod.cpp dtrace.hpp nmethod.cpp events.hpp nmethod.cpp jvmtiRedefineClassesTrace.hpp @@ -3763,7 +3763,7 @@ statSampler.hpp perfData.hpp statSampler.hpp task.hpp stubCodeGenerator.cpp assembler_.inline.hpp -stubCodeGenerator.cpp disassembler_.hpp +stubCodeGenerator.cpp disassembler.hpp stubCodeGenerator.cpp forte.hpp stubCodeGenerator.cpp oop.inline.hpp stubCodeGenerator.cpp stubCodeGenerator.hpp @@ -4530,7 +4530,7 @@ vmreg_.cpp vmreg.hpp vmreg_.hpp generate_platform_dependent_include vtableStubs.cpp allocation.inline.hpp -vtableStubs.cpp disassembler_.hpp +vtableStubs.cpp disassembler.hpp vtableStubs.cpp forte.hpp vtableStubs.cpp handles.inline.hpp vtableStubs.cpp instanceKlass.hpp diff --git a/hotspot/src/share/vm/opto/compile.cpp b/hotspot/src/share/vm/opto/compile.cpp index 3fe43b53095..87423517536 100644 --- a/hotspot/src/share/vm/opto/compile.cpp +++ b/hotspot/src/share/vm/opto/compile.cpp @@ -456,7 +456,15 @@ Compile::Compile( ciEnv* ci_env, C2Compiler* compiler, ciMethod* target, int osr } TraceTime t1("Total compilation time", &_t_totalCompilation, TimeCompiler, TimeCompiler2); TraceTime t2(NULL, &_t_methodCompilation, TimeCompiler, false); - set_print_assembly(PrintOptoAssembly || _method->should_print_assembly()); + bool print_opto_assembly = PrintOptoAssembly || _method->has_option("PrintOptoAssembly"); + if (!print_opto_assembly) { + bool print_assembly = (PrintAssembly || _method->should_print_assembly()); + if (print_assembly && !Disassembler::can_decode()) { + tty->print_cr("PrintAssembly request changed to PrintOptoAssembly"); + print_opto_assembly = true; + } + } + set_print_assembly(print_opto_assembly); #endif if (ProfileTraps) { diff --git a/hotspot/src/share/vm/runtime/globals.hpp b/hotspot/src/share/vm/runtime/globals.hpp index 1a46a00b7d9..9f79daac102 100644 --- a/hotspot/src/share/vm/runtime/globals.hpp +++ b/hotspot/src/share/vm/runtime/globals.hpp @@ -668,16 +668,19 @@ class CommandLineFlags { notproduct(bool, PrintCompilation2, false, \ "Print additional statistics per compilation") \ \ - notproduct(bool, PrintAdapterHandlers, false, \ + diagnostic(bool, PrintAdapterHandlers, false, \ "Print code generated for i2c/c2i adapters") \ \ - develop(bool, PrintAssembly, false, \ - "Print assembly code") \ + diagnostic(bool, PrintAssembly, false, \ + "Print assembly code (using external disassembler.so)") \ \ - develop(bool, PrintNMethods, false, \ + diagnostic(ccstr, PrintAssemblyOptions, false, \ + "Options string passed to disassembler.so") \ + \ + diagnostic(bool, PrintNMethods, false, \ "Print assembly code for nmethods when generated") \ \ - develop(bool, PrintNativeNMethods, false, \ + diagnostic(bool, PrintNativeNMethods, false, \ "Print assembly code for native nmethods when generated") \ \ develop(bool, PrintDebugInfo, false, \ @@ -702,7 +705,7 @@ class CommandLineFlags { develop(bool, PrintCodeCache2, false, \ "Print detailed info on the compiled_code cache when exiting") \ \ - develop(bool, PrintStubCode, false, \ + diagnostic(bool, PrintStubCode, false, \ "Print generated stub code") \ \ product(bool, StackTraceInThrowable, true, \ @@ -2250,7 +2253,7 @@ class CommandLineFlags { product_pd(bool, RewriteFrequentPairs, \ "Rewrite frequently used bytecode pairs into a single bytecode") \ \ - product(bool, PrintInterpreter, false, \ + diagnostic(bool, PrintInterpreter, false, \ "Prints the generated interpreter code") \ \ product(bool, UseInterpreter, true, \ @@ -2300,7 +2303,7 @@ class CommandLineFlags { develop(bool, PrintBytecodePairHistogram, false, \ "Print histogram of the executed bytecode pairs") \ \ - develop(bool, PrintSignatureHandlers, false, \ + diagnostic(bool, PrintSignatureHandlers, false, \ "Print code generated for native method signature handlers") \ \ develop(bool, VerifyOops, false, \ diff --git a/hotspot/src/share/vm/runtime/stubCodeGenerator.cpp b/hotspot/src/share/vm/runtime/stubCodeGenerator.cpp index bbdd6898b75..9b54e95eaa1 100644 --- a/hotspot/src/share/vm/runtime/stubCodeGenerator.cpp +++ b/hotspot/src/share/vm/runtime/stubCodeGenerator.cpp @@ -69,7 +69,6 @@ StubCodeGenerator::StubCodeGenerator(CodeBuffer* code) { _first_stub = _last_stub = NULL; } -#ifndef PRODUCT extern "C" { static int compare_cdesc(const void* void_a, const void* void_b) { int ai = (*((StubCodeDesc**) void_a))->index(); @@ -77,10 +76,8 @@ extern "C" { return ai - bi; } } -#endif StubCodeGenerator::~StubCodeGenerator() { -#ifndef PRODUCT if (PrintStubCode) { CodeBuffer* cbuf = _masm->code(); CodeBlob* blob = CodeCache::find_blob_unsafe(cbuf->insts()->start()); @@ -105,7 +102,6 @@ StubCodeGenerator::~StubCodeGenerator() { tty->cr(); } } -#endif //PRODUCT } diff --git a/hotspot/src/share/vm/utilities/ostream.cpp b/hotspot/src/share/vm/utilities/ostream.cpp index d5ad211fc01..e5139f1dd30 100644 --- a/hotspot/src/share/vm/utilities/ostream.cpp +++ b/hotspot/src/share/vm/utilities/ostream.cpp @@ -52,8 +52,9 @@ void outputStream::update_position(const char* s, size_t len) { _precount += _position + 1; _position = 0; } else if (ch == '\t') { - _position += 8; - _precount -= 7; // invariant: _precount + _position == total count + int tw = 8 - (_position & 7); + _position += tw; + _precount -= tw-1; // invariant: _precount + _position == total count } else { _position += 1; } @@ -133,7 +134,17 @@ void outputStream::vprint_cr(const char* format, va_list argptr) { } void outputStream::fill_to(int col) { - while (position() < col) sp(); + int need_fill = col - position(); + sp(need_fill); +} + +void outputStream::move_to(int col, int slop, int min_space) { + if (position() >= col + slop) + cr(); + int need_fill = col - position(); + if (need_fill < min_space) + need_fill = min_space; + sp(need_fill); } void outputStream::put(char ch) { @@ -142,8 +153,23 @@ void outputStream::put(char ch) { write(buf, 1); } -void outputStream::sp() { - this->write(" ", 1); +#define SP_USE_TABS false + +void outputStream::sp(int count) { + if (count < 0) return; + if (SP_USE_TABS && count >= 8) { + int target = position() + count; + while (count >= 8) { + this->write("\t", 1); + count -= 8; + } + count = target - position(); + } + while (count > 0) { + int nw = (count > 8) ? 8 : count; + this->write(" ", nw); + count -= nw; + } } void outputStream::cr() { diff --git a/hotspot/src/share/vm/utilities/ostream.hpp b/hotspot/src/share/vm/utilities/ostream.hpp index 3d50c69888e..7232b485096 100644 --- a/hotspot/src/share/vm/utilities/ostream.hpp +++ b/hotspot/src/share/vm/utilities/ostream.hpp @@ -59,6 +59,7 @@ class outputStream : public ResourceObj { int indentation() const { return _indentation; } void set_indentation(int i) { _indentation = i; } void fill_to(int col); + void move_to(int col, int slop = 6, int min_space = 2); // sizing int width() const { return _width; } @@ -78,7 +79,7 @@ class outputStream : public ResourceObj { void print_raw_cr(const char* str) { write(str, strlen(str)); cr(); } void print_raw_cr(const char* str, int len){ write(str, len); cr(); } void put(char ch); - void sp(); + void sp(int count = 1); void cr(); void bol() { if (_position > 0) cr(); } From ccaa58c5db50f8a184b2f6ff3e3f184a8b8c24b2 Mon Sep 17 00:00:00 2001 From: Vladimir Kozlov Date: Wed, 2 Apr 2008 16:59:37 -0700 Subject: [PATCH 131/258] 6681577: PIT: some VM tests fails with -XX:+AggressiveOpts in 6u5p b01 C2 spends > 60% in escape analysis code during test nsk/regression/b4675027. Reviewed-by: never --- hotspot/src/share/vm/opto/escape.cpp | 70 ++++++++++++++++------------ hotspot/src/share/vm/opto/escape.hpp | 2 +- 2 files changed, 42 insertions(+), 30 deletions(-) diff --git a/hotspot/src/share/vm/opto/escape.cpp b/hotspot/src/share/vm/opto/escape.cpp index e587cee177f..d3640ecb3a5 100644 --- a/hotspot/src/share/vm/opto/escape.cpp +++ b/hotspot/src/share/vm/opto/escape.cpp @@ -256,39 +256,49 @@ void ConnectionGraph::PointsTo(VectorSet &ptset, Node * n, PhaseTransform *phase } } -void ConnectionGraph::remove_deferred(uint ni) { - VectorSet visited(Thread::current()->resource_area()); +void ConnectionGraph::remove_deferred(uint ni, GrowableArray* deferred_edges, VectorSet* visited) { + // This method is most expensive during ConnectionGraph construction. + // Reuse vectorSet and an additional growable array for deferred edges. + deferred_edges->clear(); + visited->Clear(); uint i = 0; PointsToNode *ptn = ptnode_adr(ni); - while(i < ptn->edge_count()) { + // Mark current edges as visited and move deferred edges to separate array. + for (; i < ptn->edge_count(); i++) { uint t = ptn->edge_target(i); - PointsToNode *ptt = ptnode_adr(t); - if (ptn->edge_type(i) != PointsToNode::DeferredEdge) { - i++; - } else { +#ifdef ASSERT + assert(!visited->test_set(t), "expecting no duplications"); +#else + visited->set(t); +#endif + if (ptn->edge_type(i) == PointsToNode::DeferredEdge) { ptn->remove_edge(t, PointsToNode::DeferredEdge); - if(!visited.test_set(t)) { - for (uint j = 0; j < ptt->edge_count(); j++) { - uint n1 = ptt->edge_target(j); - PointsToNode *pt1 = ptnode_adr(n1); - switch(ptt->edge_type(j)) { - case PointsToNode::PointsToEdge: - add_pointsto_edge(ni, n1); - if(n1 == _phantom_object) { - // Special case - field set outside (globally escaping). - ptn->set_escape_state(PointsToNode::GlobalEscape); - } - break; - case PointsToNode::DeferredEdge: - add_deferred_edge(ni, n1); - break; - case PointsToNode::FieldEdge: - assert(false, "invalid connection graph"); - break; + deferred_edges->append(t); + } + } + for (int next = 0; next < deferred_edges->length(); ++next) { + uint t = deferred_edges->at(next); + PointsToNode *ptt = ptnode_adr(t); + for (uint j = 0; j < ptt->edge_count(); j++) { + uint n1 = ptt->edge_target(j); + if (visited->test_set(n1)) + continue; + switch(ptt->edge_type(j)) { + case PointsToNode::PointsToEdge: + add_pointsto_edge(ni, n1); + if(n1 == _phantom_object) { + // Special case - field set outside (globally escaping). + ptn->set_escape_state(PointsToNode::GlobalEscape); } - } + break; + case PointsToNode::DeferredEdge: + deferred_edges->append(n1); + break; + case PointsToNode::FieldEdge: + assert(false, "invalid connection graph"); + break; } } } @@ -1236,8 +1246,10 @@ void ConnectionGraph::compute_escape() { } VectorSet ptset(Thread::current()->resource_area()); - GrowableArray alloc_worklist; - GrowableArray worklist; + GrowableArray alloc_worklist; + GrowableArray worklist; + GrowableArray deferred_edges; + VectorSet visited(Thread::current()->resource_area()); // remove deferred edges from the graph and collect // information we will need for type splitting @@ -1247,7 +1259,7 @@ void ConnectionGraph::compute_escape() { PointsToNode::NodeType nt = ptn->node_type(); Node *n = ptn->_node; if (nt == PointsToNode::LocalVar || nt == PointsToNode::Field) { - remove_deferred(ni); + remove_deferred(ni, &deferred_edges, &visited); if (n->is_AddP()) { // If this AddP computes an address which may point to more that one // object, nothing the address points to can be scalar replaceable. diff --git a/hotspot/src/share/vm/opto/escape.hpp b/hotspot/src/share/vm/opto/escape.hpp index a7552b2c3ae..1d2c83511e7 100644 --- a/hotspot/src/share/vm/opto/escape.hpp +++ b/hotspot/src/share/vm/opto/escape.hpp @@ -269,7 +269,7 @@ private: // Remove outgoing deferred edges from the node referenced by "ni". // Any outgoing edges from the target of the deferred edge are copied // to "ni". - void remove_deferred(uint ni); + void remove_deferred(uint ni, GrowableArray* deferred_edges, VectorSet* visited); Node_Array _node_map; // used for bookeeping during type splitting // Used for the following purposes: From 2dddf4033e5e38d37344c6793976075035b9e9fc Mon Sep 17 00:00:00 2001 From: Xue-Lei Andrew Fan Date: Wed, 2 Apr 2008 22:44:45 -0400 Subject: [PATCH 132/258] 6668231: Presence of a critical subjectAltName causes JSSE's SunX509 to fail trusted checks Make the critical extension known to end entity checker. Reviewed-by: wetmore, mullan --- .../security/validator/EndEntityChecker.java | 10 + .../CriticalSubjectAltName.java | 262 ++++++++++++++++++ .../https/HttpsURLConnection/crisubn.jks | Bin 0 -> 2794 bytes .../https/HttpsURLConnection/trusted.jks | Bin 0 -> 743 bytes 4 files changed, 272 insertions(+) create mode 100644 jdk/test/sun/security/ssl/com/sun/net/ssl/internal/www/protocol/https/HttpsURLConnection/CriticalSubjectAltName.java create mode 100644 jdk/test/sun/security/ssl/com/sun/net/ssl/internal/www/protocol/https/HttpsURLConnection/crisubn.jks create mode 100644 jdk/test/sun/security/ssl/com/sun/net/ssl/internal/www/protocol/https/HttpsURLConnection/trusted.jks diff --git a/jdk/src/share/classes/sun/security/validator/EndEntityChecker.java b/jdk/src/share/classes/sun/security/validator/EndEntityChecker.java index f0fb1787fa3..189db3dd058 100644 --- a/jdk/src/share/classes/sun/security/validator/EndEntityChecker.java +++ b/jdk/src/share/classes/sun/security/validator/EndEntityChecker.java @@ -87,6 +87,9 @@ class EndEntityChecker { // the Microsoft Server-Gated-Cryptography EKU extension OID private final static String OID_EKU_MS_SGC = "1.3.6.1.4.1.311.10.3.3"; + // the recognized extension OIDs + private final static String OID_SUBJECT_ALT_NAME = "2.5.29.17"; + private final static String NSCT_SSL_CLIENT = NetscapeCertTypeExtension.SSL_CLIENT; @@ -171,6 +174,13 @@ class EndEntityChecker { throws CertificateException { // basic constraints irrelevant in EE certs exts.remove(SimpleValidator.OID_BASIC_CONSTRAINTS); + + // If the subject field contains an empty sequence, the subjectAltName + // extension MUST be marked critical. + // We do not check the validity of the critical extension, just mark + // it recognizable here. + exts.remove(OID_SUBJECT_ALT_NAME); + if (!exts.isEmpty()) { throw new CertificateException("Certificate contains unsupported " + "critical extensions: " + exts); diff --git a/jdk/test/sun/security/ssl/com/sun/net/ssl/internal/www/protocol/https/HttpsURLConnection/CriticalSubjectAltName.java b/jdk/test/sun/security/ssl/com/sun/net/ssl/internal/www/protocol/https/HttpsURLConnection/CriticalSubjectAltName.java new file mode 100644 index 00000000000..ffd70754168 --- /dev/null +++ b/jdk/test/sun/security/ssl/com/sun/net/ssl/internal/www/protocol/https/HttpsURLConnection/CriticalSubjectAltName.java @@ -0,0 +1,262 @@ +/* + * Copyright 2001-2008 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* + * @test + * @bug 6668231 + * @summary Presence of a critical subjectAltName causes JSSE's SunX509 to + * fail trusted checks + * @author Xuelei Fan + * + * This test depends on binary keystore, crisubn.jks and trusted.jks. Because + * JAVA keytool cannot generate X509 certificate with SubjectAltName extension, + * the certificates are generated with openssl toolkits and then imported into + * JAVA keystore. + * + * The crisubn.jks holds a private key entry and the corresponding X509 + * certificate issued with an empty Subject field, and a critical + * SubjectAltName extension. + * + * The trusted.jks holds the trusted certificate. + */ +import java.io.*; +import java.net.*; +import javax.net.ssl.*; +import java.security.cert.Certificate; + +public class CriticalSubjectAltName implements HostnameVerifier { + /* + * ============================================================= + * Set the various variables needed for the tests, then + * specify what tests to run on each side. + */ + + /* + * Should we run the client or server in a separate thread? + * Both sides can throw exceptions, but do you have a preference + * as to which side should be the main thread. + */ + static boolean separateServerThread = true; + + /* + * Where do we find the keystores? + */ + static String pathToStores = "./"; + static String keyStoreFile = "crisubn.jks"; + static String trustStoreFile = "trusted.jks"; + static String passwd = "passphrase"; + + /* + * Is the server ready to serve? + */ + volatile static boolean serverReady = false; + + /* + * Turn on SSL debugging? + */ + static boolean debug = false; + + /* + * If the client or server is doing some kind of object creation + * that the other side depends on, and that thread prematurely + * exits, you may experience a hang. The test harness will + * terminate all hung threads after its timeout has expired, + * currently 3 minutes by default, but you might try to be + * smart about it.... + */ + + /* + * Define the server side of the test. + * + * If the server prematurely exits, serverReady will be set to true + * to avoid infinite hangs. + */ + void doServerSide() throws Exception { + SSLServerSocketFactory sslssf = + (SSLServerSocketFactory) SSLServerSocketFactory.getDefault(); + SSLServerSocket sslServerSocket = + (SSLServerSocket) sslssf.createServerSocket(serverPort); + serverPort = sslServerSocket.getLocalPort(); + + /* + * Signal Client, we're ready for his connect. + */ + serverReady = true; + + SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept(); + OutputStream sslOS = sslSocket.getOutputStream(); + BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(sslOS)); + bw.write("HTTP/1.1 200 OK\r\n\r\n\r\n"); + bw.flush(); + Thread.sleep(5000); + sslSocket.close(); + } + + /* + * Define the client side of the test. + * + * If the server prematurely exits, serverReady will be set to true + * to avoid infinite hangs. + */ + void doClientSide() throws Exception { + + /* + * Wait for server to get started. + */ + while (!serverReady) { + Thread.sleep(50); + } + + URL url = new URL("https://localhost:"+serverPort+"/index.html"); + HttpsURLConnection urlc = (HttpsURLConnection)url.openConnection(); + urlc.setHostnameVerifier(this); + urlc.getInputStream(); + + if (urlc.getResponseCode() == -1) { + throw new RuntimeException("getResponseCode() returns -1"); + } + } + + /* + * ============================================================= + * The remainder is just support stuff + */ + + // use any free port by default + volatile int serverPort = 0; + + volatile Exception serverException = null; + volatile Exception clientException = null; + + public static void main(String[] args) throws Exception { + String keyFilename = + System.getProperty("test.src", "./") + "/" + pathToStores + + "/" + keyStoreFile; + String trustFilename = + System.getProperty("test.src", "./") + "/" + pathToStores + + "/" + trustStoreFile; + + System.setProperty("javax.net.ssl.keyStore", keyFilename); + System.setProperty("javax.net.ssl.keyStorePassword", passwd); + System.setProperty("javax.net.ssl.trustStore", trustFilename); + System.setProperty("javax.net.ssl.trustStorePassword", passwd); + + if (debug) + System.setProperty("javax.net.debug", "all"); + + /* + * Start the tests. + */ + new CriticalSubjectAltName(); + } + + Thread clientThread = null; + Thread serverThread = null; + + /* + * Primary constructor, used to drive remainder of the test. + * + * Fork off the other side, then do your work. + */ + CriticalSubjectAltName() throws Exception { + if (separateServerThread) { + startServer(true); + startClient(false); + } else { + startClient(true); + startServer(false); + } + + /* + * Wait for other side to close down. + */ + if (separateServerThread) { + serverThread.join(); + } else { + clientThread.join(); + } + + /* + * When we get here, the test is pretty much over. + * + * If the main thread excepted, that propagates back + * immediately. If the other thread threw an exception, we + * should report back. + */ + if (serverException != null) + throw serverException; + if (clientException != null) + throw clientException; + } + + void startServer(boolean newThread) throws Exception { + if (newThread) { + serverThread = new Thread() { + public void run() { + try { + doServerSide(); + } catch (Exception e) { + /* + * Our server thread just died. + * + * Release the client, if not active already... + */ + System.err.println("Server died..."); + serverReady = true; + serverException = e; + } + } + }; + serverThread.start(); + } else { + doServerSide(); + } + } + + void startClient(boolean newThread) throws Exception { + if (newThread) { + clientThread = new Thread() { + public void run() { + try { + doClientSide(); + } catch (Exception e) { + /* + * Our client thread just died. + */ + System.err.println("Client died..."); + clientException = e; + } + } + }; + clientThread.start(); + } else { + doClientSide(); + } + } + + // Simple test method to blindly agree that hostname and certname match + public boolean verify(String hostname, SSLSession session) { + return true; + } + +} diff --git a/jdk/test/sun/security/ssl/com/sun/net/ssl/internal/www/protocol/https/HttpsURLConnection/crisubn.jks b/jdk/test/sun/security/ssl/com/sun/net/ssl/internal/www/protocol/https/HttpsURLConnection/crisubn.jks new file mode 100644 index 0000000000000000000000000000000000000000..aee7d9f33792257b9c20599e198cb52e84e44303 GIT binary patch literal 2794 zcmeH}SyYqP7RSFY6DE)XhOvxArPHh)P2vH9D zK;l9Yq$IAGXgZ{+jE9Jji3vm`l1L=;Gs<{lGDI>q-!h#BW)lGl!H9!u?Px6@Yhc~z+0d)cWb1FHUdDD>v?R^y?> ze;zQg?ISZkOBt5BW<$wvqqyX$uf?nGwdz}{NU{MD?FGj2`myVMwKfS;+ss$_MmD;w znMZ>y&~qET-j`mGs#dbs-}Ha7_e|)mwZnTW8XIoBj3gleg@%wIxbtoaVHqId z+6AP?j|?jEo48OgjZNiWISS;RQ>?|Na%-rb>IXjx<5D{vkyM$F@sYUvGY?Z6rR(mn zN|aB_H~87VS!JloHElFlCGD-XGOQKk(GHxCw6wU&J=IVqLaF!Q<``QAshTBX_(7-Lwc^apJww79s*vsUTR{Wc2v zs{~p+6u0+cj|ci#)v3gxZf8&d?1&%J&u;jpZPjqKOQ+sr)a}{NMHj|`oog@vuE%;L zzfBd#&%%e(%tZ&`T^q;UyAZ8e?emoB$ka3V}*sKIu{;ZQX}67x>9%gS2ICp zH4R#hU<coWLbNTG*;N`cF;Q1{pad6})&{!wmOG3)S`#{9htC(V|1 za@LE&yR|~!tXGpSk0h}|+8iRJi6fTnsW&ZB9=u+2Y@OIwl;x$r@V$uBS9DzCIC~z| zA_fC5a7$Dc^MC1F&ahpXz{TC*d>pQ{R{1D`hu0nb)><)BVQAtGeUCPF+~<|k>MT*C zJH_F(XBW>SQg`xiFSnPxXP<8(D-Ecm>xbeTB3{%b&iHmcwd`e$LW8=G<9=@1Dzixr z<~~`Ty_~1@omDnZn5O@{`|yC(%#bI?&Y+Iuap|^Ywi^glU{~foY{8RD@z;GK& z+H77z_Loja>6F-y&16PB=8XY`3#zFJV))&BV!ms zyXOY84a^7Kwi{GCr4OU5W%m0KVrRA|?MymFD;?wZsZNuHSM+R&x$?Arm{v&A@rPUBjQ^^MfqYD8a`49%{ zpJfkby|D)IC@m!omsonVyStON9X*=PfIq7sZ5uj+85SHC2pjJ(SfRt{{JhKdhPPb( z;XbzT&<{^m1|hBA7_0&*{W*gnJ;??bH9IJE=tCBPo*WPr8%ei{fs=*@MHofXnK?)U z~3aEn!4n;G(ciyuP8 zsznt3Yrrlj+@A9!>zTzOU2`Ay>1Isn-M8#9$aki`XFzP+SZ}^DJgOMiLwn|ZS6^-! zm=EZW)_Y6+R?Z~7y1XSz+>s&@j-Aw%zQY}b{u%-P8Ug-mK>L3f0WuHHo!wu+LAs>S O7Sr#R-7eCxQu+@^S{GCR literal 0 HcmV?d00001 diff --git a/jdk/test/sun/security/ssl/com/sun/net/ssl/internal/www/protocol/https/HttpsURLConnection/trusted.jks b/jdk/test/sun/security/ssl/com/sun/net/ssl/internal/www/protocol/https/HttpsURLConnection/trusted.jks new file mode 100644 index 0000000000000000000000000000000000000000..0202bec16205771e8143c9bb2ca5d13d015dc6bf GIT binary patch literal 743 zcmezO_TO6u1_mY|W(3nLiSfyaK#n8_!;~outPy&q29`kiRR&E=%Yc}F0W%XL6B8qY z0WTY;R+~rLcV0$D7FGrWcSCLiPB!LH7B*p~&|pJh13?gnLzpW#KQ~o3xFoS8)lkrY zA0)^n%mETq@GnX?6foce2{8+^gM{+)QVrz9c?}E=jExNp4NXi;%%jA4jVugIjLe~2 z>RHq{AK4F#tPISJy$lA8olK3531z*mub}oJLyX0e!p0moXR{Jz7)>q%pMNfZZviL*$mme1+g`zUHSEQ_D zVrFDuT->C)WBL^Wc888FGF0sD&`eo6LTbCN7g*I7loNv$2 z)gZc>vuf!o>o6H@#muGF2fdlCd0csOxO$?_RBhqju)A@Zc(~x^c#j{SiX;WLe&6g+ zF0|S~clG|RP|b-sHdYIk25z4Hl||+>*Q=smy;U`LzW Date: Thu, 3 Apr 2008 15:00:21 +0400 Subject: [PATCH 133/258] 6619458: testcase depends on a file with the name te{st.html Using test.html instead of te{st.html in reg test Reviewed-by: son --- .../IOExceptionIfEncodedURLTest.java | 64 +++++ .../IOExceptionIfEncodedURLTest.sh | 231 ++++++++++++++++++ .../IOExceptionIfEncodedURLTest/test.html | 21 ++ 3 files changed, 316 insertions(+) create mode 100644 jdk/test/java/awt/appletviewer/IOExceptionIfEncodedURLTest/IOExceptionIfEncodedURLTest.java create mode 100644 jdk/test/java/awt/appletviewer/IOExceptionIfEncodedURLTest/IOExceptionIfEncodedURLTest.sh create mode 100644 jdk/test/java/awt/appletviewer/IOExceptionIfEncodedURLTest/test.html diff --git a/jdk/test/java/awt/appletviewer/IOExceptionIfEncodedURLTest/IOExceptionIfEncodedURLTest.java b/jdk/test/java/awt/appletviewer/IOExceptionIfEncodedURLTest/IOExceptionIfEncodedURLTest.java new file mode 100644 index 00000000000..5d7a73e9996 --- /dev/null +++ b/jdk/test/java/awt/appletviewer/IOExceptionIfEncodedURLTest/IOExceptionIfEncodedURLTest.java @@ -0,0 +1,64 @@ +/* + * Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* + test + @bug 6193279 + @summary REGRESSION: AppletViewer throws IOException when path is encoded URL + @author Dmitry Cherepanov: area=appletviewer + @run compile IOExceptionIfEncodedURLTest.java + @run main IOExceptionIfEncodedURLTest + @run shell IOExceptionIfEncodedURLTest.sh +*/ + +import java.applet.Applet; +import sun.net.www.ParseUtil; +import java.io.File; +import java.net.MalformedURLException; + +public class IOExceptionIfEncodedURLTest extends Applet{ + public void init(){ + } + + public void start(){ + // We check that appletviewer writes this message to log file + System.err.println("the appletviewer started"); + } + + // We expect that sun.net.www.ParseUtil.fileToEncodedURL works like following + // if relative file URL, like this "file:index.html" is processed + static String url = "file:IOExceptionIfEncodedURLTest.java"; + public static final void main(String args[]) + throws MalformedURLException{ + System.err.println("prior checking..."); + String prefix = "file:"; + String path = ParseUtil.fileToEncodedURL(new File(System.getProperty("user.dir"))).getPath(); + String filename = url.substring(prefix.length()); + System.err.println("url="+url+" -> path="+path+",filename="+filename); + + if (!path.endsWith("/") && !filename.startsWith("/")) { + throw new RuntimeException("Incorrect '/' processing"); + } + } + +} diff --git a/jdk/test/java/awt/appletviewer/IOExceptionIfEncodedURLTest/IOExceptionIfEncodedURLTest.sh b/jdk/test/java/awt/appletviewer/IOExceptionIfEncodedURLTest/IOExceptionIfEncodedURLTest.sh new file mode 100644 index 00000000000..9df3e58741b --- /dev/null +++ b/jdk/test/java/awt/appletviewer/IOExceptionIfEncodedURLTest/IOExceptionIfEncodedURLTest.sh @@ -0,0 +1,231 @@ +# +# Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. +# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. +# +# This code is free software; you can redistribute it and/or modify it +# under the terms of the GNU General Public License version 2 only, as +# published by the Free Software Foundation. Sun designates this +# particular file as subject to the "Classpath" exception as provided +# by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, +# CA 95054 USA or visit www.sun.com if you need additional information or +# have any questions. +# + +#!/bin/ksh -p +# +# @test IOExceptionIfEncodedURLTest.sh +# @bug 6193279 6619458 +# @summary REGRESSION: AppletViewer throws IOException when path is encoded URL +# @author Dmitry Cherepanov: area=appletviewer +# @run compile IOExceptionIfEncodedURLTest.java +# @run main IOExceptionIfEncodedURLTest +# @run shell IOExceptionIfEncodedURLTest.sh + +# Beginning of subroutines: +status=1 + +#Call this from anywhere to fail the test with an error message +# usage: fail "reason why the test failed" +fail() + { echo "The test failed :-(" + echo "$*" 1>&2 + echo "exit status was $status" + exit $status + } #end of fail() + +#Call this from anywhere to pass the test with a message +# usage: pass "reason why the test passed if applicable" +pass() + { echo "The test passed!!!" + echo "$*" 1>&2 + exit 0 + } #end of pass() + +#Call this to run the test with a file name +test() + { + ${TESTJAVA}${FILESEP}bin${FILESEP}appletviewer -Xnosecurity ${URL} > err 2>&1 & + APPLET_ID=$! + sleep 15 + kill -9 $APPLET_ID + + # these exceptions will be thrown if the test fails + cat err | grep "I/O exception while reading" + exception=$? + if [ $exception = "0" ]; + then fail "test failed for "${URL}", see err file and CRs #6193279,6329251,6376334" + fi + + cat err | grep "java.lang.ClassNotFoundException" + exception=$? + if [ $exception = "0" ]; + then fail "test failed for "${URL}", see err file and CRs #6193279,6329251,6376334" + fi + + # the applet will log the same message + cat err | grep "the appletviewer started" + started=$? + + echo $started | grep "2" + if [ $? = 0 ] ; + then fail "test failed for "${URL}": syntax errors or inaccessible files" + fi + + if [ $started = "0" ]; + then echo "the test passed for "${URL} + else fail "test failed for "${URL}": the appletviewer behaviour is unexpected: "$started", see err file" + fi + } + +# end of subroutines + + +# The beginning of the script proper + +# Checking for proper OS +OS=`uname -s` +case "$OS" in + SunOS ) + VAR="One value for Sun" + DEFAULT_JDK=/usr/local/java/jdk1.2.1/solaris + FILESEP="/" + ;; + + Linux ) + VAR="A different value for Linux" + DEFAULT_JDK=/usr/local/java/jdk1.4/linux-i386 + FILESEP="/" + ;; + + Windows_95 | Windows_98 | Windows_NT | Windows_ME | CYGWIN_NT-5.1) + VAR="A different value for Win32" + DEFAULT_JDK=/usr/local/java/jdk1.2.1/win32 + FILESEP="\\" + ;; + + # catch all other OSs + * ) + echo "Unrecognized system! $OS" + fail "Unrecognized system! $OS" + ;; +esac + +# 6438730: Only a minimal set of env variables are set for shell tests. +# To guarantee that env variable holds correct value we need to set it ourselves. +if [ -z "${PWD}" ] ; then + PWD=`pwd` +fi + +# check that some executable or other file you need is available, abort if not +# note that the name of the executable is in the fail string as well. +# this is how to check for presence of the compiler, etc. +#RESOURCE=`whence SomeProgramOrFileNeeded` +#if [ "${RESOURCE}" = "" ] ; +# then fail "Need SomeProgramOrFileNeeded to perform the test" ; +#fi + +# Want this test to run standalone as well as in the harness, so do the +# following to copy the test's directory into the harness's scratch directory +# and set all appropriate variables: + +if [ -z "${TESTJAVA}" ] ; then + # TESTJAVA is not set, so the test is running stand-alone. + # TESTJAVA holds the path to the root directory of the build of the JDK + # to be tested. That is, any java files run explicitly in this shell + # should use TESTJAVA in the path to the java interpreter. + # So, we'll set this to the JDK spec'd on the command line. If none + # is given on the command line, tell the user that and use a cheesy + # default. + # THIS IS THE JDK BEING TESTED. + if [ -n "$1" ] ; + then TESTJAVA=$1 + else echo "no JDK specified on command line so using default!" + TESTJAVA=$DEFAULT_JDK + fi + TESTSRC=. + TESTCLASSES=. + STANDALONE=1; +fi +echo "JDK under test is: $TESTJAVA" + +#Deal with .class files: +if [ -n "${STANDALONE}" ] ; + then + #if standalone, remind user to cd to dir. containing test before running it + echo "Just a reminder: cd to the dir containing this test when running it" + # then compile all .java files (if there are any) into .class files + if [ -a *.java ] ; + then echo "Reminder, this test should be in its own directory with all" + echo "supporting files it needs in the directory with it." + ${TESTJAVA}/bin/javac ./*.java ; + fi + # else in harness so copy all the class files from where jtreg put them + # over to the scratch directory this test is running in. + else cp ${TESTCLASSES}/*.class . ; +fi + +#if in test harness, then copy the entire directory that the test is in over +# to the scratch directory. This catches any support files needed by the test. +#if [ -z "${STANDALONE}" ] ; +# then cp ${TESTSRC}/* . +#fi + +#Just before executing anything, make sure it has executable permission! +chmod 777 ./* + +############### YOUR TEST CODE HERE!!!!!!! ############# + +#All files required for the test should be in the same directory with +# this file. If converting a standalone test to run with the harness, +# as long as all files are in the same directory and it returns 0 for +# pass, you should be able to cut and paste it into here and it will +# run with the test harness. + +# This is an example of running something -- test +# The stuff below catches the exit status of test then passes or fails +# this shell test as appropriate ( 0 status is considered a pass here ) + +# The test verifies that appletviewer correctly works with the different +# names of the files, including relative and absolute paths + +# 6619458: exclude left brace from the name of the files managed by the VCS +NAME='test.html' + +ENCODED='te%7Bst.html' +UNENCODED='te{st.html' + +# Copy needed files into the harness's scratch directory +# or create a copy with the required name if the test is +# running as stand-alone +cp ${TESTSRC}${FILESEP}${NAME} ${UNENCODED} + +# the encoded name, the path is absolute +URL="file:"${PWD}${FILESEP}${ENCODED} +test + +# the encoded name, the path is relative +URL="file:"${ENCODED} +test + +# the unencoded name, the path is absolute +URL="file:"${PWD}${FILESEP}${UNENCODED} +test + +# the unencoded name, the path is relative +URL="file:"${UNENCODED} +test + +# pick up our toys from the scratch directory +rm ${UNENCODED} diff --git a/jdk/test/java/awt/appletviewer/IOExceptionIfEncodedURLTest/test.html b/jdk/test/java/awt/appletviewer/IOExceptionIfEncodedURLTest/test.html new file mode 100644 index 00000000000..104905bc4ea --- /dev/null +++ b/jdk/test/java/awt/appletviewer/IOExceptionIfEncodedURLTest/test.html @@ -0,0 +1,21 @@ + + + +Started by shell script + + + +

IOExceptionIfEncodedURLTest
Bug ID: 6193279

+ +

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

+ + + + \ No newline at end of file From a602ec9fb2dbdd710f428de017a7759c99cceeff Mon Sep 17 00:00:00 2001 From: Dmitry Cherepanov Date: Thu, 3 Apr 2008 15:48:10 +0400 Subject: [PATCH 134/258] 6615015: Typo in javadoc for Component.getTreeLock() Fix for typo Reviewed-by: son --- jdk/src/share/classes/java/awt/Component.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jdk/src/share/classes/java/awt/Component.java b/jdk/src/share/classes/java/awt/Component.java index 005a282442a..1bbd4dcf45b 100644 --- a/jdk/src/share/classes/java/awt/Component.java +++ b/jdk/src/share/classes/java/awt/Component.java @@ -1005,7 +1005,7 @@ public abstract class Component implements ImageObserver, MenuContainer, /** * Gets this component's locking object (the object that owns the thread - * sychronization monitor) for AWT component-tree and layout + * synchronization monitor) for AWT component-tree and layout * operations. * @return this component's locking object */ From a61087c7628bf61405b90ff48eff3ef171f170d4 Mon Sep 17 00:00:00 2001 From: Peter Zhelezniakov Date: Thu, 3 Apr 2008 16:41:43 +0400 Subject: [PATCH 135/258] 4714674: JEditorPane.setPage(url) blocks AWT thread when HTTP protocol is used Both POST and GET can now be processed asynchronously; PageLoader refactored Reviewed-by: gsm --- .../classes/javax/swing/JEditorPane.java | 125 +++++------------- .../javax/swing/JEditorPane/bug4714674.java | 124 +++++++++++++++++ 2 files changed, 155 insertions(+), 94 deletions(-) create mode 100644 jdk/test/javax/swing/JEditorPane/bug4714674.java diff --git a/jdk/src/share/classes/javax/swing/JEditorPane.java b/jdk/src/share/classes/javax/swing/JEditorPane.java index 8395075295f..4cf18c009c3 100644 --- a/jdk/src/share/classes/javax/swing/JEditorPane.java +++ b/jdk/src/share/classes/javax/swing/JEditorPane.java @@ -429,9 +429,8 @@ public class JEditorPane extends JTextComponent { // different url or POST method, load the new content int p = getAsynchronousLoadPriority(getDocument()); - if ((postData == null) || (p < 0)) { - // Either we do not have POST data, or should submit the data - // synchronously. + if (p < 0) { + // open stream synchronously InputStream in = getStream(page); if (kit != null) { Document doc = initializeModel(kit, page); @@ -440,22 +439,13 @@ public class JEditorPane extends JTextComponent { // view notifications slowing it down (i.e. best synchronous // behavior) or set the model and start to feed it on a separate // thread (best asynchronous behavior). - synchronized(this) { - if (loading != null) { - // we are loading asynchronously, so we need to cancel - // the old stream. - loading.cancel(); - loading = null; - } - } p = getAsynchronousLoadPriority(doc); if (p >= 0) { // load asynchronously setDocument(doc); synchronized(this) { - loading = new PageStream(in); - Thread pl = new PageLoader(doc, loading, p, loaded, page); - pl.start(); + pageLoader = new PageLoader(doc, in, loaded, page); + pageLoader.execute(); } return; } @@ -464,11 +454,15 @@ public class JEditorPane extends JTextComponent { reloaded = true; } } else { - // We have POST data and should send it asynchronously. - // Send (and subsequentally read) data in separate thread. + // we may need to cancel background loading + if (pageLoader != null) { + pageLoader.cancel(true); + } + + // Do everything in a background thread. // Model initialization is deferred to that thread, too. - Thread pl = new PageLoader(null, null, p, loaded, page); - pl.start(); + pageLoader = new PageLoader(null, null, loaded, page); + pageLoader.execute(); return; } } @@ -604,44 +598,38 @@ public class JEditorPane extends JTextComponent { /** - * Thread to load a stream into the text document model. + * Loads a stream into the text document model. */ - class PageLoader extends Thread { + class PageLoader extends SwingWorker { /** * Construct an asynchronous page loader. */ - PageLoader(Document doc, InputStream in, int priority, URL old, - URL page) { - setPriority(priority); + PageLoader(Document doc, InputStream in, URL old, URL page) { this.in = in; this.old = old; this.page = page; this.doc = doc; } - boolean pageLoaded = false; - /** * Try to load the document, then scroll the view * to the reference (if specified). When done, fire * a page property change event. */ - public void run() { + protected URL doInBackground() { + boolean pageLoaded = false; try { if (in == null) { in = getStream(page); if (kit == null) { // We received document of unknown content type. - UIManager.getLookAndFeel().provideErrorFeedback( - JEditorPane.this); - return; - } - // Access to loading should be synchronized. - synchronized(JEditorPane.this) { - in = loading = new PageStream(in); + UIManager.getLookAndFeel(). + provideErrorFeedback(JEditorPane.this); + return old; } } + if (doc == null) { try { SwingUtilities.invokeAndWait(new Runnable() { @@ -653,11 +641,11 @@ public class JEditorPane extends JTextComponent { } catch (InvocationTargetException ex) { UIManager.getLookAndFeel().provideErrorFeedback( JEditorPane.this); - return; + return old; } catch (InterruptedException ex) { UIManager.getLookAndFeel().provideErrorFeedback( JEditorPane.this); - return; + return old; } } @@ -682,16 +670,14 @@ public class JEditorPane extends JTextComponent { } catch (IOException ioe) { UIManager.getLookAndFeel().provideErrorFeedback(JEditorPane.this); } finally { - synchronized(JEditorPane.this) { - loading = null; - } - SwingUtilities.invokeLater(new Runnable() { - public void run() { - if (pageLoaded) { - firePropertyChange("page", old, page); + if (pageLoaded) { + SwingUtilities.invokeLater(new Runnable() { + public void run() { + JEditorPane.this.firePropertyChange("page", old, page); } - } - }); + }); + } + return (pageLoaded ? page : old); } } @@ -718,51 +704,6 @@ public class JEditorPane extends JTextComponent { Document doc; } - static class PageStream extends FilterInputStream { - - boolean canceled; - - public PageStream(InputStream i) { - super(i); - canceled = false; - } - - /** - * Cancel the loading of the stream by throwing - * an IOException on the next request. - */ - public synchronized void cancel() { - canceled = true; - } - - protected synchronized void checkCanceled() throws IOException { - if (canceled) { - throw new IOException("page canceled"); - } - } - - public int read() throws IOException { - checkCanceled(); - return super.read(); - } - - public long skip(long n) throws IOException { - checkCanceled(); - return super.skip(n); - } - - public int available() throws IOException { - checkCanceled(); - return super.available(); - } - - public void reset() throws IOException { - checkCanceled(); - super.reset(); - } - - } - /** * Fetches a stream for the given URL, which is about to * be loaded by the setPage method. By @@ -1573,11 +1514,7 @@ public class JEditorPane extends JTextComponent { // --- variables --------------------------------------- - /** - * Stream currently loading asynchronously (potentially cancelable). - * Access to this variable should be synchronized. - */ - PageStream loading; + private SwingWorker pageLoader; /** * Current content binding of the editor. diff --git a/jdk/test/javax/swing/JEditorPane/bug4714674.java b/jdk/test/javax/swing/JEditorPane/bug4714674.java new file mode 100644 index 00000000000..a3426144330 --- /dev/null +++ b/jdk/test/javax/swing/JEditorPane/bug4714674.java @@ -0,0 +1,124 @@ +/* @test + @bug 4714674 + @summary Tests that JEditorPane opens HTTP connection asynchronously + @author Peter Zhelezniakov + @run main bug4714674 +*/ + +import javax.swing.*; + +import com.sun.net.httpserver.HttpExchange; +import com.sun.net.httpserver.HttpHandler; +import com.sun.net.httpserver.HttpServer; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.util.concurrent.Executors; + + +public class bug4714674 { + + public static void main(String[] args) throws Exception { + new bug4714674().test(); + } + + private void test() throws Exception { + final DeafServer server = new DeafServer(); + final String baseURL = "http://localhost:" + server.getPort() + "/"; + + SwingUtilities.invokeLater(new Runnable() { + public void run() { + try { + JEditorPane pane = new JEditorPane(); + ((javax.swing.text.AbstractDocument)pane.getDocument()). + setAsynchronousLoadPriority(1); + + // this will block EDT unless 4714674 is fixed + pane.setPage(baseURL); + } catch (IOException e) { + // should not happen + throw new Error(e); + } + } + }); + + // if 4714674 is fixed, this executes before connection times out + SwingUtilities.invokeLater(new Runnable() { + public void run() { + synchronized (server) { + server.wakeup = true; + server.notifyAll(); + } + pass(); + } + }); + + // wait, then check test status + try { + Thread.sleep(5000); + if (!passed()) { + throw new RuntimeException("Failed: EDT was blocked"); + } + } finally { + server.destroy(); + } + } + + private boolean passed = false; + + private synchronized boolean passed() { + return passed; + } + + private synchronized void pass() { + passed = true; + } +} + +/** + * A "deaf" HTTP server that does not respond to requests. + */ +class DeafServer { + HttpServer server; + boolean wakeup = false; + + /** + * Create and start the HTTP server. + */ + public DeafServer() throws IOException { + InetSocketAddress addr = new InetSocketAddress(0); + server = HttpServer.create(addr, 0); + HttpHandler handler = new DeafHandler(); + server.createContext("/", handler); + server.setExecutor(Executors.newCachedThreadPool()); + server.start(); + } + + /** + * Stop server without any delay. + */ + public void destroy() { + server.stop(0); + } + + /** + * Return actual server port number, useful for constructing request URIs. + */ + public int getPort() { + return server.getAddress().getPort(); + } + + + class DeafHandler implements HttpHandler { + public void handle(HttpExchange r) throws IOException { + synchronized (DeafServer.this) { + while (! wakeup) { + try { + DeafServer.this.wait(); + } catch (InterruptedException e) { + // just wait again + } + } + } + } + } +} From 89290f28174957b882ec0c02ae613856c376c06b Mon Sep 17 00:00:00 2001 From: Tom Rodriguez Date: Thu, 3 Apr 2008 10:20:44 -0700 Subject: [PATCH 136/258] 6619271: The -Xprintflags causes the VM to segv Add null checks Reviewed-by: jrose, kvn --- hotspot/src/share/vm/runtime/globals.cpp | 51 +++++++++++++----------- 1 file changed, 28 insertions(+), 23 deletions(-) diff --git a/hotspot/src/share/vm/runtime/globals.cpp b/hotspot/src/share/vm/runtime/globals.cpp index 139fe1c41f5..f70d0c08bd5 100644 --- a/hotspot/src/share/vm/runtime/globals.cpp +++ b/hotspot/src/share/vm/runtime/globals.cpp @@ -68,18 +68,20 @@ void Flag::print_on(outputStream* st) { if (is_uintx()) st->print("%-16lu", get_uintx()); if (is_ccstr()) { const char* cp = get_ccstr(); - const char* eol; - while ((eol = strchr(cp, '\n')) != NULL) { - char format_buffer[FORMAT_BUFFER_LEN]; - size_t llen = pointer_delta(eol, cp, sizeof(char)); - jio_snprintf(format_buffer, FORMAT_BUFFER_LEN, - "%%." SIZE_FORMAT "s", llen); - st->print(format_buffer, cp); - st->cr(); - cp = eol+1; - st->print("%5s %-35s += ", "", name); + if (cp != NULL) { + const char* eol; + while ((eol = strchr(cp, '\n')) != NULL) { + char format_buffer[FORMAT_BUFFER_LEN]; + size_t llen = pointer_delta(eol, cp, sizeof(char)); + jio_snprintf(format_buffer, FORMAT_BUFFER_LEN, + "%%." SIZE_FORMAT "s", llen); + st->print(format_buffer, cp); + st->cr(); + cp = eol+1; + st->print("%5s %-35s += ", "", name); + } + st->print("%-16s", cp); } - st->print("%-16s", cp); } st->print(" %s", kind); st->cr(); @@ -94,18 +96,21 @@ void Flag::print_as_flag(outputStream* st) { st->print("-XX:%s=" UINTX_FORMAT, name, get_uintx()); } else if (is_ccstr()) { st->print("-XX:%s=", name); - // Need to turn embedded '\n's back into separate arguments - // Not so efficient to print one character at a time, - // but the choice is to do the transformation to a buffer - // and print that. And this need not be efficient. - for (const char* cp = get_ccstr(); *cp != '\0'; cp += 1) { - switch (*cp) { - default: - st->print("%c", *cp); - break; - case '\n': - st->print(" -XX:%s=", name); - break; + const char* cp = get_ccstr(); + if (cp != NULL) { + // Need to turn embedded '\n's back into separate arguments + // Not so efficient to print one character at a time, + // but the choice is to do the transformation to a buffer + // and print that. And this need not be efficient. + for (; *cp != '\0'; cp += 1) { + switch (*cp) { + default: + st->print("%c", *cp); + break; + case '\n': + st->print(" -XX:%s=", name); + break; + } } } } else { From 3bc5120d53fd92a6ff1c9d4fc9d719b08547a560 Mon Sep 17 00:00:00 2001 From: Xiaobin Lu Date: Thu, 3 Apr 2008 12:21:06 -0700 Subject: [PATCH 137/258] 6671882: memory access after free in solaris/vm/os_solaris.cpp Corrected the wrong memory access problem and made some minor clean ups Reviewed-by: dholmes, jcoomes --- hotspot/src/os/solaris/vm/os_solaris.cpp | 55 ++++++++++-------------- 1 file changed, 23 insertions(+), 32 deletions(-) diff --git a/hotspot/src/os/solaris/vm/os_solaris.cpp b/hotspot/src/os/solaris/vm/os_solaris.cpp index 75ad158a9cd..f1051ed2acf 100644 --- a/hotspot/src/os/solaris/vm/os_solaris.cpp +++ b/hotspot/src/os/solaris/vm/os_solaris.cpp @@ -4391,61 +4391,52 @@ static address resolve_symbol(const char *name) { // threads. Calling thr_setprio is meaningless in this case. // bool isT2_libthread() { - int i, rslt; static prheader_t * lwpArray = NULL; static int lwpSize = 0; static int lwpFile = -1; lwpstatus_t * that; - int aslwpcount; char lwpName [128]; bool isT2 = false; #define ADR(x) ((uintptr_t)(x)) #define LWPINDEX(ary,ix) ((lwpstatus_t *)(((ary)->pr_entsize * (ix)) + (ADR((ary) + 1)))) - aslwpcount = 0; - lwpSize = 16*1024; - lwpArray = ( prheader_t *)NEW_C_HEAP_ARRAY (char, lwpSize); - lwpFile = open ("/proc/self/lstatus", O_RDONLY, 0); - if (lwpArray == NULL) { - if ( ThreadPriorityVerbose ) warning ("Couldn't allocate T2 Check array\n"); - return(isT2); - } + lwpFile = open("/proc/self/lstatus", O_RDONLY, 0); if (lwpFile < 0) { - if ( ThreadPriorityVerbose ) warning ("Couldn't open /proc/self/lstatus\n"); - return(isT2); + if (ThreadPriorityVerbose) warning ("Couldn't open /proc/self/lstatus\n"); + return false; } + lwpSize = 16*1024; for (;;) { lseek (lwpFile, 0, SEEK_SET); - rslt = read (lwpFile, lwpArray, lwpSize); - if ((lwpArray->pr_nent * lwpArray->pr_entsize) <= lwpSize) { + lwpArray = (prheader_t *)NEW_C_HEAP_ARRAY(char, lwpSize); + if (read(lwpFile, lwpArray, lwpSize) < 0) { + if (ThreadPriorityVerbose) warning("Error reading /proc/self/lstatus\n"); + break; + } + if ((lwpArray->pr_nent * lwpArray->pr_entsize) <= lwpSize) { + // We got a good snapshot - now iterate over the list. + int aslwpcount = 0; + for (int i = 0; i < lwpArray->pr_nent; i++ ) { + that = LWPINDEX(lwpArray,i); + if (that->pr_flags & PR_ASLWP) { + aslwpcount++; + } + } + if (aslwpcount == 0) isT2 = true; break; } - FREE_C_HEAP_ARRAY(char, lwpArray); lwpSize = lwpArray->pr_nent * lwpArray->pr_entsize; - lwpArray = ( prheader_t *)NEW_C_HEAP_ARRAY (char, lwpSize); - if (lwpArray == NULL) { - if ( ThreadPriorityVerbose ) warning ("Couldn't allocate T2 Check array\n"); - return(isT2); - } + FREE_C_HEAP_ARRAY(char, lwpArray); // retry. } - // We got a good snapshot - now iterate over the list. - for (i = 0; i < lwpArray->pr_nent; i++ ) { - that = LWPINDEX(lwpArray,i); - if (that->pr_flags & PR_ASLWP) { - aslwpcount++; - } - } - if ( aslwpcount == 0 ) isT2 = true; - FREE_C_HEAP_ARRAY(char, lwpArray); close (lwpFile); - if ( ThreadPriorityVerbose ) { - if ( isT2 ) tty->print_cr("We are running with a T2 libthread\n"); + if (ThreadPriorityVerbose) { + if (isT2) tty->print_cr("We are running with a T2 libthread\n"); else tty->print_cr("We are not running with a T2 libthread\n"); } - return (isT2); + return isT2; } From 21dbe47a30f57d24bf2dcbd4b6ffa1214b08ba42 Mon Sep 17 00:00:00 2001 From: Chuck Rasbold Date: Thu, 3 Apr 2008 13:33:13 -0700 Subject: [PATCH 138/258] 6624474: Server compiler generates unexpected LinkageError Fix load_signature_classes to tolerate LinkageErrors Reviewed-by: kvn, never --- hotspot/src/share/vm/oops/methodOop.cpp | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/hotspot/src/share/vm/oops/methodOop.cpp b/hotspot/src/share/vm/oops/methodOop.cpp index dfe9dee8560..db4dc773590 100644 --- a/hotspot/src/share/vm/oops/methodOop.cpp +++ b/hotspot/src/share/vm/oops/methodOop.cpp @@ -888,10 +888,11 @@ bool methodOopDesc::load_signature_classes(methodHandle m, TRAPS) { symbolHandle name (THREAD, sym); klassOop klass = SystemDictionary::resolve_or_null(name, class_loader, protection_domain, THREAD); - // We are loading classes eagerly. If a ClassNotFoundException was generated, - // be sure to ignore it. + // We are loading classes eagerly. If a ClassNotFoundException or + // a LinkageError was generated, be sure to ignore it. if (HAS_PENDING_EXCEPTION) { - if (PENDING_EXCEPTION->is_a(SystemDictionary::classNotFoundException_klass())) { + if (PENDING_EXCEPTION->is_a(SystemDictionary::classNotFoundException_klass()) || + PENDING_EXCEPTION->is_a(SystemDictionary::linkageError_klass())) { CLEAR_PENDING_EXCEPTION; } else { return false; From f62ccad5cdd2fb4d3adeb062596f209539166e12 Mon Sep 17 00:00:00 2001 From: Kumar Srinivasan Date: Thu, 3 Apr 2008 18:01:55 -0700 Subject: [PATCH 139/258] 6570242: Regression test failures with Javac on win32 Takes this test out of service until the reall bug is fixed Reviewed-by: jjg --- langtools/test/tools/javac/api/6431257/T6431257.java | 1 + 1 file changed, 1 insertion(+) diff --git a/langtools/test/tools/javac/api/6431257/T6431257.java b/langtools/test/tools/javac/api/6431257/T6431257.java index 4d751eb5190..3be14e2c027 100644 --- a/langtools/test/tools/javac/api/6431257/T6431257.java +++ b/langtools/test/tools/javac/api/6431257/T6431257.java @@ -27,6 +27,7 @@ * @summary JSR 199: Changes to JavaFileManager to support JSR 269 Filer API * @author Peter von der Ah\u00e9 * @library ../lib + * @ignore Need to fix this test when 6508981 is fixed. * @compile T6431257.java package-info.java * @run main T6431257 foo.bar.baz foo/bar/baz */ From 3093e354db2671d203d5134040a5cea39c47c52b Mon Sep 17 00:00:00 2001 From: Tom Rodriguez Date: Thu, 3 Apr 2008 21:26:03 -0700 Subject: [PATCH 140/258] 6646020: assert(in_bb(n),"must be in block") in -Xcomp mode Reviewed-by: kvn, rasbold --- hotspot/src/share/vm/opto/superword.cpp | 5 + hotspot/test/compiler/6646020/Tester.java | 886 ++++++++++++++++++++++ 2 files changed, 891 insertions(+) create mode 100644 hotspot/test/compiler/6646020/Tester.java diff --git a/hotspot/src/share/vm/opto/superword.cpp b/hotspot/src/share/vm/opto/superword.cpp index 625acd85efa..b9b8a98bb2d 100644 --- a/hotspot/src/share/vm/opto/superword.cpp +++ b/hotspot/src/share/vm/opto/superword.cpp @@ -65,6 +65,11 @@ void SuperWord::transform_loop(IdealLoopTree* lpt) { Node *cl_exit = cl->loopexit(); if (cl_exit->in(0) != lpt->_head) return; + // Make sure the are no extra control users of the loop backedge + if (cl->back_control()->outcnt() != 1) { + return; + } + // Check for pre-loop ending with CountedLoopEnd(Bool(Cmp(x,Opaque1(limit)))) CountedLoopEndNode* pre_end = get_pre_loop_end(cl); if (pre_end == NULL) return; diff --git a/hotspot/test/compiler/6646020/Tester.java b/hotspot/test/compiler/6646020/Tester.java new file mode 100644 index 00000000000..1035a7bd8eb --- /dev/null +++ b/hotspot/test/compiler/6646020/Tester.java @@ -0,0 +1,886 @@ +/* + * Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* + * @test + * @bug 6646020 + * @summary assert(in_bb(n),"must be in block") in -Xcomp mode + */ + +/* Complexity upper bound: 3361 ops */ + +class Tester_Class_0 { + static byte var_1; + + + public Tester_Class_0() + { + "".length(); + { + var_1 = (var_1 = (new byte[(byte)'D'])[(byte)2.40457E38F]); + var_1 = (var_1 = (byte)1.738443503665377E307); + var_1 = (var_1 = (byte)1237144669662298112L); + } + var_1 = "baldh".equalsIgnoreCase("") ? (var_1 = (byte)7.2932087E37F) : (byte)3909726578709910528L; + var_1 = (var_1 = (var_1 = (var_1 = (byte)7.223761846153971E307))); + var_1 = (var_1 = (var_1 = (var_1 = (var_1 = (byte)((short)7860452029249754112L + (byte)1.7374232546809952E308))))); + var_1 = (!true ? (var_1 = (byte)4359229782598970368L) : (short)(byte)1.7509836746850026E308) >= 'P' ? (var_1 = (byte)3.275114793095594E307) : (byte)(- ((byte)1.5595572E38F) / 8.2971296E37F); + byte var_9 = (true ? true : (false ? true : false)) ? (var_1 = (var_1 = (byte)9.928434E37F)) : (var_1 = (byte)9.785060633966518E307); + final byte var_10 = 53; + var_9 <<= (true | true) & (((var_10 == "".substring(2001075014).compareToIgnoreCase("rhbytggv") ? !true : ! !true) ? !false : false) ? !true & true : !false) ? var_10 : var_10; + var_9 <<= - (var_9 -= - ~6397182310329038848L >> (char)955837891 << (short)- - -8.4452034E37F >> + ~5485157895941338112L); + --var_9; + var_9 >>= 'V'; + var_9 -= (new char[var_10])[var_9]; + double var_11; + var_11 = (var_11 = (new int[var_9 = (var_9 %= 684423748)])[var_9]); + var_9 /= 'q'; + var_9 *= ~var_9 | (short)1.7667766368850557E308 - "w".trim().charAt(- (var_9 /= + (var_11 = 'q'))); + if (var_10 <= 605036859609030656L | !false & false) + { + var_9 >>>= false ^ false ? (new short[var_10])[var_10] : (short)1013619326108001280L; + } + else + { + var_11 = var_9; + } + var_9 -= 'X'; + var_9 *= 'E'; + { + var_9 ^= (new short[var_9])[var_9 >>>= 'c']; + } + var_11 = 4315867074042433536L; + double var_12 = 1.2183900219527627E308; + var_9 <<= (false ? !false : false) ? '\\' : 'D'; + } + + + + + private final long func_0() + { + float var_2 = 0F; + var_1 = (var_1 = (var_1 = (byte)((short)1.4106931056021857E308 % var_2))); + for (new String(); true & (! !true ^ !false | false) && var_2 < 1; var_1 = (var_1 = (var_1 = (var_1 = (byte)1183673628639185920L)))) + { + var_1 = true | false ? (var_1 = (byte)1.6263855E37F) : (byte)'O'; + var_2++; + "fui".toUpperCase(); + final int var_3 = (var_1 = (var_1 = (byte)'i')) + (byte)2008561384 / (byte)1.4413369179905006E308; + } + var_1 = (var_1 = false ^ false ? (byte)2.3850814E38F : (byte)4.42887E37F); + final float var_4 = 3.052265E38F; + var_1 = (var_1 = (var_1 = (var_1 = (var_1 = (byte)'o')))); + long var_5; + var_1 = (var_1 = (byte)((var_1 = (byte)1913212786) * (var_1 = (byte)var_2))); + var_5 = (short)3.2024069E38F * (short)(var_5 = 'Q'); + var_5 = (false ? true : false) ? (short)1098137179 : (byte)~695765814858203136L; + var_1 = (var_1 = true & false ^ true ? (byte)1662737306 : (byte)'r'); + { + (true ? "a" : "lymivj".toString()).codePointCount((short)3.032349E38F + (var_1 = (var_1 = (var_1 = (var_1 = (byte)1.3159799E37F)))), (byte)2.0898819853138264E307 & (new short[(byte)(short)var_2])[var_1 = (byte)(short)4.859332921376913E307]); + } + double var_6; + var_6 = 1359078277; + final float var_7 = 3.5952457E37F; + var_5 = ('u' | 9005660398910009344L) << 'j'; + int var_8; + var_5 = (!false || true & !false) && false ? (byte)1836342254 : (byte)1.4836203E38F; + var_1 = (var_1 = (var_1 = (var_1 = (byte)1.5824984701060493E308))); + var_1 = (var_1 = (var_1 = (byte)~ (var_1 = (var_1 = (var_1 = (byte)var_7))))); + return +9.067416E37F <= (true | true ^ false ? (var_1 = (byte)(short)1.5243446E38F) : (var_1 = (byte)1.6893049E37F)) ? (byte)~4408841475280588800L - (var_5 = (var_1 = (byte)2.1542209E38F)) : (var_8 = (short)var_4); + } + + protected final static double func_1(final char arg_0, final long arg_1) + { + var_1 = (short)8779631802405542912L << 'x' <= arg_0 ? (byte)+9.96859509852443E307 : (var_1 = (var_1 = (byte)(short)5.218454879223281E307)); + return 5.57437404144192E307; + } + + double func_2(byte arg_0, final boolean arg_1, Object arg_2) + { + arg_2 = arg_1 != arg_1 ? "wq" : "w"; + arg_2 = arg_2; + if (arg_1) + { + arg_2 = false & arg_1 ? "hasmp" : (arg_2 = arg_2); + } + else + { + arg_2 = "lcquv"; + } + arg_0 -= arg_1 ^ false ? (arg_0 |= (short)arg_0) : (~3462197988186869760L | 7274210797196514304L) % - - + +130998764279904256L; + arg_0 &= (true ? - - ~7861994999369861120L << 'l' : 'c') * 1246069704; + return (arg_1 ? 9.311174E37F : 1.7085558737202237E308) * 1168887722; + } + + public String toString() + { + String result = "[\n"; + result += "Tester_Class_0.var_1 = "; result += Tester.Printer.print(var_1); + result += ""; + result += "\n]"; + return result; + } +} + + +final class Tester_Class_1 extends Tester_Class_0 { + static Object var_13; + final static boolean var_14 = false | (false ? false : true); + Object var_15; + static byte var_16; + final long var_17 = (long)(-9.40561658911133E307 - (short)2.2016736E38F) ^ (char)1099667310; + static boolean var_18; + static float var_19; + final static byte var_20 = 123; + static byte var_21 = var_1 = (var_1 = var_20); + final static float var_22 = 1.5415572E38F; + + + public Tester_Class_1() + { + char[][] var_39; + boolean var_40 = false | !var_14; + if (var_14) + { + final String[] var_41 = (new String[var_21][var_20])[var_21 *= var_21]; + var_15 = (new Tester_Class_0[var_20])[var_20]; + --var_21; + int var_42; + } + else + { + var_19 = (short)325110146; + } + var_40 &= true; + var_13 = (((new Tester_Class_1[var_21 |= (new char[var_20])[var_21]])[var_21]).var_15 = (new String[var_21][var_20][var_20])[var_21 >>= (byte)(int)var_22]); + var_15 = "m"; + } + + + + + + protected final static Tester_Class_0 func_0(final char arg_0, boolean arg_1) + { + final short var_23 = false ? (short)2.2956268E38F : var_20; + { + ((new Tester_Class_1[var_21])[var_20]).var_15 = ((new Tester_Class_0[var_20][var_21])[var_21])[var_20]; + } + var_19 = var_23; + { + var_21++; + --var_21; + var_13 = (false ? arg_1 : arg_1) ? "" : "aianteahl"; + arg_1 ^= ! (var_14 ? var_14 : !var_14); + } + (arg_1 ? "rq" : "certd").trim(); + arg_1 ^= 's' < var_22; + var_19 = 'T'; + var_19 = var_14 ? --var_21 : var_20; + var_19 = (var_21 >>>= ~ -1559436447128426496L >> 88912720393932800L) | (new char[var_20][var_21])[var_21][var_20]; + short var_24 = 7601; + if (arg_1) + { + var_13 = (new Tester_Class_0[var_20])[var_21]; + } + else + { + var_19 = var_23; + } + var_19 = var_24; + var_19 = 174274929356416000L; + return arg_1 ? (Tester_Class_0)(new Object[var_20])[var_21 >>>= - ((byte)6471979169965446144L)] : (new Tester_Class_0[var_21])[var_20]; + } + + private static int func_1(final Object arg_0, final boolean arg_1) + { + var_19 = 'N'; + var_13 = "ftspm".toUpperCase(); + var_18 = arg_1 ? !arg_1 : var_14; + var_19 = var_21 % 'j'; + { + var_13 = new short[var_21 >>= 8019540572802872320L]; + } + final Tester_Class_0 var_25 = arg_1 ? ((short)1.3614569631193786E308 >= (short)var_20 ? func_0('O', true) : (Tester_Class_0)arg_0) : func_0('e', false); + "cltpxrg".offsetByCodePoints((new short[var_20])[(byte)'F'] & var_20, 942627356); + final Object var_26 = ((new Tester_Class_1[var_21])[var_20]).var_15 = arg_0; + { + var_21 |= 'H'; + } + var_19 = 4705089801895780352L; + var_19 = (var_18 = arg_1 & false) ? var_20 : (! (~var_21 > var_22) ? (new short[var_20])[var_21] : (short)3904907750551380992L); + var_18 = false; + { + var_18 = "aoy".startsWith("ia", 18060804); + if (true) + { + final short var_27 = 4832; + } + else + { + var_18 = (var_18 = arg_1) ? !false : !var_14; + } + var_18 = (var_18 = var_14); + var_19 = 'L'; + } + func_0((false ? ! ((var_21 -= 4.670301365216022E307) > 1.1839209E37F) : (var_18 = false)) ? 's' : 'R', 'Z' > - ((long)var_21) << 2585724390819764224L & var_25.func_2(var_21, false, var_13 = var_25) != 4918861136400833536L); + double var_28 = 0; + var_21 %= -var_28; + for (byte var_29 = 91; arg_1 && (var_28 < 1 && false); var_19 = var_20) + { + var_19 = (var_18 = arg_1) & (var_18 = false) ? 'm' : '['; + var_28++; + var_18 = var_14; + var_21 += (short)1363703973; + } + var_19 = (var_19 = var_22); + var_18 = (var_18 = false | false ? 1743087391 <= (var_21 >>= 8790741242417599488L) : !arg_1); + var_18 = true | true; + --var_21; + var_18 = !var_14 & false; + "mt".indexOf(var_14 ? new String("fpu") : "awivb", (var_14 ? !true : (var_18 = var_14)) ? + ++var_21 : ~var_20); + return (short)(new float[var_21--])[var_21] & ((var_18 = false) ? (var_21 *= 'N') : var_20 + (short)1680927063794178048L) & 1839004800; + } + + protected static int func_2(Tester_Class_0[][] arg_0) + { + ((new Tester_Class_1[var_20][var_21])[var_20][var_20]).var_15 = ((new int[var_21][var_21][(byte)var_22])[var_21 <<= var_20])[var_20]; + ((new Tester_Class_1[var_20])[var_20]).var_15 = "d"; + int var_30 = 0; + "joxjgpywp".lastIndexOf(1834367264 >> var_21, (byte)7.572305E37F >>> (false ? (short)2.3909862E38F : + - +3939434849912855552L)); + while (var_14 | false ^ var_14 && (var_30 < 1 && true)) + { + var_1 = var_20; + var_30++; + var_13 = new float[var_21][--var_21]; + boolean var_31; + } + var_19 = ((new Tester_Class_1[var_21])[var_20]).var_17 <= (~2158227803735181312L & 6001748808824762368L) ? (short)var_20 : var_20; + var_18 = (var_18 = true); + return (byte)(new short[var_20])[var_20] >>> ((new char[var_21][var_21])[var_21 |= 6074708801143703552L])[var_20]; + } + + private final String func_3(boolean arg_0, short arg_1, short arg_2) + { + var_13 = (Tester_Class_0)((arg_0 ^= arg_0) ? (var_13 = (var_15 = (var_15 = "grfphyrs"))) : (var_13 = new Object[var_21 *= ']'])); + if (true & ! (arg_0 ^= !arg_0 | true)) + { + boolean var_32 = true; + var_19 = --arg_1; + arg_2 <<= var_21; + } + else + { + arg_0 |= false; + } + var_21 >>>= arg_1; + final float var_33 = 2.5500976E38F; + return ""; + } + + private static String func_4(final double arg_0, final Object arg_1, final short[] arg_2, final char arg_3) + { + float var_34; + var_21++; + ((new Tester_Class_1[var_20])[var_20]).var_15 = false ? arg_1 : arg_1; + var_13 = arg_1; + var_19 = var_22; + var_13 = new long[var_21 /= 1038797776 + var_21][--var_21]; + ++var_21; + var_18 = false && false; + var_21--; + "".lastIndexOf("kjro"); + final int var_35 = (var_21 <<= var_21--) * var_21--; + if ("kohilkx".startsWith("gy", var_35)) + { + var_34 = 2.0849673E37F; + } + else + { + double var_36 = arg_0; + } + var_34 = (var_21 /= var_20); + { + func_2(new Tester_Class_0[var_20][var_21]); + var_34 = var_20 * (- ~5805881602002385920L / arg_3) << (short)~8041668398152312832L; + var_13 = (var_13 = "qfwbfdf"); + } + ((new Tester_Class_1[var_20])[var_21 += var_20]).var_15 = false ? func_0(arg_3, var_14) : func_0('J', var_18 = var_14); + var_18 = (var_18 = var_14) & var_14; + if ((new boolean[var_21])[var_21 >>= 121380821]) + { + var_34 = 1382979413; + } + else + { + var_34 = (var_20 & var_20) + (true ? 'I' : arg_3); + } + byte var_37; + ((new Tester_Class_1[var_20][var_21])[var_14 ^ var_14 | !var_14 ? var_20 : var_20][var_21 ^= (short)1692053070 & + ~7232298887878750208L - 1512699919]).var_15 = arg_2; + byte var_38 = 1; + var_38 -= arg_0; + var_34 = arg_3; + return var_14 ? "" : "xgkr".toUpperCase(); + } + + public String toString() + { + String result = "[\n"; + result += "Tester_Class_1.var_1 = "; result += Tester.Printer.print(var_1); + result += "\n"; + result += "Tester_Class_1.var_16 = "; result += Tester.Printer.print(var_16); + result += "\n"; + result += "Tester_Class_1.var_20 = "; result += Tester.Printer.print(var_20); + result += "\n"; + result += "Tester_Class_1.var_21 = "; result += Tester.Printer.print(var_21); + result += "\n"; + result += "Tester_Class_1.var_14 = "; result += Tester.Printer.print(var_14); + result += "\n"; + result += "Tester_Class_1.var_18 = "; result += Tester.Printer.print(var_18); + result += "\n"; + result += "Tester_Class_1.var_17 = "; result += Tester.Printer.print(var_17); + result += "\n"; + result += "Tester_Class_1.var_19 = "; result += Tester.Printer.print(var_19); + result += "\n"; + result += "Tester_Class_1.var_22 = "; result += Tester.Printer.print(var_22); + result += "\n"; + result += "Tester_Class_1.var_13 = "; result += Tester.Printer.print(var_13); + result += "\n"; + result += "Tester_Class_1.var_15 = "; result += Tester.Printer.print(var_15); + result += ""; + result += "\n]"; + return result; + } +} + + +class Tester_Class_2 extends Tester_Class_0 { + final int var_43 = 1600723343; + static long var_44 = ~1297640037857117184L; + static String var_45 = "ejaglds"; + double var_46; + static float var_47 = 7.9423827E37F; + static Tester_Class_1[][] var_48; + + + public Tester_Class_2() + { + var_45 = (var_45 = "nkulkweqt"); + var_47 %= (new char[Tester_Class_1.var_21 >>= (short)Tester_Class_1.var_20])[Tester_Class_1.var_20]; + { + Tester_Class_1.var_18 = Tester_Class_1.var_14; + } + var_47 %= 1.559461406041646E308; + var_44 -= Tester_Class_1.var_21++ & ((new Tester_Class_1[Tester_Class_1.var_20])[Tester_Class_1.var_20]).var_17; + var_44 *= false ? (short)Tester_Class_1.var_20 : (short)var_47; + Tester_Class_1.var_13 = (new Tester_Class_1().var_15 = new char[Tester_Class_1.var_20]); + var_46 = 'i'; + double var_49 = var_46 = false ? (var_47 *= (var_46 = var_43)) : Tester_Class_1.var_20; + var_49 += 'k'; + } + + + + + public String toString() + { + String result = "[\n"; + result += "Tester_Class_2.var_43 = "; result += Tester.Printer.print(var_43); + result += "\n"; + result += "Tester_Class_2.var_48 = "; result += Tester.Printer.print(var_48); + result += "\n"; + result += "Tester_Class_2.var_44 = "; result += Tester.Printer.print(var_44); + result += "\n"; + result += "Tester_Class_2.var_46 = "; result += Tester.Printer.print(var_46); + result += "\n"; + result += "Tester_Class_2.var_47 = "; result += Tester.Printer.print(var_47); + result += "\n"; + result += "Tester_Class_2.var_1 = "; result += Tester.Printer.print(var_1); + result += "\n"; + result += "Tester_Class_2.var_45 = "; result += Tester.Printer.print(var_45); + result += ""; + result += "\n]"; + return result; + } +} + + +class Tester_Class_3 extends Tester_Class_0 { + byte var_50; + int var_51; + static double var_52; + static boolean var_53 = true; + long var_54; + static short var_55; + short var_56; + + + public Tester_Class_3() + { + var_53 |= false; + (Tester_Class_2.var_45 = "gpbcgq").replaceAll("m".concat(Tester_Class_2.var_45 = "q"), Tester_Class_2.var_45).indexOf(Tester_Class_2.var_45 = "d"); + Tester_Class_2.var_45 = Tester_Class_2.var_45; + double var_68 = 0; + Tester_Class_1.var_19 = (var_55 = Tester_Class_1.var_20); + do + { + var_53 ^= 'T' > Tester_Class_1.var_21-- & (var_53 |= Tester_Class_1.var_14); + Tester_Class_2.var_44 >>= (char)3.928497616986412E307; + var_68++; + new Tester_Class_2().func_2(Tester_Class_1.var_20, !var_53 & Tester_Class_1.var_14, Tester_Class_1.var_13 = (Tester_Class_2.var_45 = Tester_Class_2.var_45)); + } while ((((var_56 = (short)1161292485) != 'M' ? var_53 : Tester_Class_1.var_14) ? Tester_Class_1.var_14 ^ true : var_53) && var_68 < 1); + Tester_Class_2.var_45 = Tester_Class_2.var_45; + ((Tester_Class_1)(Tester_Class_1.var_13 = new Tester_Class_2())).var_15 = Tester_Class_2.var_45; + var_55 = func_1() | ((Tester_Class_1.var_18 = var_53) | (var_53 |= Tester_Class_1.var_14) | Tester_Class_1.var_14 | !Tester_Class_1.var_14) || false ? (short)Tester_Class_2.var_44 : (var_56 = (var_56 = (short)'[')); + var_52 = (var_51 = (var_55 = Tester_Class_1.var_20)); + double var_69 = 0; + Tester_Class_2.var_44 |= (Tester_Class_1.var_14 ? (Tester_Class_2)(Tester_Class_1.var_13 = (Tester_Class_2)(Tester_Class_1.var_13 = Tester_Class_2.var_45)) : (Tester_Class_2)(Tester_Class_0)(Tester_Class_1.var_13 = Tester_Class_2.var_45)).var_43; + do + { + var_51 = 495861255; + var_69++; + } while (var_69 < 3); + Tester_Class_2.var_47 -= Tester_Class_1.var_20; + Tester_Class_2.var_47 %= '['; + } + + + + + static Object func_0(final Tester_Class_0 arg_0, String arg_1, final float arg_2, final long arg_3) + { + (!var_53 | (var_53 &= var_53) ^ false ? new Tester_Class_1() : (Tester_Class_1)(new Tester_Class_0[Tester_Class_1.var_21])[Tester_Class_1.var_21]).var_15 = Tester_Class_1.var_14 ? new Tester_Class_1() : new Tester_Class_1(); + Tester_Class_2.var_47 /= !var_53 || var_53 ? (short)(((Tester_Class_2)arg_0).var_46 = (new char[Tester_Class_1.var_21][Tester_Class_1.var_21])[Tester_Class_1.var_20][Tester_Class_1.var_20]) : Tester_Class_1.var_21; + return (new Object[Tester_Class_1.var_21])[Tester_Class_1.var_21]; + } + + boolean func_1() + { + { + Tester_Class_1.var_21 >>= (var_56 = (Tester_Class_1.var_21 |= (Tester_Class_1.var_21 -= Tester_Class_1.var_20))); + Tester_Class_2.var_45 = "w"; + var_51 = Tester_Class_1.var_21; + Object var_57; + ((Tester_Class_2)(Tester_Class_0)((new Object[Tester_Class_1.var_21][Tester_Class_1.var_21])[Tester_Class_1.var_20])[Tester_Class_1.var_20]).var_46 = (var_52 = 1.3957085765622284E308); + } + Tester_Class_1.var_21 &= (var_55 = (byte)(Tester_Class_1.var_14 ? -Tester_Class_1.var_20 : 4290961666344782848L)); + Tester_Class_2.var_45 = Tester_Class_2.var_45; + var_51 = (var_53 ^= ((var_53 &= Tester_Class_1.var_14) ? 'J' : 'M') > (var_56 = Tester_Class_1.var_21)) && (var_53 = Tester_Class_1.var_14) ? (Tester_Class_1.var_21 &= ~Tester_Class_1.var_20) : Tester_Class_1.var_20; + { + final Tester_Class_1 var_58 = (Tester_Class_1)(Tester_Class_0)(Tester_Class_1.var_13 = (new Object[Tester_Class_1.var_21])[Tester_Class_1.var_20]); + Object var_59; + Tester_Class_1.var_21 |= 'X'; + var_53 ^= Tester_Class_1.var_14; + } + int var_60 = 0; + var_53 |= var_53; + for (char var_61 = 'i'; (Tester_Class_1.var_14 ? false : Tester_Class_1.var_14) | (true | Tester_Class_1.var_14) && var_60 < 1; var_53 &= !Tester_Class_1.var_14) + { + var_51 = var_61; + var_60++; + var_61 &= (new short[Tester_Class_1.var_20][Tester_Class_1.var_20])[Tester_Class_1.var_20][Tester_Class_1.var_21]; + Tester_Class_2.var_45 = "vsuy"; + } + Tester_Class_2 var_62 = ((var_53 &= Tester_Class_1.var_14 | Tester_Class_1.var_14 || Tester_Class_1.var_14) ? Tester_Class_1.var_14 : "hgwne".startsWith("etyhd", var_60)) ? (var_53 ? (Tester_Class_2)(Tester_Class_1.var_13 = "uyiaxtqc") : (Tester_Class_2)(Tester_Class_1.var_13 = Tester_Class_2.var_45)) : new Tester_Class_2(); + var_62 = var_62; + float var_63; + Object var_64; + Tester_Class_2.var_44 <<= 'v'; + String var_65; + { + var_51 = Tester_Class_1.var_21; + } + var_55 = true ? (var_56 = Tester_Class_1.var_20) : (var_55 = Tester_Class_1.var_20); + var_56 = Tester_Class_1.var_21; + Tester_Class_1.var_21 |= var_60; + Object var_66; + Tester_Class_2 var_67; + return true & Tester_Class_1.var_14 ^ (false ? var_53 : var_53); + } + + public String toString() + { + String result = "[\n"; + result += "Tester_Class_3.var_51 = "; result += Tester.Printer.print(var_51); + result += "\n"; + result += "Tester_Class_3.var_54 = "; result += Tester.Printer.print(var_54); + result += "\n"; + result += "Tester_Class_3.var_52 = "; result += Tester.Printer.print(var_52); + result += "\n"; + result += "Tester_Class_3.var_55 = "; result += Tester.Printer.print(var_55); + result += "\n"; + result += "Tester_Class_3.var_56 = "; result += Tester.Printer.print(var_56); + result += "\n"; + result += "Tester_Class_3.var_1 = "; result += Tester.Printer.print(var_1); + result += "\n"; + result += "Tester_Class_3.var_50 = "; result += Tester.Printer.print(var_50); + result += "\n"; + result += "Tester_Class_3.var_53 = "; result += Tester.Printer.print(var_53); + result += ""; + result += "\n]"; + return result; + } +} + +public class Tester { + final long var_70 = Tester_Class_2.var_44; + int var_71; + static double var_72; + static short var_73 = (Tester_Class_3.var_53 &= (Tester_Class_3.var_53 ^= Tester_Class_3.var_53)) ? (short)(byte)(Tester_Class_3.var_55 = Tester_Class_1.var_20) : (Tester_Class_3.var_55 = Tester_Class_1.var_20); + final static short var_74 = (Tester_Class_3.var_53 &= Tester_Class_3.var_53) ? (Tester_Class_3.var_53 ? var_73 : var_73++) : (var_73 *= (Tester_Class_1.var_21 |= var_73)); + float var_75; + + + protected final Tester_Class_2 func_0() + { + Tester_Class_1.var_21 ^= ~Tester_Class_1.var_21; + if (false) + { + ((Tester_Class_3)(new Object[Tester_Class_1.var_21])[Tester_Class_1.var_21 -= + + (Tester_Class_2.var_44 >>>= Tester_Class_1.var_21)]).var_50 = (Tester_Class_1.var_21 &= (var_71 = 554295231)); + } + else + { + Tester_Class_2.var_47 += 'H'; + } + final Tester_Class_0 var_76 = ((new Tester_Class_0[Tester_Class_1.var_20][Tester_Class_1.var_21])[Tester_Class_1.var_20])[Tester_Class_1.var_20]; + (Tester_Class_1.var_14 ? (Tester_Class_2)var_76 : (Tester_Class_2)var_76).var_46 = (var_73 %= var_74 / (((new Tester_Class_2[Tester_Class_1.var_20])[Tester_Class_1.var_21 |= Tester_Class_1.var_20]).var_46 = Tester_Class_1.var_22)); + var_73 |= ((Tester_Class_2)(Tester_Class_1.var_13 = var_76)).var_43 | Tester_Class_1.var_20; + return new Tester_Class_2(); + } + + private static Tester_Class_3 func_1(byte arg_0, Tester_Class_1 arg_1, Tester_Class_1 arg_2, final int arg_3) + { + arg_0 <<= '`'; + return false ? (Tester_Class_3)(Tester_Class_0)(arg_1.var_15 = (arg_1 = arg_2)) : (Tester_Class_3)((new Tester_Class_0[Tester_Class_1.var_20][arg_0])[Tester_Class_1.var_20])[Tester_Class_1.var_20]; + } + + public static String execute() + { + try { + Tester t = new Tester(); + try { t.test(); } + catch(Throwable e) { } + try { return t.toString(); } + catch (Throwable e) { return "Error during result conversion to String"; } + } catch (Throwable e) { return "Error during test execution"; } + } + + public static void main(String[] args) + { + for (int i = 0; i < 20000; i++) { + Tester t = new Tester(); + try { t.test(); } + catch(Throwable e) { } + if (t.var_71 != 0 || + t.var_70 != -1297640037857117185L || + t.var_72 != 0.0 || + t.var_75 != 0.0 || + t.var_73 != -1 || + t.var_74 != 15129) { + throw new InternalError("wrong answer"); + } + } + } + + private void test() + { + long var_77 = 0L; + var_73 /= (Tester_Class_2.var_47 = 'D' | 'Q'); + Tester_Class_2.var_47 *= 't'; + while (var_77 < 36) + { + var_73 += Tester_Class_1.var_22; + Tester_Class_2.var_47 += Tester_Class_1.var_20; + var_77++; + Tester_Class_2.var_45 = ""; + Tester_Class_2.var_45 = (Tester_Class_2.var_45 = Tester_Class_2.var_45); + } + if (Tester_Class_3.var_53 |= false) + { + int var_78 = 0; + (false ? "idipdjrln" : "l").startsWith(Tester_Class_2.var_45); + while ((Tester_Class_3.var_53 |= (Tester_Class_3.var_53 &= ! (Tester_Class_1.var_18 = true)) | Tester_Class_3.var_53) && (var_78 < 15 && (Tester_Class_3.var_53 &= Tester_Class_1.var_14))) + { + Tester_Class_2.var_44 <<= 'b'; + var_78++; + var_72 = var_74; + var_71 = (char)6792782617594333184L; + } + float var_79 = Tester_Class_2.var_47 /= 1.5148047552641134E308; + ((new boolean[Tester_Class_1.var_20])[Tester_Class_1.var_21 <= (Tester_Class_1.var_21 -= 9.675021723726166E307) / - + (var_72 = 4.3844763012510596E307) ? (byte)(Tester_Class_2.var_44 += ~Tester_Class_1.var_21) : (Tester_Class_1.var_21 += 1.7430965313164616E308)] ? (Tester_Class_2)(new Tester_Class_1().var_15 = func_0()) : new Tester_Class_2()).var_46 = (var_72 = (Tester_Class_1.var_21 *= 'j')); + Tester_Class_1.var_13 = (new Tester_Class_3[Tester_Class_1.var_21 >>>= var_78][Tester_Class_1.var_21])[Tester_Class_1.var_21][Tester_Class_1.var_20]; + } + else + { + long var_80 = 0L; + ((Tester_Class_2)(Tester_Class_1.var_13 = new long[Tester_Class_1.var_21])).var_46 = 'r'; + do + { + final float var_81 = 7.3633934E37F; + var_80++; + var_73 ^= Tester_Class_2.var_44; + } while (Tester_Class_3.var_53 && var_80 < 4); + Tester_Class_1.var_18 = Tester_Class_2.var_47 >= var_73; + Tester_Class_2.var_45 = "xvodcylp"; + Tester_Class_2.var_45.codePointCount("indreb".charAt(+(new byte[Tester_Class_1.var_20][Tester_Class_1.var_20])[Tester_Class_1.var_21][Tester_Class_1.var_21]) * ~ (Tester_Class_1.var_21 %= (var_71 = --var_73)), ((Tester_Class_3.var_53 ^= Tester_Class_2.var_45.equalsIgnoreCase("rkxwa")) || Tester_Class_2.var_47 <= (Tester_Class_2.var_47 %= -var_80) ? (Tester_Class_1.var_21 ^= var_70) : var_73) & (var_71 = 'k')); + Tester_Class_1.var_13 = ((new long[Tester_Class_1.var_21][Tester_Class_1.var_20][Tester_Class_1.var_21])[Tester_Class_1.var_21])[Tester_Class_1.var_21]; + } + var_73 <<= (Tester_Class_1.var_18 = false) ? 't' : (false ? 'E' : 'u'); + var_73++; + int var_82 = 0; + Tester_Class_1.var_13 = func_1(Tester_Class_1.var_20, new Tester_Class_1(), (new Tester_Class_1[Tester_Class_1.var_21])[Tester_Class_1.var_21], 'M' & var_74); + "gdrlrsubb".substring(12438522, var_82); + Tester_Class_2.var_44 |= (((new Tester_Class_3[Tester_Class_1.var_21][Tester_Class_1.var_21])[Tester_Class_1.var_21 >>= 7993744087962264576L][Tester_Class_1.var_21]).var_51 = Tester_Class_3.var_53 ? 'B' : '['); + final long var_83 = ~ (4544638910183665664L << (((Tester_Class_3)((new Tester_Class_0[Tester_Class_1.var_20][Tester_Class_1.var_21])[Tester_Class_1.var_21])[Tester_Class_1.var_21]).var_56 = (Tester_Class_3.var_53 &= Tester_Class_3.var_53) ? Tester_Class_1.var_21 : Tester_Class_1.var_20)); + Tester_Class_2.var_45 = Tester_Class_2.var_45; + while (var_82 < 2 && Tester_Class_3.var_53 & (Tester_Class_3.var_53 ^= !false)) + { + (Tester_Class_3.var_53 ? "xqeisnyf" : (Tester_Class_2.var_45 = (Tester_Class_2.var_45 = (Tester_Class_2.var_45 = Tester_Class_2.var_45)))).concat(Tester_Class_2.var_45 = "i"); + var_82++; + boolean var_84 = false; + Tester_Class_2.var_45 = Tester_Class_2.var_45; + } + var_71 = ~Tester_Class_2.var_44 != Tester_Class_2.var_44-- ? (var_73 = var_73) : (var_73 >>>= var_73); + char var_85; + Tester_Class_3.var_53 |= (Tester_Class_3.var_53 ^= true); + int var_86 = 0; + Tester_Class_1.var_21 %= (var_73 | (Tester_Class_1.var_21 *= 9.831691E37F)) * (Tester_Class_1.var_21 += 6784278051481715712L); + while (Tester_Class_3.var_53 && (var_86 < 24 && ((((Tester_Class_3.var_53 ^= true) ? Tester_Class_3.var_53 : Tester_Class_1.var_14) ? !Tester_Class_3.var_53 : Tester_Class_3.var_53) ? (Tester_Class_1.var_18 = Tester_Class_3.var_53) : Tester_Class_1.var_14 || true))) + { + final byte var_87 = (byte)((false & true ? Tester_Class_1.var_20 : 257407175) & 4242055901066916864L * (var_73 *= 1621204618) / ((((Tester_Class_1)(new Object[(byte)4.925362697409246E307])[Tester_Class_1.var_21]).var_17 ^ (var_71 = var_86)) & 1859382584)); + var_86++; + Tester_Class_2.var_45 = (Tester_Class_2.var_45 = (Tester_Class_2.var_45 = "arceo")); + float var_88; + } + "a".lastIndexOf(var_71 = Tester_Class_3.var_53 ^ false ? (var_71 = 1058420888) : Tester_Class_1.var_20); + int var_89 = 0; + { + var_71 = 661164411; + } + boolean var_90; + --var_73; + Tester_Class_2.var_45.concat(Tester_Class_2.var_45); + { + var_85 = (Tester_Class_3.var_53 ? Tester_Class_3.var_53 : Tester_Class_3.var_53) ? 'R' : '['; + } + ((new Tester_Class_2[Tester_Class_1.var_21][Tester_Class_1.var_21])[Tester_Class_1.var_20][Tester_Class_1.var_20]).var_46 = Tester_Class_1.var_20; + final float var_91 = ((new Tester_Class_0[Tester_Class_1.var_21][Tester_Class_1.var_21])[Tester_Class_1.var_20][Tester_Class_1.var_21 -= Tester_Class_1.var_21]).equals(((new Tester_Class_1[Tester_Class_1.var_20])[Tester_Class_1.var_21]).var_15 = (Tester_Class_2.var_45 = Tester_Class_2.var_45)) ? (var_71 = Tester_Class_1.var_20) : 2.2259766E38F + Tester_Class_2.var_44; + Tester_Class_2.var_47 *= ((Tester_Class_2)(Tester_Class_0)(Tester_Class_1.var_13 = Tester_Class_2.var_45)).var_43; + Tester_Class_2.var_45 = Tester_Class_2.var_45; + Tester_Class_3.var_53 &= Tester_Class_1.var_14; + while (Tester_Class_1.var_20 >= ++Tester_Class_1.var_21 && var_89 < 2) + { + Tester_Class_1.var_13 = (Tester_Class_3)(new Tester_Class_0[Tester_Class_1.var_21])[Tester_Class_1.var_21]; + var_89++; + if (true) + { + Tester_Class_3.var_53 |= true; + break; + } + else + { + Tester_Class_2 var_92; + } + ((Tester_Class_3)((Tester_Class_3.var_53 |= Tester_Class_3.var_53) ? (new Tester_Class_1().var_15 = (Tester_Class_0)(Tester_Class_1.var_13 = new boolean[Tester_Class_1.var_20][Tester_Class_1.var_21])) : new Tester_Class_0[Tester_Class_1.var_21][Tester_Class_1.var_21])).var_54 = (Tester_Class_1.var_21 = (Tester_Class_1.var_21 /= (Tester_Class_2.var_44 |= (int)(Tester_Class_1.var_21 >>>= var_82)))); + ((Tester_Class_3)(Tester_Class_1.var_13 = (new Tester_Class_1().var_15 = new Tester_Class_1()))).var_51 = Tester_Class_1.var_20; + final char var_93 = 'u'; + ((Tester_Class_2)(new Tester_Class_1().var_15 = (Tester_Class_2.var_45 = Tester_Class_2.var_45))).var_46 = var_93; + Tester_Class_2.var_45.toUpperCase(); + Tester_Class_2.var_45 = "mhk"; + (true | false ? new Tester_Class_1() : (new Tester_Class_1[Tester_Class_1.var_20])[Tester_Class_1.var_20]).var_15 = (Tester_Class_1)(((new Tester_Class_1[Tester_Class_1.var_21 |= Tester_Class_1.var_20][Tester_Class_1.var_21])[Tester_Class_1.var_21][Tester_Class_1.var_21]).var_15 = (Tester_Class_1.var_13 = (Tester_Class_1)(Tester_Class_1.var_13 = (Tester_Class_2.var_45 = "ofkbg")))); + } + float var_94 = 0F; + Tester_Class_2.var_44 |= (var_73 >>>= (var_85 = (var_85 = 'j'))); + Tester_Class_3.var_52 = 1835242863964218368L; + do + { + int var_95 = 1361237611; + var_94++; + Tester_Class_3.var_53 ^= (Tester_Class_3.var_53 |= Tester_Class_1.var_14); + } while (var_94 < 16); + { + var_73 = var_73--; + Tester_Class_2.var_45 = (Tester_Class_1.var_14 ? Tester_Class_1.var_14 : !false) ? "oaxg" : "igdnja"; + } + ((new Tester_Class_1[Tester_Class_1.var_21])[Tester_Class_1.var_21]).equals(new Tester_Class_1().var_15 = (Tester_Class_2.var_45 = "agdnue").charAt(1416972150) != Tester_Class_2.var_47 ? new Tester_Class_1() : new Tester_Class_1()); + byte var_96 = Tester_Class_1.var_21 >>>= (var_85 = (var_85 = '`')); + Tester_Class_2.var_45 = ""; + Tester_Class_2.var_47 += Tester_Class_2.var_47; + Tester_Class_2.var_45 = Tester_Class_2.var_45; + } + public String toString() + { + String result = "[\n"; + result += "Tester.var_71 = "; result += Printer.print(var_71); + result += "\n"; + result += "Tester.var_70 = "; result += Printer.print(var_70); + result += "\n"; + result += "Tester.var_72 = "; result += Printer.print(var_72); + result += "\n"; + result += "Tester.var_75 = "; result += Printer.print(var_75); + result += "\n"; + result += "Tester.var_73 = "; result += Printer.print(var_73); + result += "\n"; + result += "Tester.var_74 = "; result += Printer.print(var_74); + result += ""; + result += "\n]"; + return result; + } + static class Printer + { + public static String print(boolean arg) { return String.valueOf(arg); } + public static String print(byte arg) { return String.valueOf(arg); } + public static String print(short arg) { return String.valueOf(arg); } + public static String print(char arg) { return String.valueOf((int)arg); } + public static String print(int arg) { return String.valueOf(arg); } + public static String print(long arg) { return String.valueOf(arg); } + public static String print(float arg) { return String.valueOf(arg); } + public static String print(double arg) { return String.valueOf(arg); } + + + public static String print(Object arg) + { + return print_r(new java.util.Stack(), arg); + } + + private static String print_r(java.util.Stack visitedObjects, Object arg) + { + String result = ""; + if (arg == null) + result += "null"; + else + if (arg.getClass().isArray()) + { + for (int i = 0; i < visitedObjects.size(); i++) + if (visitedObjects.elementAt(i) == arg) return ""; + + visitedObjects.push(arg); + + final String delimiter = ", "; + result += "["; + + if (arg instanceof Object[]) + { + Object[] array = (Object[]) arg; + for (int i = 0; i < array.length; i++) + { + result += print_r(visitedObjects, array[i]); + if (i < array.length - 1) result += delimiter; + } + } + else + if (arg instanceof boolean[]) + { + boolean[] array = (boolean[]) arg; + for (int i = 0; i < array.length; i++) + { + result += print(array[i]); + if (i < array.length - 1) result += delimiter; + } + } + else + if (arg instanceof byte[]) + { + byte[] array = (byte[]) arg; + for (int i = 0; i < array.length; i++) + { + result += print(array[i]); + if (i < array.length - 1) result += delimiter; + } + } + else + if (arg instanceof short[]) + { + short[] array = (short[]) arg; + for (int i = 0; i < array.length; i++) + { + result += print(array[i]); + if (i < array.length - 1) result += delimiter; + } + } + else + if (arg instanceof char[]) + { + char[] array = (char[]) arg; + for (int i = 0; i < array.length; i++) + { + result += print(array[i]); + if (i < array.length - 1) result += delimiter; + } + } + else + if (arg instanceof int[]) + { + int[] array = (int[]) arg; + for (int i = 0; i < array.length; i++) + { + result += print(array[i]); + if (i < array.length - 1) result += delimiter; + } + } + else + if (arg instanceof long[]) + { + long[] array = (long[]) arg; + for (int i = 0; i < array.length; i++) + { + result += print(array[i]); + if (i < array.length - 1) result += delimiter; + } + } + else + if (arg instanceof float[]) + { + float[] array = (float[]) arg; + for (int i = 0; i < array.length; i++) + { + result += print(array[i]); + if (i < array.length - 1) result += delimiter; + } + } + else + if (arg instanceof double[]) + { + double[] array = (double[]) arg; + for (int i = 0; i < array.length; i++) + { + result += print(array[i]); + if (i < array.length - 1) result += delimiter; + } + } + + result += "]"; + visitedObjects.pop(); + + } else + { + result += arg.toString(); + } + + return result; + } + } +} + + From c54c100fd7e8b78559cea77ca008a7887292452b Mon Sep 17 00:00:00 2001 From: Andrei Dmitriev Date: Fri, 4 Apr 2008 20:20:16 +0400 Subject: [PATCH 141/258] 6573289: api/java_awt/Color/index.html#CreateContextTesttestCase4,5,6,7 fail since JDK 7 b14 Specify current behavior - not caching the painting context Reviewed-by: flar, son --- jdk/src/share/classes/java/awt/Color.java | 40 +++++++---- .../share/classes/java/awt/GradientPaint.java | 36 +++++++--- .../classes/java/awt/LinearGradientPaint.java | 27 +++++++- jdk/src/share/classes/java/awt/Paint.java | 68 ++++++++++++------- .../classes/java/awt/RadialGradientPaint.java | 26 ++++++- .../share/classes/java/awt/TexturePaint.java | 39 +++++++---- 6 files changed, 169 insertions(+), 67 deletions(-) diff --git a/jdk/src/share/classes/java/awt/Color.java b/jdk/src/share/classes/java/awt/Color.java index c06b573d7ca..22a8455f2b5 100644 --- a/jdk/src/share/classes/java/awt/Color.java +++ b/jdk/src/share/classes/java/awt/Color.java @@ -51,6 +51,7 @@ import java.awt.color.ColorSpace; * http://www.w3.org/pub/WWW/Graphics/Color/sRGB.html * . *

+ * @version 10 Feb 1997 * @author Sami Shaio * @author Arthur van Hoff * @see ColorSpace @@ -1176,23 +1177,32 @@ public class Color implements Paint, java.io.Serializable { } /** - * Creates and returns a {@link PaintContext} used to generate a solid - * color pattern. This enables a Color object to be used - * as an argument to any method requiring an object implementing the - * {@link Paint} interface. - * The same PaintContext is returned, regardless of - * whether or not r, r2d, - * xform, or hints are null. - * @param cm the specified ColorModel - * @param r the specified {@link Rectangle} - * @param r2d the specified {@link Rectangle2D} - * @param xform the specified {@link AffineTransform} - * @param hints the specified {@link RenderingHints} - * @return a PaintContext that is used to generate a - * solid color pattern. + * Creates and returns a {@link PaintContext} used to + * generate a solid color field pattern. + * See the {@link Paint#createContext specification} of the + * method in the {@link Paint} interface for information + * on null parameter handling. + * + * @param cm the preferred {@link ColorModel} which represents the most convenient + * format for the caller to receive the pixel data, or {@code null} + * if there is no preference. + * @param r the device space bounding box + * of the graphics primitive being rendered. + * @param r2d the user space bounding box + * of the graphics primitive being rendered. + * @param xform the {@link AffineTransform} from user + * space into device space. + * @param hints the set of hints that the context object can use to + * choose between rendering alternatives. + * @return the {@code PaintContext} for + * generating color patterns. * @see Paint * @see PaintContext - * @see Graphics2D#setPaint + * @see ColorModel + * @see Rectangle + * @see Rectangle2D + * @see AffineTransform + * @see RenderingHints */ public synchronized PaintContext createContext(ColorModel cm, Rectangle r, Rectangle2D r2d, diff --git a/jdk/src/share/classes/java/awt/GradientPaint.java b/jdk/src/share/classes/java/awt/GradientPaint.java index 840e7aec826..105fcd1f607 100644 --- a/jdk/src/share/classes/java/awt/GradientPaint.java +++ b/jdk/src/share/classes/java/awt/GradientPaint.java @@ -53,6 +53,7 @@ import java.awt.image.ColorModel; * * @see Paint * @see Graphics2D#setPaint + * @version 10 Feb 1997 */ public class GradientPaint implements Paint { @@ -223,19 +224,32 @@ public class GradientPaint implements Paint { } /** - * Creates and returns a context used to generate the color pattern. - * @param cm {@link ColorModel} that receives - * the Paint data. This is used only as a hint. - * @param deviceBounds the device space bounding box of the - * graphics primitive being rendered - * @param userBounds the user space bounding box of the - * graphics primitive being rendered + * Creates and returns a {@link PaintContext} used to + * generate a linear color gradient pattern. + * See the {@link Paint#createContext specification} of the + * method in the {@link Paint} interface for information + * on null parameter handling. + * + * @param cm the preferred {@link ColorModel} which represents the most convenient + * format for the caller to receive the pixel data, or {@code null} + * if there is no preference. + * @param deviceBounds the device space bounding box + * of the graphics primitive being rendered. + * @param userBounds the user space bounding box + * of the graphics primitive being rendered. * @param xform the {@link AffineTransform} from user - * space into device space - * @param hints the hints that the context object uses to choose - * between rendering alternatives - * @return the {@link PaintContext} that generates color patterns. + * space into device space. + * @param hints the set of hints that the context object can use to + * choose between rendering alternatives. + * @return the {@code PaintContext} for + * generating color patterns. + * @see Paint * @see PaintContext + * @see ColorModel + * @see Rectangle + * @see Rectangle2D + * @see AffineTransform + * @see RenderingHints */ public PaintContext createContext(ColorModel cm, Rectangle deviceBounds, diff --git a/jdk/src/share/classes/java/awt/LinearGradientPaint.java b/jdk/src/share/classes/java/awt/LinearGradientPaint.java index ea5a7339d16..2cf21cbe86d 100644 --- a/jdk/src/share/classes/java/awt/LinearGradientPaint.java +++ b/jdk/src/share/classes/java/awt/LinearGradientPaint.java @@ -296,7 +296,32 @@ public final class LinearGradientPaint extends MultipleGradientPaint { } /** - * {@inheritDoc} + * Creates and returns a {@link PaintContext} used to + * generate a linear color gradient pattern. + * See the {@link Paint#createContext specification} of the + * method in the {@link Paint} interface for information + * on null parameter handling. + * + * @param cm the preferred {@link ColorModel} which represents the most convenient + * format for the caller to receive the pixel data, or {@code null} + * if there is no preference. + * @param deviceBounds the device space bounding box + * of the graphics primitive being rendered. + * @param userBounds the user space bounding box + * of the graphics primitive being rendered. + * @param transform the {@link AffineTransform} from user + * space into device space. + * @param hints the set of hints that the context object can use to + * choose between rendering alternatives. + * @return the {@code PaintContext} for + * generating color patterns. + * @see Paint + * @see PaintContext + * @see ColorModel + * @see Rectangle + * @see Rectangle2D + * @see AffineTransform + * @see RenderingHints */ public PaintContext createContext(ColorModel cm, Rectangle deviceBounds, diff --git a/jdk/src/share/classes/java/awt/Paint.java b/jdk/src/share/classes/java/awt/Paint.java index 07c4274a08f..8e572db7eab 100644 --- a/jdk/src/share/classes/java/awt/Paint.java +++ b/jdk/src/share/classes/java/awt/Paint.java @@ -46,42 +46,58 @@ import java.awt.geom.Rectangle2D; * @see GradientPaint * @see TexturePaint * @see Graphics2D#setPaint + * @version 1.36, 06/05/07 */ public interface Paint extends Transparency { /** * Creates and returns a {@link PaintContext} used to * generate the color pattern. - * Since the ColorModel argument to createContext is only a - * hint, implementations of Paint should accept a null argument - * for ColorModel. Note that if the application does not - * prefer a specific ColorModel, the null ColorModel argument - * will give the Paint implementation full leeway in using the - * most efficient ColorModel it prefers for its raster processing. - *

- * Since the API documentation was not specific about this in - * releases before 1.4, there may be implementations of - * Paint that do not accept a null - * ColorModel argument. - * If a developer is writing code which passes a null - * ColorModel argument to the - * createContext method of Paint - * objects from arbitrary sources it would be wise to code defensively - * by manufacturing a non-null ColorModel for those - * objects which throw a NullPointerException. - * @param cm the {@link ColorModel} that receives the - * Paint data. This is used only as a hint. + * The arguments to this method convey additional information + * about the rendering operation that may be + * used or ignored on various implementations of the {@code Paint} interface. + * A caller must pass non-{@code null} values for all of the arguments + * except for the {@code ColorModel} argument which may be {@code null} to + * indicate that no specific {@code ColorModel} type is preferred. + * Implementations of the {@code Paint} interface are allowed to use or ignore + * any of the arguments as makes sense for their function, and are + * not constrained to use the specified {@code ColorModel} for the returned + * {@code PaintContext}, even if it is not {@code null}. + * Implementations are allowed to throw {@code NullPointerException} for + * any {@code null} argument other than the {@code ColorModel} argument, + * but are not required to do so. + * + * @param cm the preferred {@link ColorModel} which represents the most convenient + * format for the caller to receive the pixel data, or {@code null} + * if there is no preference. * @param deviceBounds the device space bounding box - * of the graphics primitive being rendered + * of the graphics primitive being rendered. + * Implementations of the {@code Paint} interface + * are allowed to throw {@code NullPointerException} + * for a {@code null} {@code deviceBounds}. * @param userBounds the user space bounding box - * of the graphics primitive being rendered + * of the graphics primitive being rendered. + * Implementations of the {@code Paint} interface + * are allowed to throw {@code NullPointerException} + * for a {@code null} {@code userBounds}. * @param xform the {@link AffineTransform} from user - * space into device space - * @param hints the hint that the context object uses to - * choose between rendering alternatives - * @return the PaintContext for - * generating color patterns + * space into device space. + * Implementations of the {@code Paint} interface + * are allowed to throw {@code NullPointerException} + * for a {@code null} {@code xform}. + * @param hints the set of hints that the context object can use to + * choose between rendering alternatives. + * Implementations of the {@code Paint} interface + * are allowed to throw {@code NullPointerException} + * for a {@code null} {@code hints}. + * @return the {@code PaintContext} for + * generating color patterns. * @see PaintContext + * @see ColorModel + * @see Rectangle + * @see Rectangle2D + * @see AffineTransform + * @see RenderingHints */ public PaintContext createContext(ColorModel cm, Rectangle deviceBounds, diff --git a/jdk/src/share/classes/java/awt/RadialGradientPaint.java b/jdk/src/share/classes/java/awt/RadialGradientPaint.java index 278906bb771..494daa57d1e 100644 --- a/jdk/src/share/classes/java/awt/RadialGradientPaint.java +++ b/jdk/src/share/classes/java/awt/RadialGradientPaint.java @@ -543,7 +543,31 @@ public final class RadialGradientPaint extends MultipleGradientPaint { } /** - * {@inheritDoc} + * Creates and returns a {@link PaintContext} used to + * generate a circular radial color gradient pattern. + * See the description of the {@link Paint#createContext createContext} method + * for information on null parameter handling. + * + * @param cm the preferred {@link ColorModel} which represents the most convenient + * format for the caller to receive the pixel data, or {@code null} + * if there is no preference. + * @param deviceBounds the device space bounding box + * of the graphics primitive being rendered. + * @param userBounds the user space bounding box + * of the graphics primitive being rendered. + * @param transform the {@link AffineTransform} from user + * space into device space. + * @param hints the set of hints that the context object can use to + * choose between rendering alternatives. + * @return the {@code PaintContext} for + * generating color patterns. + * @see Paint + * @see PaintContext + * @see ColorModel + * @see Rectangle + * @see Rectangle2D + * @see AffineTransform + * @see RenderingHints */ public PaintContext createContext(ColorModel cm, Rectangle deviceBounds, diff --git a/jdk/src/share/classes/java/awt/TexturePaint.java b/jdk/src/share/classes/java/awt/TexturePaint.java index 7c5dd5de01e..c4054e5783a 100644 --- a/jdk/src/share/classes/java/awt/TexturePaint.java +++ b/jdk/src/share/classes/java/awt/TexturePaint.java @@ -45,6 +45,7 @@ import java.awt.image.ColorModel; * replicated Rectangle2D. * @see Paint * @see Graphics2D#setPaint + * @version 1.48, 06/05/07 */ public class TexturePaint implements Paint { @@ -93,20 +94,32 @@ public class TexturePaint implements Paint { } /** - * Creates and returns a context used to generate the color pattern. - * @param cm the {@link ColorModel} that receives the - * Paint data. This is used only as a hint. - * @param deviceBounds the device space bounding box of the graphics - * primitive being rendered - * @param userBounds the user space bounding box of the graphics - * primitive being rendered - * @param xform the {@link AffineTransform} from user space - * into device space - * @param hints a {@link RenderingHints} object that can be used to - * specify how the pattern is ultimately rendered - * @return the {@link PaintContext} used for generating color - * patterns. + * Creates and returns a {@link PaintContext} used to + * generate a tiled image pattern. + * See the {@link Paint#createContext specification} of the + * method in the {@link Paint} interface for information + * on null parameter handling. + * + * @param cm the preferred {@link ColorModel} which represents the most convenient + * format for the caller to receive the pixel data, or {@code null} + * if there is no preference. + * @param deviceBounds the device space bounding box + * of the graphics primitive being rendered. + * @param userBounds the user space bounding box + * of the graphics primitive being rendered. + * @param xform the {@link AffineTransform} from user + * space into device space. + * @param hints the set of hints that the context object can use to + * choose between rendering alternatives. + * @return the {@code PaintContext} for + * generating color patterns. + * @see Paint * @see PaintContext + * @see ColorModel + * @see Rectangle + * @see Rectangle2D + * @see AffineTransform + * @see RenderingHints */ public PaintContext createContext(ColorModel cm, Rectangle deviceBounds, From e6ce57d09edba63a31db2ea3dff71b98485f716b Mon Sep 17 00:00:00 2001 From: Bradford Wetmore Date: Sun, 6 Apr 2008 10:15:03 -0700 Subject: [PATCH 142/258] 6683078: Update JCE framework and provider builds to work on read-only filesystems 6644659: Error in default target of make/javax/crypto in OpenJDK build Reviewed-by: valeriep, ohair --- jdk/make/com/sun/crypto/provider/Makefile | 76 +++++++++---- jdk/make/common/shared/Defs.gmk | 11 +- jdk/make/javax/crypto/Defs-jce.gmk | 13 ++- jdk/make/javax/crypto/Makefile | 126 +++++++++++++++------- jdk/make/sun/security/mscapi/Makefile | 47 ++++++-- jdk/make/sun/security/pkcs11/Makefile | 47 ++++++-- 6 files changed, 240 insertions(+), 80 deletions(-) diff --git a/jdk/make/com/sun/crypto/provider/Makefile b/jdk/make/com/sun/crypto/provider/Makefile index 3d948d03537..64e4320b19a 100644 --- a/jdk/make/com/sun/crypto/provider/Makefile +++ b/jdk/make/com/sun/crypto/provider/Makefile @@ -1,5 +1,5 @@ # -# Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. +# Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. # # This code is free software; you can redistribute it and/or modify it @@ -87,8 +87,7 @@ # sign Alias for sign-jar # sign-jar Builds/signs sunjce_provider.jar (no install) # -# obfus Builds/obfuscates/signs/installs -# sunjce_provider.jar +# obfus Builds/obfuscates/signs sunjce_provider.jar # # release Builds all targets in preparation # for workspace integration. @@ -101,8 +100,25 @@ BUILDDIR = ../../../.. PACKAGE = com.sun.crypto.provider PRODUCT = sun + +# +# The following is for when we need to do postprocessing +# (signing/obfuscation) against a read-only build. If the OUTPUTDIR +# isn't writable, the build currently crashes out. +# +ifndef OPENJDK + ifdef ALT_JCE_BUILD_DIR + # ===================================================== + # Where to place the output, in case we're building from a read-only + # build area. (e.g. a release engineering build.) + JCE_BUILD_DIR=${ALT_JCE_BUILD_DIR} + IGNORE_WRITABLE_OUTPUTDIR_TEST=true + else + JCE_BUILD_DIR=${TEMPDIR} + endif +endif + include $(BUILDDIR)/common/Defs.gmk -include $(BUILDDIR)/javax/crypto/Defs-jce.gmk # # Location for the newly built classfiles. @@ -147,6 +163,8 @@ endif # OPENJDK # UNSIGNED_DIR = $(TEMPDIR)/unsigned +include $(BUILDDIR)/javax/crypto/Defs-jce.gmk + # ===================================================== # Build the unsigned sunjce_provider.jar file. @@ -184,44 +202,66 @@ ifndef OPENJDK # Sign the provider jar file. Not needed for OpenJDK. # -SIGNED_DIR = $(TEMPDIR)/signed +SIGNED_DIR = $(JCE_BUILD_DIR)/signed sign: sign-jar sign-jar: $(SIGNED_DIR)/sunjce_provider.jar +ifndef ALT_JCE_BUILD_DIR $(SIGNED_DIR)/sunjce_provider.jar: $(UNSIGNED_DIR)/sunjce_provider.jar - $(sign-file) +else +# +# We have to remove the build dependency, otherwise, we'll try to rebuild it +# which we can't do on a read-only filesystem. +# +$(SIGNED_DIR)/sunjce_provider.jar: + @if [ ! -r $(UNSIGNED_DIR)/sunjce_provider.jar ] ; then \ + $(ECHO) "Couldn't find $(UNSIGNED_DIR)/sunjce_provider.jar"; \ + exit 1; \ + fi +endif + $(call sign-file, $(UNSIGNED_DIR)/sunjce_provider.jar) # ===================================================== # Obfuscate/sign/install the JDK build. Not needed for OpenJDK. # -OBFUS_DIR = $(TEMPDIR)/obfus +OBFUS_DIR = $(JCE_BUILD_DIR)/obfus/sunjce CLOSED_DIR = $(BUILDDIR)/closed/com/sun/crypto/provider obfus: $(OBFUS_DIR)/sunjce_provider.jar $(release-warning) -$(OBFUS_DIR)/sunjce_provider.jar: build-jar $(JCE_MANIFEST_FILE) +ifndef ALT_JCE_BUILD_DIR +$(OBFUS_DIR)/sunjce_provider.jar: build-jar $(JCE_MANIFEST_FILE) \ + $(OBFUS_DIR)/sunjce.dox +else +$(OBFUS_DIR)/sunjce_provider.jar: $(JCE_MANIFEST_FILE) $(OBFUS_DIR)/sunjce.dox + @if [ ! -d $(CLASSDESTDIR) ] ; then \ + $(ECHO) "Couldn't find $(CLASSDESTDIR)"; \ + exit 1; \ + fi +endif + @$(ECHO) ">>>Obfuscating SunJCE Provider..." $(presign) $(preobfus) - @$(ECHO) ">>>Obfuscating Sun JCE Provider..." $(prep-target) $(CD) $(OBFUS_DIR); \ - $(OBFUSCATOR) -fv \ - $(CURRENT_DIRECTORY)/$(CLOSED_DIR)/obfus/sunjce.dox + $(OBFUSCATOR) -fv sunjce.dox @$(CD) $(OBFUS_DIR); $(java-vm-cleanup) $(BOOT_JAR_CMD) cmf $(JCE_MANIFEST_FILE) $@ \ -C $(OBFUS_DIR)/build com \ $(JAR_JFLAGS) $(sign-target) - $(MKDIR) -p $(dir $(JAR_DESTFILE)) - $(RM) $(JAR_DESTFILE) - $(CP) $@ $(JAR_DESTFILE) @$(java-vm-cleanup) +$(OBFUS_DIR)/sunjce.dox: $(CLOSED_DIR)/obfus/sunjce.dox + @$(ECHO) ">>>Creating sunjce.dox" + $(prep-target) + $(SED) "s:@@TEMPDIR@@:$(ABS_TEMPDIR):" $< > $@ + # # The current obfuscator has a limitation in that it currently only # supports up to v49 class file format. Force v49 classfiles in our @@ -235,9 +275,9 @@ TARGET_CLASS_VERSION = 5 # release: $(OBFUS_DIR)/sunjce_provider.jar - $(RM) $(RELEASE_DIR)/sunjce_provider.jar - $(MKDIR) -p $(RELEASE_DIR) - $(CP) $(OBFUS_DIR)/sunjce_provider.jar $(RELEASE_DIR) + $(RM) $(JCE_BUILD_DIR)/release/sunjce_provider.jar + $(MKDIR) -p $(JCE_BUILD_DIR)/release + $(CP) $(OBFUS_DIR)/sunjce_provider.jar $(JCE_BUILD_DIR)/release $(release-warning) endif # OPENJDK @@ -275,7 +315,7 @@ endif # clobber clean:: - $(RM) -r $(JAR_DESTFILE) $(TEMPDIR) + $(RM) -r $(JAR_DESTFILE) $(TEMPDIR) $(JCE_BUILD_DIR) .PHONY: build-jar jar install-jar ifndef OPENJDK diff --git a/jdk/make/common/shared/Defs.gmk b/jdk/make/common/shared/Defs.gmk index 0eb8c729a96..c57baafc118 100644 --- a/jdk/make/common/shared/Defs.gmk +++ b/jdk/make/common/shared/Defs.gmk @@ -1,5 +1,5 @@ # -# Copyright 2005-2007 Sun Microsystems, Inc. All Rights Reserved. +# Copyright 2005-2008 Sun Microsystems, Inc. All Rights Reserved. # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. # # This code is free software; you can redistribute it and/or modify it @@ -449,11 +449,20 @@ endif # Check for spaces and null value OUTPUTDIR:=$(call AltCheckSpaces,OUTPUTDIR) OUTPUTDIR:=$(call AltCheckValue,OUTPUTDIR) + +# +# When signing the JCE framework and provider, we could be using built +# bits on a read-only filesystem. If so, this test will fail and crash +# the build. +# +ifndef IGNORE_WRITABLE_OUTPUTDIR_TEST # Create the output directory and make sure it exists and is writable _create_outputdir:=$(shell $(MKDIR) -p "$(OUTPUTDIR)" > $(DEV_NULL) 2>&1) ifeq ($(call WriteDirExists,$(OUTPUTDIR),/dev/null),/dev/null) _outputdir_error:=$(error "ERROR: OUTPUTDIR '$(OUTPUTDIR)' not created or not writable") endif +endif + # Define absolute path if needed and check for spaces and null value ifndef ABS_OUTPUTDIR ABS_OUTPUTDIR:=$(call FullPath,$(OUTPUTDIR)) diff --git a/jdk/make/javax/crypto/Defs-jce.gmk b/jdk/make/javax/crypto/Defs-jce.gmk index c1ef30d5448..46fe1118dca 100644 --- a/jdk/make/javax/crypto/Defs-jce.gmk +++ b/jdk/make/javax/crypto/Defs-jce.gmk @@ -1,5 +1,5 @@ # -# Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. +# Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. # # This code is free software; you can redistribute it and/or modify it @@ -31,7 +31,7 @@ include $(BUILDDIR)/common/Release.gmk JCE_MANIFEST_FILE = $(TEMPDIR)/manifest.mf $(JCE_MANIFEST_FILE): $(MAINMANIFEST) $(prep-target) - ( $(SED) "s/@@RELEASE@@/$(RELEASE)/" $(MAINMANIFEST); \ + ( $(SED) "s/@@RELEASE@@/$(RELEASE)/" $<; \ $(ECHO) "Extension-Name: javax.crypto"; \ $(ECHO) "Implementation-Vendor-Id: com.sun"; ) > $@ @@ -75,6 +75,7 @@ endef define sign-target $(BOOT_JARSIGNER_CMD) -keystore $(SIGNING_KEYSTORE) \ $@ $(SIGNING_ALIAS) < $(SIGNING_PASSPHRASE) + @$(java-vm-cleanup) @$(ECHO) "\nJar codesigning finished." endef @@ -88,13 +89,15 @@ define release-warning endef # -# Convenience macro for steps needed to sign a jar file. +# Convenience macros for signing a jar file. +# +# Call through $(call sign-file, target file) # define sign-file $(presign) - $(install-file) + $(prep-target) + $(CP) $1 $@ $(sign-target) - @$(java-vm-cleanup) endef # diff --git a/jdk/make/javax/crypto/Makefile b/jdk/make/javax/crypto/Makefile index 98b8a9158bf..86588e855ef 100644 --- a/jdk/make/javax/crypto/Makefile +++ b/jdk/make/javax/crypto/Makefile @@ -1,5 +1,5 @@ # -# Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. +# Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. # # This code is free software; you can redistribute it and/or modify it @@ -96,7 +96,7 @@ # sign-jar Builds/signs jce.jar file (no install) # sign-policy Builds/signs policy files (no install) # -# obfus Builds/obfuscates/signs/installs jce.jar +# obfus Builds/obfuscates/signs jce.jar # # release Builds all targets in preparation # for workspace integration. @@ -110,8 +110,24 @@ BUILDDIR = ../.. PACKAGE = javax.crypto PRODUCT = sun +# +# The following is for when we need to do postprocessing +# (signing/obfuscation) against a read-only build. If the OUTPUTDIR +# isn't writable, the build currently crashes out. +# +ifndef OPENJDK + ifdef ALT_JCE_BUILD_DIR + # ===================================================== + # Where to place the output, in case we're building from a read-only + # build area. (e.g. a release engineering build.) + JCE_BUILD_DIR=${ALT_JCE_BUILD_DIR} + IGNORE_WRITABLE_OUTPUTDIR_TEST=true + else + JCE_BUILD_DIR=${TEMPDIR} + endif +endif + include $(BUILDDIR)/common/Defs.gmk -include Defs-jce.gmk # # Location for the newly built classfiles. @@ -158,6 +174,8 @@ endif # OPENJDK # UNSIGNED_DIR = $(TEMPDIR)/unsigned +include Defs-jce.gmk + # ===================================================== # Build the unsigned jce.jar file. Signing/obfuscation comes later. @@ -299,7 +317,7 @@ ifndef OPENJDK # Sign the various jar files. Not needed for OpenJDK. # -SIGNED_DIR = $(TEMPDIR)/signed +SIGNED_DIR = $(JCE_BUILD_DIR)/signed SIGNED_POLICY_BUILDDIR = $(SIGNED_DIR)/policy SIGNED_POLICY_FILES = \ @@ -312,61 +330,87 @@ sign-jar: $(SIGNED_DIR)/jce.jar sign-policy: $(SIGNED_POLICY_FILES) +ifndef ALT_JCE_BUILD_DIR $(SIGNED_DIR)/jce.jar: $(UNSIGNED_DIR)/jce.jar - $(sign-file) +else +# +# We have to remove the build dependency, otherwise, we'll try to rebuild it +# which we can't do on a read-only filesystem. +# +$(SIGNED_DIR)/jce.jar: + @if [ ! -r $(UNSIGNED_DIR)/jce.jar ] ; then \ + $(ECHO) "Couldn't find $(UNSIGNED_DIR)/jce.jar"; \ + exit 1; \ + fi +endif + $(call sign-file, $(UNSIGNED_DIR)/jce.jar) $(SIGNED_POLICY_BUILDDIR)/unlimited/US_export_policy.jar: \ -$(UNSIGNED_POLICY_BUILDDIR)/unlimited/US_export_policy.jar - $(sign-file) + $(UNSIGNED_POLICY_BUILDDIR)/unlimited/US_export_policy.jar + $(call sign-file, $<) $(SIGNED_POLICY_BUILDDIR)/unlimited/local_policy.jar: \ -$(UNSIGNED_POLICY_BUILDDIR)/unlimited/local_policy.jar - $(sign-file) + $(UNSIGNED_POLICY_BUILDDIR)/unlimited/local_policy.jar + $(call sign-file, $<) $(SIGNED_POLICY_BUILDDIR)/limited/US_export_policy.jar: \ -$(UNSIGNED_POLICY_BUILDDIR)/limited/US_export_policy.jar - $(sign-file) + $(UNSIGNED_POLICY_BUILDDIR)/limited/US_export_policy.jar + $(call sign-file, $<) $(SIGNED_POLICY_BUILDDIR)/limited/local_policy.jar: \ -$(UNSIGNED_POLICY_BUILDDIR)/limited/local_policy.jar - $(sign-file) + $(UNSIGNED_POLICY_BUILDDIR)/limited/local_policy.jar + $(call sign-file, $<) # ===================================================== # Obfuscate/sign/install the JDK build. Not needed for OpenJDK. # -OBFUS_DIR = $(TEMPDIR)/obfus +OBFUS_DIR = $(JCE_BUILD_DIR)/obfus/jce CLOSED_DIR = $(BUILDDIR)/closed/javax/crypto obfus: $(OBFUS_DIR)/jce.jar $(release-warning) -$(OBFUS_DIR)/jce.jar: build-jar $(JCE_MANIFEST_FILE) +ifndef ALT_JCE_BUILD_DIR +$(OBFUS_DIR)/jce.jar: build-jar $(JCE_MANIFEST_FILE) $(OBFUS_DIR)/framework.dox +else +# +# We have to remove the build dependency, otherwise, we'll try to rebuild it +# which we can't do on a read-only filesystem. +# +$(OBFUS_DIR)/jce.jar: $(JCE_MANIFEST_FILE) $(OBFUS_DIR)/framework.dox + @if [ ! -d $(CLASSDESTDIR) ] ; then \ + $(ECHO) "Couldn't find $(CLASSDESTDIR)"; \ + exit 1; \ + fi +endif + @$(ECHO) ">>>Obfuscating JCE framework..." $(presign) $(preobfus) - @$(ECHO) ">>>Obfuscating JCE framework..." $(prep-target) $(CD) $(OBFUS_DIR); \ - $(OBFUSCATOR) -fv \ - $(CURRENT_DIRECTORY)/$(CLOSED_DIR)/obfus/framework.dox + $(OBFUSCATOR) -fv framework.dox @$(CD) $(OBFUS_DIR); $(java-vm-cleanup) + @# @# The sun.security.internal classes are currently not obfuscated @# due to an obfus problem. Manually copy them to the build directory @# so that they are included in the jce.jar file. + @# $(CP) -r $(CLASSDESTDIR)/sun $(OBFUS_DIR)/build - $(RM) $(UNSIGNED_DIR)/jce.jar $(BOOT_JAR_CMD) cmf $(JCE_MANIFEST_FILE) $@ \ -C $(OBFUS_DIR)/build javax \ -C $(OBFUS_DIR)/build sun \ $(JAR_JFLAGS) $(sign-target) - $(MKDIR) -p $(dir $(JAR_DESTFILE)) - $(RM) $(JAR_DESTFILE) - $(CP) $@ $(JAR_DESTFILE) @$(java-vm-cleanup) +$(OBFUS_DIR)/framework.dox: $(CLOSED_DIR)/obfus/framework.dox + @$(ECHO) ">>>Creating framework.dox" + $(prep-target) + $(SED) "s:@@TEMPDIR@@:$(ABS_TEMPDIR):" $< > $@ + # # The current obfuscator has a limitation in that it currently only # supports up to v49 class file format. Force v49 classfiles in our @@ -380,26 +424,27 @@ TARGET_CLASS_VERSION = 5 # unlimited policy file distribution, etc. # -release: $(OBFUS_DIR)/jce.jar sign-policy +release: $(OBFUS_DIR)/jce.jar sign-policy $(CLOSED_DIR)/doc/COPYRIGHT.html \ + $(CLOSED_DIR)/doc/README.txt $(RM) -r \ - $(RELEASE_DIR)/UnlimitedJCEPolicy \ - $(RELEASE_DIR)/jce.jar \ - $(RELEASE_DIR)/US_export_policy.jar \ - $(RELEASE_DIR)/local_policy.jar \ - $(RELEASE_DIR)/UnlimitedJCEPolicy.zip - $(MKDIR) -p $(RELEASE_DIR)/UnlimitedJCEPolicy - $(CP) $(OBFUS_DIR)/jce.jar $(RELEASE_DIR) - $(CP) -r \ - $(SIGNED_POLICY_BUILDDIR)/limited/US_export_policy.jar \ - $(SIGNED_POLICY_BUILDDIR)/limited/local_policy.jar \ - $(RELEASE_DIR) + $(JCE_BUILD_DIR)/release/UnlimitedJCEPolicy \ + $(JCE_BUILD_DIR)/release/jce.jar \ + $(JCE_BUILD_DIR)/release/US_export_policy.jar \ + $(JCE_BUILD_DIR)/release/local_policy.jar \ + $(JCE_BUILD_DIR)/release/UnlimitedJCEPolicy.zip + $(MKDIR) -p $(JCE_BUILD_DIR)/release/UnlimitedJCEPolicy + $(CP) $(OBFUS_DIR)/jce.jar $(JCE_BUILD_DIR)/release + $(CP) \ + $(SIGNED_POLICY_BUILDDIR)/limited/US_export_policy.jar \ + $(SIGNED_POLICY_BUILDDIR)/limited/local_policy.jar \ + $(JCE_BUILD_DIR)/release $(CP) \ $(SIGNED_POLICY_BUILDDIR)/unlimited/US_export_policy.jar \ - $(SIGNED_POLICY_BUILDDIR)/unlimited/local_policy.jar \ - $(RELEASE_DIR)/UnlimitedJCEPolicy - $(CP) $(CLOSED_DIR)/doc/COPYRIGHT.html \ - $(CLOSED_DIR)/doc/README.txt $(RELEASE_DIR)/UnlimitedJCEPolicy - cd $(RELEASE_DIR) ; \ + $(SIGNED_POLICY_BUILDDIR)/unlimited/local_policy.jar \ + $(CLOSED_DIR)/doc/COPYRIGHT.html \ + $(CLOSED_DIR)/doc/README.txt \ + $(JCE_BUILD_DIR)/release/UnlimitedJCEPolicy + cd $(JCE_BUILD_DIR)/release ; \ $(ZIPEXE) -qr UnlimitedJCEPolicy.zip UnlimitedJCEPolicy $(release-warning) @@ -478,7 +523,8 @@ endif clobber clean:: $(RM) -r $(JAR_DESTFILE) $(POLICY_DESTDIR)/US_export_policy.jar \ - $(POLICY_DESTDIR)/local_policy.jar $(DELETE_DIRS) $(TEMPDIR) + $(POLICY_DESTDIR)/local_policy.jar $(DELETE_DIRS) $(TEMPDIR) \ + $(JCE_BUILD_DIR) .PHONY: build-jar jar build-policy unlimited limited install-jar \ install-limited install-unlimited diff --git a/jdk/make/sun/security/mscapi/Makefile b/jdk/make/sun/security/mscapi/Makefile index e6b2372b69b..8223b536709 100644 --- a/jdk/make/sun/security/mscapi/Makefile +++ b/jdk/make/sun/security/mscapi/Makefile @@ -1,5 +1,5 @@ # -# Copyright 2005-2007 Sun Microsystems, Inc. All Rights Reserved. +# Copyright 2005-2008 Sun Microsystems, Inc. All Rights Reserved. # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. # # This code is free software; you can redistribute it and/or modify it @@ -92,8 +92,25 @@ BUILDDIR = ../../.. PACKAGE = sun.security.mscapi LIBRARY = sunmscapi PRODUCT = sun + +# +# The following is for when we need to do postprocessing +# (signing/obfuscation) against a read-only build. If the OUTPUTDIR +# isn't writable, the build currently crashes out. +# +ifndef OPENJDK + ifdef ALT_JCE_BUILD_DIR + # ===================================================== + # Where to place the output, in case we're building from a read-only + # build area. (e.g. a release engineering build.) + JCE_BUILD_DIR=${ALT_JCE_BUILD_DIR} + IGNORE_WRITABLE_OUTPUTDIR_TEST=true + else + JCE_BUILD_DIR=${TEMPDIR} + endif +endif + include $(BUILDDIR)/common/Defs.gmk -include $(BUILDDIR)/javax/crypto/Defs-jce.gmk CPLUSPLUSLIBRARY=true @@ -163,6 +180,8 @@ all: build-jar install-prebuilt $(build-warning) endif +include $(BUILDDIR)/javax/crypto/Defs-jce.gmk + # ===================================================== # Build the unsigned sunmscapi.jar file. @@ -200,14 +219,26 @@ ifndef OPENJDK # Sign the provider jar file. Not needed for OpenJDK. # -SIGNED_DIR = $(TEMPDIR)/signed +SIGNED_DIR = $(JCE_BUILD_DIR)/signed sign: sign-jar sign-jar: $(SIGNED_DIR)/sunmscapi.jar +ifndef ALT_JCE_BUILD_DIR $(SIGNED_DIR)/sunmscapi.jar: $(UNSIGNED_DIR)/sunmscapi.jar - $(sign-file) +else +# +# We have to remove the build dependency, otherwise, we'll try to rebuild it +# which we can't do on a read-only filesystem. +# +$(SIGNED_DIR)/sunmscapi.jar: + @if [ ! -r $(UNSIGNED_DIR)/sunmscapi.jar ] ; then \ + $(ECHO) "Couldn't find $(UNSIGNED_DIR)/sunmscapi.jar"; \ + exit 1; \ + fi +endif + $(call sign-file, $(UNSIGNED_DIR)/sunmscapi.jar) # ===================================================== @@ -215,9 +246,9 @@ $(SIGNED_DIR)/sunmscapi.jar: $(UNSIGNED_DIR)/sunmscapi.jar # release: $(SIGNED_DIR)/sunmscapi.jar - $(RM) $(RELEASE_DIR)/sunmscapi.jar - $(MKDIR) -p $(RELEASE_DIR) - $(CP) $(SIGNED_DIR)/sunmscapi.jar $(RELEASE_DIR) + $(RM) $(JCE_BUILD_DIR)/release/sunmscapi.jar + $(MKDIR) -p $(JCE_BUILD_DIR)/release + $(CP) $(SIGNED_DIR)/sunmscapi.jar $(JCE_BUILD_DIR)/release $(release-warning) endif # OPENJDK @@ -255,7 +286,7 @@ endif # clobber clean:: - $(RM) -r $(JAR_DESTFILE) $(TEMPDIR) + $(RM) -r $(JAR_DESTFILE) $(TEMPDIR) $(JCE_BUILD_DIR) .PHONY: build-jar jar install-jar ifndef OPENJDK diff --git a/jdk/make/sun/security/pkcs11/Makefile b/jdk/make/sun/security/pkcs11/Makefile index 32d77f90d94..4508b20f843 100644 --- a/jdk/make/sun/security/pkcs11/Makefile +++ b/jdk/make/sun/security/pkcs11/Makefile @@ -1,5 +1,5 @@ # -# Copyright 2003-2007 Sun Microsystems, Inc. All Rights Reserved. +# Copyright 2003-2008 Sun Microsystems, Inc. All Rights Reserved. # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. # # This code is free software; you can redistribute it and/or modify it @@ -92,8 +92,25 @@ BUILDDIR = ../../.. PACKAGE = sun.security.pkcs11 LIBRARY = j2pkcs11 PRODUCT = sun + +# +# The following is for when we need to do postprocessing +# (signing/obfuscation) against a read-only build. If the OUTPUTDIR +# isn't writable, the build currently crashes out. +# +ifndef OPENJDK + ifdef ALT_JCE_BUILD_DIR + # ===================================================== + # Where to place the output, in case we're building from a read-only + # build area. (e.g. a release engineering build.) + JCE_BUILD_DIR=${ALT_JCE_BUILD_DIR} + IGNORE_WRITABLE_OUTPUTDIR_TEST=true + else + JCE_BUILD_DIR=${TEMPDIR} + endif +endif + include $(BUILDDIR)/common/Defs.gmk -include $(BUILDDIR)/javax/crypto/Defs-jce.gmk # # C and Java Files @@ -163,6 +180,8 @@ all: build-jar install-prebuilt $(build-warning) endif +include $(BUILDDIR)/javax/crypto/Defs-jce.gmk + # ===================================================== # Build the unsigned sunpkcs11.jar file. @@ -200,14 +219,26 @@ ifndef OPENJDK # Sign the provider jar file. Not needed for OpenJDK. # -SIGNED_DIR = $(TEMPDIR)/signed +SIGNED_DIR = $(JCE_BUILD_DIR)/signed sign: sign-jar sign-jar: $(SIGNED_DIR)/sunpkcs11.jar +ifndef ALT_JCE_BUILD_DIR $(SIGNED_DIR)/sunpkcs11.jar: $(UNSIGNED_DIR)/sunpkcs11.jar - $(sign-file) +else +# +# We have to remove the build dependency, otherwise, we'll try to rebuild it +# which we can't do on a read-only filesystem. +# +$(SIGNED_DIR)/sunpkcs11.jar: + @if [ ! -r $(UNSIGNED_DIR)/sunpkcs11.jar ] ; then \ + $(ECHO) "Couldn't find $(UNSIGNED_DIR)/sunpkcs11.jar"; \ + exit 1; \ + fi +endif + $(call sign-file, $(UNSIGNED_DIR)/sunpkcs11.jar) # ===================================================== @@ -215,9 +246,9 @@ $(SIGNED_DIR)/sunpkcs11.jar: $(UNSIGNED_DIR)/sunpkcs11.jar # release: $(SIGNED_DIR)/sunpkcs11.jar - $(RM) $(RELEASE_DIR)/sunpkcs11.jar - $(MKDIR) -p $(RELEASE_DIR) - $(CP) $(SIGNED_DIR)/sunpkcs11.jar $(RELEASE_DIR) + $(RM) $(JCE_BUILD_DIR)/release/sunpkcs11.jar + $(MKDIR) -p $(JCE_BUILD_DIR)/release + $(CP) $(SIGNED_DIR)/sunpkcs11.jar $(JCE_BUILD_DIR)/release $(release-warning) endif # OPENJDK @@ -255,7 +286,7 @@ endif # clobber clean:: - $(RM) -r $(JAR_DESTFILE) $(TEMPDIR) + $(RM) -r $(JAR_DESTFILE) $(TEMPDIR) $(JCE_BUILD_DIR) .PHONY: build-jar jar install-jar ifndef OPENJDK From f3cc321cb27cf735a02905ecefa86640e13c59e0 Mon Sep 17 00:00:00 2001 From: Peter Zhelezniakov Date: Mon, 7 Apr 2008 13:07:04 +0400 Subject: [PATCH 143/258] 4765383: JTextArea.append(String) not thread safe Several swing.text methods are not marked thread-safe anymore. Reviewed-by: gsm --- .../classes/javax/swing/JEditorPane.java | 10 ------- .../share/classes/javax/swing/JTextArea.java | 15 ---------- .../share/classes/javax/swing/JTextPane.java | 30 ------------------- .../javax/swing/text/JTextComponent.java | 11 +------ 4 files changed, 1 insertion(+), 65 deletions(-) diff --git a/jdk/src/share/classes/javax/swing/JEditorPane.java b/jdk/src/share/classes/javax/swing/JEditorPane.java index 4cf18c009c3..c126fe70c01 100644 --- a/jdk/src/share/classes/javax/swing/JEditorPane.java +++ b/jdk/src/share/classes/javax/swing/JEditorPane.java @@ -1120,11 +1120,6 @@ public class JEditorPane extends JTextComponent { * current selection. The replacement text will have the * attributes currently defined for input. If the component is not * editable, beep and return. - *

- * This method is thread safe, although most Swing methods - * are not. Please see - * How - * to Use Threads for more information. * * @param content the content to replace the selection with. This * value can be null @@ -1395,11 +1390,6 @@ public class JEditorPane extends JTextComponent { * create a StringReader and call the read method. In this case the model * would be replaced after it was initialized with the contents of the * string. - *

- * This method is thread safe, although most Swing methods - * are not. Please see - * How - * to Use Threads for more information. * * @param t the new text to be set; if null the old * text will be deleted diff --git a/jdk/src/share/classes/javax/swing/JTextArea.java b/jdk/src/share/classes/javax/swing/JTextArea.java index 8f53daf2aca..f7718198bf7 100644 --- a/jdk/src/share/classes/javax/swing/JTextArea.java +++ b/jdk/src/share/classes/javax/swing/JTextArea.java @@ -444,11 +444,6 @@ public class JTextArea extends JTextComponent { /** * Inserts the specified text at the specified position. Does nothing * if the model is null or if the text is null or empty. - *

- * This method is thread safe, although most Swing methods - * are not. Please see - * How - * to Use Threads for more information. * * @param str the text to insert * @param pos the position at which to insert >= 0 @@ -471,11 +466,6 @@ public class JTextArea extends JTextComponent { /** * Appends the given text to the end of the document. Does nothing if * the model is null or the string is null or empty. - *

- * This method is thread safe, although most Swing methods - * are not. Please see - * How - * to Use Threads for more information. * * @param str the text to insert * @see #insert @@ -494,11 +484,6 @@ public class JTextArea extends JTextComponent { * Replaces text from the indicated start to end position with the * new text specified. Does nothing if the model is null. Simply * does a delete if the new string is null or empty. - *

- * This method is thread safe, although most Swing methods - * are not. Please see - * How - * to Use Threads for more information. * * @param str the text to use as the replacement * @param start the start position >= 0 diff --git a/jdk/src/share/classes/javax/swing/JTextPane.java b/jdk/src/share/classes/javax/swing/JTextPane.java index 69b94a30e42..c820f512d7e 100644 --- a/jdk/src/share/classes/javax/swing/JTextPane.java +++ b/jdk/src/share/classes/javax/swing/JTextPane.java @@ -167,11 +167,6 @@ public class JTextPane extends JEditorPane { * current selection. The replacement text will have the * attributes currently defined for input at the point of * insertion. If the document is not editable, beep and return. - *

- * This method is thread safe, although most Swing methods - * are not. Please see - * How - * to Use Threads for more information. * * @param content the content to replace the selection with */ @@ -229,11 +224,6 @@ public class JTextPane extends JEditorPane { * a value of 0.75 will cause 75 percent of the * component to be above the baseline, and 25 percent of the * component to be below the baseline. - *

- * This method is thread safe, although most Swing methods - * are not. Please see - * How - * to Use Threads for more information. * * @param c the component to insert */ @@ -252,11 +242,6 @@ public class JTextPane extends JEditorPane { * current position of the caret. This is represented in * the associated document as an attribute of one character * of content. - *

- * This method is thread safe, although most Swing methods - * are not. Please see - * How - * to Use Threads for more information. * * @param g the icon to insert * @see Icon @@ -320,11 +305,6 @@ public class JTextPane extends JEditorPane { * through the logical style assigned to the paragraph, which * in term may resolve through some hierarchy completely * independent of the element hierarchy in the document. - *

- * This method is thread safe, although most Swing methods - * are not. Please see - * How - * to Use Threads for more information. * * @param s the logical style to assign to the paragraph, * or null for no style @@ -367,11 +347,6 @@ public class JTextPane extends JEditorPane { * is no selection, the attributes are applied to * the input attribute set which defines the attributes * for any new text that gets inserted. - *

- * This method is thread safe, although most Swing methods - * are not. Please see - * How - * to Use Threads for more information. * * @param attr the attributes * @param replace if true, then replace the existing attributes first @@ -412,11 +387,6 @@ public class JTextPane extends JEditorPane { * to the paragraphs that intersect the selection. * If there is no selection, the attributes are applied * to the paragraph at the current caret position. - *

- * This method is thread safe, although most Swing methods - * are not. Please see - * How - * to Use Threads for more information. * * @param attr the non-null attributes * @param replace if true, replace the existing attributes first diff --git a/jdk/src/share/classes/javax/swing/text/JTextComponent.java b/jdk/src/share/classes/javax/swing/text/JTextComponent.java index 9ba89895682..d340f281eff 100644 --- a/jdk/src/share/classes/javax/swing/text/JTextComponent.java +++ b/jdk/src/share/classes/javax/swing/text/JTextComponent.java @@ -1349,11 +1349,6 @@ public abstract class JTextComponent extends JComponent implements Scrollable, A * This is the method that is used by the default implementation * of the action for inserting content that gets bound to the * keymap actions. - *

- * This method is thread safe, although most Swing methods - * are not. Please see - * How - * to Use Threads for more information. * * @param content the content to replace the selection with */ @@ -1687,12 +1682,8 @@ public abstract class JTextComponent extends JComponent implements Scrollable, A * or empty, has the effect of simply deleting the old text. * When text has been inserted, the resulting caret location * is determined by the implementation of the caret class. - *

- * This method is thread safe, although most Swing methods - * are not. Please see - * How - * to Use Threads for more information. * + *

* Note that text is not a bound property, so no PropertyChangeEvent * is fired when it changes. To listen for changes to the text, * use DocumentListener. From 0e36651f33707dfd5761bd2242b8793f24b6659e Mon Sep 17 00:00:00 2001 From: Andrei Dmitriev Date: Mon, 7 Apr 2008 14:53:51 +0400 Subject: [PATCH 144/258] 6613529: Avoid duplicate object creation within JDK packages Avoid using constructors when unique values are not necessary Reviewed-by: volk, igor, peterz --- .../imageio/plugins/gif/GIFImageReader.java | 2 +- .../plugins/gif/GIFWritableImageMetadata.java | 2 +- .../swing/plaf/gtk/GTKColorChooserPanel.java | 30 ++++----- .../java/swing/plaf/gtk/GTKLookAndFeel.java | 32 +++++----- .../com/sun/java/swing/plaf/gtk/GTKStyle.java | 14 ++--- .../com/sun/java/swing/plaf/gtk/Metacity.java | 4 +- .../swing/plaf/motif/MotifLookAndFeel.java | 14 ++--- .../plaf/windows/WindowsLookAndFeel.java | 62 +++++++++---------- jdk/src/share/classes/java/awt/Button.java | 2 +- jdk/src/share/classes/java/awt/MenuItem.java | 2 +- .../awt/datatransfer/SystemFlavorMap.java | 4 +- .../classes/java/awt/image/BufferedImage.java | 6 +- .../text/DictionaryBasedBreakIterator.java | 6 +- .../classes/java/text/MessageFormat.java | 4 +- .../imageio/stream/ImageInputStreamImpl.java | 4 +- .../classes/javax/swing/AbstractButton.java | 12 ++-- .../javax/swing/DebugGraphicsInfo.java | 2 +- .../classes/javax/swing/JInternalFrame.java | 8 +-- .../classes/javax/swing/JOptionPane.java | 2 +- .../classes/javax/swing/JProgressBar.java | 14 ++--- .../share/classes/javax/swing/JScrollBar.java | 14 ++--- .../share/classes/javax/swing/JSlider.java | 20 +++--- .../share/classes/javax/swing/JSplitPane.java | 6 +- .../classes/javax/swing/JTabbedPane.java | 2 +- jdk/src/share/classes/javax/swing/JTable.java | 8 +-- .../share/classes/javax/swing/JTextArea.java | 2 +- .../javax/swing/SpinnerNumberModel.java | 12 ++-- .../classes/javax/swing/TablePrintable.java | 2 +- .../javax/swing/plaf/basic/BasicButtonUI.java | 2 +- .../swing/plaf/basic/BasicLookAndFeel.java | 2 +- .../swing/plaf/basic/BasicMenuItemUI.java | 2 +- .../swing/plaf/basic/BasicOptionPaneUI.java | 6 +- .../swing/plaf/basic/BasicTabbedPaneUI.java | 4 +- .../swing/plaf/basic/BasicToolBarUI.java | 2 +- .../swing/plaf/metal/MetalLookAndFeel.java | 6 +- .../swing/plaf/synth/SynthArrowButton.java | 2 +- .../swing/plaf/synth/SynthDesktopPaneUI.java | 2 +- .../swing/plaf/synth/SynthSplitPaneUI.java | 2 +- .../javax/swing/table/TableColumn.java | 2 +- .../javax/swing/text/AbstractDocument.java | 4 +- .../javax/swing/text/NumberFormatter.java | 13 ++-- .../javax/swing/text/PlainDocument.java | 2 +- .../classes/javax/swing/text/Segment.java | 2 +- .../javax/swing/text/StyleConstants.java | 6 +- .../javax/swing/text/html/AccessibleHTML.java | 8 +-- .../classes/javax/swing/text/html/CSS.java | 2 +- .../javax/swing/text/html/HTMLEditorKit.java | 4 +- .../swing/text/html/parser/AttributeList.java | 14 ++--- .../javax/swing/text/html/parser/DTD.java | 4 +- .../javax/swing/text/html/parser/Element.java | 8 +-- .../javax/swing/text/html/parser/Entity.java | 18 +++--- .../javax/swing/text/html/parser/Parser.java | 2 +- .../javax/swing/text/rtf/RTFAttributes.java | 6 +- .../javax/swing/text/rtf/RTFGenerator.java | 14 +---- .../swing/tree/DefaultTreeSelectionModel.java | 4 +- .../share/classes/sun/applet/AppletPanel.java | 2 +- .../classes/sun/applet/AppletViewer.java | 4 +- .../classes/sun/awt/FontConfiguration.java | 2 +- .../classes/sun/awt/im/InputContext.java | 4 +- .../classes/sun/font/FileFontStrike.java | 4 +- .../share/classes/sun/font/FontManager.java | 2 +- .../share/classes/sun/font/FontResolver.java | 2 +- .../classes/sun/font/PhysicalStrike.java | 2 +- .../classes/sun/java2d/SunGraphics2D.java | 2 +- .../classes/sun/java2d/loops/SurfaceType.java | 2 +- .../share/classes/sun/print/PSPrinterJob.java | 18 +++--- .../classes/sun/print/RasterPrinterJob.java | 2 +- .../sun/text/normalizer/VersionInfo.java | 2 +- .../sun/awt/X11/XDropTargetProtocol.java | 2 +- .../sun/awt/X11/XDropTargetRegistry.java | 2 +- .../sun/awt/X11/XEmbedServerTester.java | 4 +- .../classes/sun/awt/X11/XFileDialogPeer.java | 2 +- .../classes/sun/awt/X11/XScrollbar.java | 8 +-- .../classes/sun/awt/X11GraphicsConfig.java | 2 +- .../classes/sun/awt/X11GraphicsDevice.java | 6 +- .../classes/sun/print/UnixPrintJob.java | 21 +++---- .../sun/awt/windows/WDataTransferer.java | 2 +- .../classes/sun/awt/windows/WInputMethod.java | 2 +- .../classes/sun/awt/windows/WWindowPeer.java | 2 +- .../classes/sun/print/Win32PrintService.java | 8 +-- 80 files changed, 268 insertions(+), 276 deletions(-) diff --git a/jdk/src/share/classes/com/sun/imageio/plugins/gif/GIFImageReader.java b/jdk/src/share/classes/com/sun/imageio/plugins/gif/GIFImageReader.java index b41450257a0..ae2bcb56a20 100644 --- a/jdk/src/share/classes/com/sun/imageio/plugins/gif/GIFImageReader.java +++ b/jdk/src/share/classes/com/sun/imageio/plugins/gif/GIFImageReader.java @@ -504,7 +504,7 @@ public class GIFImageReader extends ImageReader { } // Found position of metadata for image 0 - imageStartPosition.add(new Long(stream.getStreamPosition())); + imageStartPosition.add(Long.valueOf(stream.getStreamPosition())); } catch (IOException e) { throw new IIOException("I/O error reading header!", e); } diff --git a/jdk/src/share/classes/com/sun/imageio/plugins/gif/GIFWritableImageMetadata.java b/jdk/src/share/classes/com/sun/imageio/plugins/gif/GIFWritableImageMetadata.java index 66d647f6856..58d819f11ea 100644 --- a/jdk/src/share/classes/com/sun/imageio/plugins/gif/GIFWritableImageMetadata.java +++ b/jdk/src/share/classes/com/sun/imageio/plugins/gif/GIFWritableImageMetadata.java @@ -98,7 +98,7 @@ class GIFWritableImageMetadata extends GIFImageMetadata { try { return data.getBytes("ISO-8859-1"); } catch (UnsupportedEncodingException e) { - return (new String("")).getBytes(); + return "".getBytes(); } } diff --git a/jdk/src/share/classes/com/sun/java/swing/plaf/gtk/GTKColorChooserPanel.java b/jdk/src/share/classes/com/sun/java/swing/plaf/gtk/GTKColorChooserPanel.java index f5b671e7cd4..ba1c8da7958 100644 --- a/jdk/src/share/classes/com/sun/java/swing/plaf/gtk/GTKColorChooserPanel.java +++ b/jdk/src/share/classes/com/sun/java/swing/plaf/gtk/GTKColorChooserPanel.java @@ -328,7 +328,7 @@ class GTKColorChooserPanel extends AbstractColorChooserPanel implements setHSB(hue, saturation, brightness); if (update) { settingColor = true; - hueSpinner.setValue(new Integer((int)(hue * 360))); + hueSpinner.setValue(Integer.valueOf((int)(hue * 360))); settingColor = false; } } @@ -376,8 +376,8 @@ class GTKColorChooserPanel extends AbstractColorChooserPanel implements setHSB(hue, s, b); if (update) { settingColor = true; - saturationSpinner.setValue(new Integer((int)(s * 255))); - valueSpinner.setValue(new Integer((int)(b * 255))); + saturationSpinner.setValue(Integer.valueOf((int)(s * 255))); + valueSpinner.setValue(Integer.valueOf((int)(b * 255))); settingColor = false; } } @@ -391,9 +391,9 @@ class GTKColorChooserPanel extends AbstractColorChooserPanel implements setColor(color, false, true, true); settingColor = true; - hueSpinner.setValue(new Integer((int)(hue * 360))); - saturationSpinner.setValue(new Integer((int)(saturation * 255))); - valueSpinner.setValue(new Integer((int)(brightness * 255))); + hueSpinner.setValue(Integer.valueOf((int)(hue * 360))); + saturationSpinner.setValue(Integer.valueOf((int)(saturation * 255))); + valueSpinner.setValue(Integer.valueOf((int)(brightness * 255))); settingColor = false; } @@ -409,9 +409,9 @@ class GTKColorChooserPanel extends AbstractColorChooserPanel implements setColor(color, false, false, true); settingColor = true; - redSpinner.setValue(new Integer(color.getRed())); - greenSpinner.setValue(new Integer(color.getGreen())); - blueSpinner.setValue(new Integer(color.getBlue())); + redSpinner.setValue(Integer.valueOf(color.getRed())); + greenSpinner.setValue(Integer.valueOf(color.getGreen())); + blueSpinner.setValue(Integer.valueOf(color.getBlue())); settingColor = false; } @@ -454,13 +454,13 @@ class GTKColorChooserPanel extends AbstractColorChooserPanel implements colorNameTF.setText("#" + hexString.substring(1)); if (updateSpinners) { - redSpinner.setValue(new Integer(color.getRed())); - greenSpinner.setValue(new Integer(color.getGreen())); - blueSpinner.setValue(new Integer(color.getBlue())); + redSpinner.setValue(Integer.valueOf(color.getRed())); + greenSpinner.setValue(Integer.valueOf(color.getGreen())); + blueSpinner.setValue(Integer.valueOf(color.getBlue())); - hueSpinner.setValue(new Integer((int)(hue * 360))); - saturationSpinner.setValue(new Integer((int)(saturation * 255))); - valueSpinner.setValue(new Integer((int)(brightness * 255))); + hueSpinner.setValue(Integer.valueOf((int)(hue * 360))); + saturationSpinner.setValue(Integer.valueOf((int)(saturation * 255))); + valueSpinner.setValue(Integer.valueOf((int)(brightness * 255))); } settingColor = false; } diff --git a/jdk/src/share/classes/com/sun/java/swing/plaf/gtk/GTKLookAndFeel.java b/jdk/src/share/classes/com/sun/java/swing/plaf/gtk/GTKLookAndFeel.java index b4f435798a1..3c565604174 100644 --- a/jdk/src/share/classes/com/sun/java/swing/plaf/gtk/GTKLookAndFeel.java +++ b/jdk/src/share/classes/com/sun/java/swing/plaf/gtk/GTKLookAndFeel.java @@ -336,7 +336,7 @@ public class GTKLookAndFeel extends SynthLookAndFeel { // populate the table with the values from basic. super.initComponentDefaults(table); - Integer zero = new Integer(0); + Integer zero = Integer.valueOf(0); Object zeroBorder = new sun.swing.SwingLazyValue( "javax.swing.plaf.BorderUIResource$EmptyBorderUIResource", new Object[] {zero, zero, zero, zero}); @@ -371,7 +371,7 @@ public class GTKLookAndFeel extends SynthLookAndFeel { int vProgWidth = 22 - (progXThickness * 2); int vProgHeight = 80 - (progYThickness * 2); - Integer caretBlinkRate = new Integer(500); + Integer caretBlinkRate = Integer.valueOf(500); Insets zeroInsets = new InsetsUIResource(0, 0, 0, 0); Double defaultCaretAspectRatio = new Double(0.025); @@ -540,7 +540,7 @@ public class GTKLookAndFeel extends SynthLookAndFeel { } Object[] defaults = new Object[] { - "ArrowButton.size", new Integer(13), + "ArrowButton.size", Integer.valueOf(13), "Button.defaultButtonFollowsFocus", Boolean.FALSE, @@ -893,8 +893,8 @@ public class GTKLookAndFeel extends SynthLookAndFeel { "ScrollBar.squareButtons", Boolean.FALSE, - "ScrollBar.thumbHeight", new Integer(14), - "ScrollBar.width", new Integer(16), + "ScrollBar.thumbHeight", Integer.valueOf(14), + "ScrollBar.width", Integer.valueOf(16), "ScrollBar.minimumThumbSize", new Dimension(8, 8), "ScrollBar.maximumThumbSize", new Dimension(4096, 4096), "ScrollBar.allowsAbsolutePositioning", Boolean.TRUE, @@ -954,12 +954,12 @@ public class GTKLookAndFeel extends SynthLookAndFeel { "Separator.insets", zeroInsets, - "Separator.thickness", new Integer(2), + "Separator.thickness", Integer.valueOf(2), "Slider.paintValue", Boolean.TRUE, - "Slider.thumbWidth", new Integer(30), - "Slider.thumbHeight", new Integer(14), + "Slider.thumbWidth", Integer.valueOf(30), + "Slider.thumbHeight", Integer.valueOf(14), "Slider.focusInputMap", new UIDefaults.LazyInputMap(new Object[] { "RIGHT", "positiveUnitIncrement", @@ -1013,9 +1013,9 @@ public class GTKLookAndFeel extends SynthLookAndFeel { }), - "SplitPane.size", new Integer(7), - "SplitPane.oneTouchOffset", new Integer(2), - "SplitPane.oneTouchButtonSize", new Integer(5), + "SplitPane.size", Integer.valueOf(7), + "SplitPane.oneTouchOffset", Integer.valueOf(2), + "SplitPane.oneTouchButtonSize", Integer.valueOf(5), "SplitPane.supportsOneTouchButtons", Boolean.FALSE, @@ -1223,13 +1223,13 @@ public class GTKLookAndFeel extends SynthLookAndFeel { "ToolTip.font", new FontLazyValue(Region.TOOL_TIP), - "Tree.padding", new Integer(4), + "Tree.padding", Integer.valueOf(4), "Tree.background", tableBg, "Tree.drawHorizontalLines", Boolean.FALSE, "Tree.drawVerticalLines", Boolean.FALSE, - "Tree.rowHeight", new Integer(-1), + "Tree.rowHeight", Integer.valueOf(-1), "Tree.scrollsOnExpand", Boolean.FALSE, - "Tree.expanderSize", new Integer(10), + "Tree.expanderSize", Integer.valueOf(10), "Tree.repaintWholeRow", Boolean.TRUE, "Tree.closedIcon", null, "Tree.leafIcon", null, @@ -1240,8 +1240,8 @@ public class GTKLookAndFeel extends SynthLookAndFeel { "Tree.collapsedIcon", new GTKStyle.GTKLazyValue( "com.sun.java.swing.plaf.gtk.GTKIconFactory", "getTreeCollapsedIcon"), - "Tree.leftChildIndent", new Integer(2), - "Tree.rightChildIndent", new Integer(12), + "Tree.leftChildIndent", Integer.valueOf(2), + "Tree.rightChildIndent", Integer.valueOf(12), "Tree.scrollsHorizontallyAndVertically", Boolean.FALSE, "Tree.drawsFocusBorder", Boolean.TRUE, "Tree.focusInputMap", diff --git a/jdk/src/share/classes/com/sun/java/swing/plaf/gtk/GTKStyle.java b/jdk/src/share/classes/com/sun/java/swing/plaf/gtk/GTKStyle.java index 0d008907248..4f6e42c784c 100644 --- a/jdk/src/share/classes/com/sun/java/swing/plaf/gtk/GTKStyle.java +++ b/jdk/src/share/classes/com/sun/java/swing/plaf/gtk/GTKStyle.java @@ -851,7 +851,7 @@ class GTKStyle extends SynthStyle implements GTKConstants { int focusLineWidth = getClassSpecificIntValue(context, "focus-line-width", 0); if (value == null && focusLineWidth > 0) { - value = new Integer(16 + 2 * focusLineWidth); + value = Integer.valueOf(16 + 2 * focusLineWidth); } } return value; @@ -975,12 +975,12 @@ class GTKStyle extends SynthStyle implements GTKConstants { private static void initIconTypeMap() { ICON_TYPE_MAP = new HashMap(); - ICON_TYPE_MAP.put("gtk-menu", new Integer(1)); - ICON_TYPE_MAP.put("gtk-small-toolbar", new Integer(2)); - ICON_TYPE_MAP.put("gtk-large-toolbar", new Integer(3)); - ICON_TYPE_MAP.put("gtk-button", new Integer(4)); - ICON_TYPE_MAP.put("gtk-dnd", new Integer(5)); - ICON_TYPE_MAP.put("gtk-dialog", new Integer(6)); + ICON_TYPE_MAP.put("gtk-menu", Integer.valueOf(1)); + ICON_TYPE_MAP.put("gtk-small-toolbar", Integer.valueOf(2)); + ICON_TYPE_MAP.put("gtk-large-toolbar", Integer.valueOf(3)); + ICON_TYPE_MAP.put("gtk-button", Integer.valueOf(4)); + ICON_TYPE_MAP.put("gtk-dnd", Integer.valueOf(5)); + ICON_TYPE_MAP.put("gtk-dialog", Integer.valueOf(6)); } } diff --git a/jdk/src/share/classes/com/sun/java/swing/plaf/gtk/Metacity.java b/jdk/src/share/classes/com/sun/java/swing/plaf/gtk/Metacity.java index 274ac510c0b..e6117989134 100644 --- a/jdk/src/share/classes/com/sun/java/swing/plaf/gtk/Metacity.java +++ b/jdk/src/share/classes/com/sun/java/swing/plaf/gtk/Metacity.java @@ -178,7 +178,7 @@ class Metacity implements SynthConstants { name = child.getNodeName(); Object value = null; if ("distance".equals(name)) { - value = new Integer(getIntAttr(child, "value", 0)); + value = Integer.valueOf(getIntAttr(child, "value", 0)); } else if ("border".equals(name)) { value = new Insets(getIntAttr(child, "top", 0), getIntAttr(child, "left", 0), @@ -808,7 +808,7 @@ class Metacity implements SynthConstants { protected void setFrameGeometry(JComponent titlePane, Map gm) { this.frameGeometry = gm; if (getInt("top_height") == 0 && titlePane != null) { - gm.put("top_height", new Integer(titlePane.getHeight())); + gm.put("top_height", Integer.valueOf(titlePane.getHeight())); } } diff --git a/jdk/src/share/classes/com/sun/java/swing/plaf/motif/MotifLookAndFeel.java b/jdk/src/share/classes/com/sun/java/swing/plaf/motif/MotifLookAndFeel.java index 63994ff6732..995d195c34f 100644 --- a/jdk/src/share/classes/com/sun/java/swing/plaf/motif/MotifLookAndFeel.java +++ b/jdk/src/share/classes/com/sun/java/swing/plaf/motif/MotifLookAndFeel.java @@ -567,7 +567,7 @@ public class MotifLookAndFeel extends BasicLookAndFeel "ProgressBar.selectionBackground", table.get("controlText"), "ProgressBar.border", loweredBevelBorder, "ProgressBar.cellLength", new Integer(6), - "ProgressBar.cellSpacing", new Integer(0), + "ProgressBar.cellSpacing", Integer.valueOf(0), // Buttons "Button.margin", new InsetsUIResource(2, 4, 2, 4), @@ -859,7 +859,7 @@ public class MotifLookAndFeel extends BasicLookAndFeel "SplitPane.background", table.get("control"), "SplitPane.highlight", table.get("controlHighlight"), "SplitPane.shadow", table.get("controlShadow"), - "SplitPane.dividerSize", new Integer(20), + "SplitPane.dividerSize", Integer.valueOf(20), "SplitPane.activeThumb", table.get("activeCaptionBorder"), "SplitPane.ancestorInputMap", new UIDefaults.LazyInputMap(new Object[] { @@ -1160,7 +1160,7 @@ public class MotifLookAndFeel extends BasicLookAndFeel }), "TextField.caretForeground", black, - "TextField.caretBlinkRate", new Integer(500), + "TextField.caretBlinkRate", Integer.valueOf(500), "TextField.inactiveForeground", table.get("textInactiveText"), "TextField.selectionBackground", table.get("textHighlight"), "TextField.selectionForeground", table.get("textHighlightText"), @@ -1171,7 +1171,7 @@ public class MotifLookAndFeel extends BasicLookAndFeel "TextField.focusInputMap", fieldInputMap, "PasswordField.caretForeground", black, - "PasswordField.caretBlinkRate", new Integer(500), + "PasswordField.caretBlinkRate", Integer.valueOf(500), "PasswordField.inactiveForeground", table.get("textInactiveText"), "PasswordField.selectionBackground", table.get("textHighlight"), "PasswordField.selectionForeground", table.get("textHighlightText"), @@ -1182,7 +1182,7 @@ public class MotifLookAndFeel extends BasicLookAndFeel "PasswordField.focusInputMap", passwordInputMap, "TextArea.caretForeground", black, - "TextArea.caretBlinkRate", new Integer(500), + "TextArea.caretBlinkRate", Integer.valueOf(500), "TextArea.inactiveForeground", table.get("textInactiveText"), "TextArea.selectionBackground", table.get("textHighlight"), "TextArea.selectionForeground", table.get("textHighlightText"), @@ -1193,7 +1193,7 @@ public class MotifLookAndFeel extends BasicLookAndFeel "TextArea.focusInputMap", multilineInputMap, "TextPane.caretForeground", black, - "TextPane.caretBlinkRate", new Integer(500), + "TextPane.caretBlinkRate", Integer.valueOf(500), "TextPane.inactiveForeground", table.get("textInactiveText"), "TextPane.selectionBackground", lightGray, "TextPane.selectionForeground", table.get("textHighlightText"), @@ -1204,7 +1204,7 @@ public class MotifLookAndFeel extends BasicLookAndFeel "TextPane.focusInputMap", multilineInputMap, "EditorPane.caretForeground", red, - "EditorPane.caretBlinkRate", new Integer(500), + "EditorPane.caretBlinkRate", Integer.valueOf(500), "EditorPane.inactiveForeground", table.get("textInactiveText"), "EditorPane.selectionBackground", lightGray, "EditorPane.selectionForeground", table.get("textHighlightText"), diff --git a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsLookAndFeel.java b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsLookAndFeel.java index 3977b4d1de6..9af41fc39c8 100644 --- a/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsLookAndFeel.java +++ b/jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsLookAndFeel.java @@ -299,9 +299,9 @@ public class WindowsLookAndFeel extends BasicLookAndFeel initResourceBundle(table); // *** Shared Fonts - Integer twelve = new Integer(12); - Integer fontPlain = new Integer(Font.PLAIN); - Integer fontBold = new Integer(Font.BOLD); + Integer twelve = Integer.valueOf(12); + Integer fontPlain = Integer.valueOf(Font.PLAIN); + Integer fontBold = Integer.valueOf(Font.BOLD); Object dialogPlain12 = new SwingLazyValue( "javax.swing.plaf.FontUIResource", @@ -522,19 +522,19 @@ public class WindowsLookAndFeel extends BasicLookAndFeel toolkit); Object WindowBorderWidth = new DesktopProperty( "win.frame.sizingBorderWidth", - new Integer(1), + Integer.valueOf(1), toolkit); Object TitlePaneHeight = new DesktopProperty( "win.frame.captionHeight", - new Integer(18), + Integer.valueOf(18), toolkit); Object TitleButtonWidth = new DesktopProperty( "win.frame.captionButtonWidth", - new Integer(16), + Integer.valueOf(16), toolkit); Object TitleButtonHeight = new DesktopProperty( "win.frame.captionButtonHeight", - new Integer(16), + Integer.valueOf(16), toolkit); Object InactiveTextColor = new DesktopProperty( "win.text.grayedTextColor", @@ -567,7 +567,7 @@ public class WindowsLookAndFeel extends BasicLookAndFeel Object IconFont = ControlFont; Object scrollBarWidth = new DesktopProperty("win.scrollbar.width", - new Integer(16), toolkit); + Integer.valueOf(16), toolkit); Object menuBarHeight = new DesktopProperty("win.menu.height", null, toolkit); @@ -673,12 +673,12 @@ public class WindowsLookAndFeel extends BasicLookAndFeel "Button.disabledForeground", InactiveTextColor, "Button.disabledShadow", ControlHighlightColor, "Button.focus", black, - "Button.dashedRectGapX", new XPValue(new Integer(3), new Integer(5)), - "Button.dashedRectGapY", new XPValue(new Integer(3), new Integer(4)), - "Button.dashedRectGapWidth", new XPValue(new Integer(6), new Integer(10)), - "Button.dashedRectGapHeight", new XPValue(new Integer(6), new Integer(8)), - "Button.textShiftOffset", new XPValue(new Integer(0), - new Integer(1)), + "Button.dashedRectGapX", new XPValue(Integer.valueOf(3), Integer.valueOf(5)), + "Button.dashedRectGapY", new XPValue(Integer.valueOf(3), Integer.valueOf(4)), + "Button.dashedRectGapWidth", new XPValue(Integer.valueOf(6), Integer.valueOf(10)), + "Button.dashedRectGapHeight", new XPValue(Integer.valueOf(6), Integer.valueOf(8)), + "Button.textShiftOffset", new XPValue(Integer.valueOf(0), + Integer.valueOf(1)), // W2K keyboard navigation hidding. "Button.showMnemonics", showMnemonics, "Button.focusInputMap", @@ -780,7 +780,7 @@ public class WindowsLookAndFeel extends BasicLookAndFeel }), // DesktopIcon - "DesktopIcon.width", new Integer(160), + "DesktopIcon.width", Integer.valueOf(160), "EditorPane.font", ControlFont, "EditorPane.background", WindowBackgroundColor, @@ -814,9 +814,9 @@ public class WindowsLookAndFeel extends BasicLookAndFeel "icons/NewFolder.gif"), "FileChooser.useSystemExtensionHiding", Boolean.TRUE, - "FileChooser.lookInLabelMnemonic", new Integer(KeyEvent.VK_I), - "FileChooser.fileNameLabelMnemonic", new Integer(KeyEvent.VK_N), - "FileChooser.filesOfTypeLabelMnemonic", new Integer(KeyEvent.VK_T), + "FileChooser.lookInLabelMnemonic", Integer.valueOf(KeyEvent.VK_I), + "FileChooser.fileNameLabelMnemonic", Integer.valueOf(KeyEvent.VK_N), + "FileChooser.filesOfTypeLabelMnemonic", Integer.valueOf(KeyEvent.VK_T), "FileChooser.usesSingleFilePane", Boolean.TRUE, "FileChooser.noPlacesBar", new DesktopProperty("win.comdlg.noPlacesBar", Boolean.FALSE, toolkit), @@ -1021,10 +1021,10 @@ public class WindowsLookAndFeel extends BasicLookAndFeel "Menu.selectionBackground", SelectionBackgroundColor, "Menu.acceleratorForeground", MenuTextColor, "Menu.acceleratorSelectionForeground", SelectionTextColor, - "Menu.menuPopupOffsetX", new Integer(0), - "Menu.menuPopupOffsetY", new Integer(0), - "Menu.submenuPopupOffsetX", new Integer(-4), - "Menu.submenuPopupOffsetY", new Integer(-3), + "Menu.menuPopupOffsetX", Integer.valueOf(0), + "Menu.menuPopupOffsetY", Integer.valueOf(0), + "Menu.submenuPopupOffsetX", Integer.valueOf(-4), + "Menu.submenuPopupOffsetY", Integer.valueOf(-3), "Menu.crossMenuMnemonic", Boolean.FALSE, "Menu.preserveTopLevelSelection", Boolean.TRUE, @@ -1184,8 +1184,8 @@ public class WindowsLookAndFeel extends BasicLookAndFeel "ProgressBar.highlight", ControlHighlightColor, "ProgressBar.selectionForeground", ControlBackgroundColor, "ProgressBar.selectionBackground", SelectionBackgroundColor, - "ProgressBar.cellLength", new Integer(7), - "ProgressBar.cellSpacing", new Integer(2), + "ProgressBar.cellLength", Integer.valueOf(7), + "ProgressBar.cellSpacing", Integer.valueOf(2), "ProgressBar.indeterminateInsets", new Insets(3, 3, 3, 3), // *** RootPane. @@ -1292,7 +1292,7 @@ public class WindowsLookAndFeel extends BasicLookAndFeel "SplitPane.highlight", ControlHighlightColor, "SplitPane.shadow", ControlShadowColor, "SplitPane.darkShadow", ControlDarkShadowColor, - "SplitPane.dividerSize", new Integer(5), + "SplitPane.dividerSize", Integer.valueOf(5), "SplitPane.ancestorInputMap", new UIDefaults.LazyInputMap(new Object[] { "UP", "negativeIncrement", @@ -1496,7 +1496,7 @@ public class WindowsLookAndFeel extends BasicLookAndFeel "ToggleButton.light", ControlLightColor, "ToggleButton.highlight", ControlHighlightColor, "ToggleButton.focus", ControlTextColor, - "ToggleButton.textShiftOffset", new Integer(1), + "ToggleButton.textShiftOffset", Integer.valueOf(1), "ToggleButton.focusInputMap", new UIDefaults.LazyInputMap(new Object[] { "SPACE", "pressed", @@ -1548,8 +1548,8 @@ public class WindowsLookAndFeel extends BasicLookAndFeel "Tree.background", WindowBackgroundColor, "Tree.foreground", WindowTextColor, "Tree.hash", gray, - "Tree.leftChildIndent", new Integer(8), - "Tree.rightChildIndent", new Integer(11), + "Tree.leftChildIndent", Integer.valueOf(8), + "Tree.rightChildIndent", Integer.valueOf(11), "Tree.textForeground", WindowTextColor, "Tree.textBackground", WindowBackgroundColor, "Tree.selectionForeground", SelectionTextColor, @@ -2488,18 +2488,18 @@ public class WindowsLookAndFeel extends BasicLookAndFeel private int direction; XPDLUValue(int xpdlu, int classicdlu, int direction) { - super(new Integer(xpdlu), new Integer(classicdlu)); + super(Integer.valueOf(xpdlu), Integer.valueOf(classicdlu)); this.direction = direction; } public Object getXPValue(UIDefaults table) { int px = dluToPixels(((Integer)xpValue).intValue(), direction); - return new Integer(px); + return Integer.valueOf(px); } public Object getClassicValue(UIDefaults table) { int px = dluToPixels(((Integer)classicValue).intValue(), direction); - return new Integer(px); + return Integer.valueOf(px); } } diff --git a/jdk/src/share/classes/java/awt/Button.java b/jdk/src/share/classes/java/awt/Button.java index 46d0d072424..fcb33ddecc2 100644 --- a/jdk/src/share/classes/java/awt/Button.java +++ b/jdk/src/share/classes/java/awt/Button.java @@ -597,7 +597,7 @@ public class Button extends Component implements Accessible { public String getAccessibleActionDescription(int i) { if (i == 0) { // [[[PENDING: WDW -- need to provide a localized string]]] - return new String("click"); + return "click"; } else { return null; } diff --git a/jdk/src/share/classes/java/awt/MenuItem.java b/jdk/src/share/classes/java/awt/MenuItem.java index 899cab485ee..54756b8f488 100644 --- a/jdk/src/share/classes/java/awt/MenuItem.java +++ b/jdk/src/share/classes/java/awt/MenuItem.java @@ -847,7 +847,7 @@ public class MenuItem extends MenuComponent implements Accessible { public String getAccessibleActionDescription(int i) { if (i == 0) { // [[[PENDING: WDW -- need to provide a localized string]]] - return new String("click"); + return "click"; } else { return null; } diff --git a/jdk/src/share/classes/java/awt/datatransfer/SystemFlavorMap.java b/jdk/src/share/classes/java/awt/datatransfer/SystemFlavorMap.java index 77eb2bcec61..57936eb6045 100644 --- a/jdk/src/share/classes/java/awt/datatransfer/SystemFlavorMap.java +++ b/jdk/src/share/classes/java/awt/datatransfer/SystemFlavorMap.java @@ -298,7 +298,7 @@ public final class SystemFlavorMap implements FlavorMap, FlavorTable { while (continueLine(line)) { String nextLine = in.readLine(); if (nextLine == null) { - nextLine = new String(""); + nextLine = ""; } String loppedLine = line.substring(0, line.length() - 1); @@ -313,7 +313,7 @@ public final class SystemFlavorMap implements FlavorMap, FlavorTable { } nextLine = nextLine.substring(startIndex, nextLine.length()); - line = new String(loppedLine+nextLine); + line = loppedLine+nextLine; } // Find start of key diff --git a/jdk/src/share/classes/java/awt/image/BufferedImage.java b/jdk/src/share/classes/java/awt/image/BufferedImage.java index 763fc31df69..e5b77bec510 100644 --- a/jdk/src/share/classes/java/awt/image/BufferedImage.java +++ b/jdk/src/share/classes/java/awt/image/BufferedImage.java @@ -1210,9 +1210,9 @@ public class BufferedImage extends java.awt.Image * BufferedImage. */ public String toString() { - return new String("BufferedImage@"+Integer.toHexString(hashCode()) - +": type = "+imageType - +" "+colorModel+" "+raster); + return "BufferedImage@"+Integer.toHexString(hashCode()) + +": type = "+imageType + +" "+colorModel+" "+raster; } /** diff --git a/jdk/src/share/classes/java/text/DictionaryBasedBreakIterator.java b/jdk/src/share/classes/java/text/DictionaryBasedBreakIterator.java index 4a598155496..dac78aeda4b 100644 --- a/jdk/src/share/classes/java/text/DictionaryBasedBreakIterator.java +++ b/jdk/src/share/classes/java/text/DictionaryBasedBreakIterator.java @@ -384,7 +384,7 @@ class DictionaryBasedBreakIterator extends RuleBasedBreakIterator { // on the last character of a legal word. Push that position onto // the possible-break-positions stack if (dictionary.getNextState(state, 0) == -1) { - possibleBreakPositions.push(new Integer(text.getIndex())); + possibleBreakPositions.push(Integer.valueOf(text.getIndex())); } // look up the new state to transition to in the dictionary @@ -395,7 +395,7 @@ class DictionaryBasedBreakIterator extends RuleBasedBreakIterator { // and we've successfully traversed the whole range. Drop out // of the loop. if (state == -1) { - currentBreakPositions.push(new Integer(text.getIndex())); + currentBreakPositions.push(Integer.valueOf(text.getIndex())); break; } @@ -496,7 +496,7 @@ class DictionaryBasedBreakIterator extends RuleBasedBreakIterator { if (!currentBreakPositions.isEmpty()) { currentBreakPositions.pop(); } - currentBreakPositions.push(new Integer(endPos)); + currentBreakPositions.push(Integer.valueOf(endPos)); // create a regular array to hold the break positions and copy // the break positions from the stack to the array (in addition, diff --git a/jdk/src/share/classes/java/text/MessageFormat.java b/jdk/src/share/classes/java/text/MessageFormat.java index b16fefe646e..7f3db05402b 100644 --- a/jdk/src/share/classes/java/text/MessageFormat.java +++ b/jdk/src/share/classes/java/text/MessageFormat.java @@ -1286,7 +1286,7 @@ public class MessageFormat extends Format { characterIterators.add( createAttributedCharacterIterator( subIterator, Field.ARGUMENT, - new Integer(argumentNumber))); + Integer.valueOf(argumentNumber))); last = result.length(); } arg = null; @@ -1296,7 +1296,7 @@ public class MessageFormat extends Format { characterIterators.add( createAttributedCharacterIterator( arg, Field.ARGUMENT, - new Integer(argumentNumber))); + Integer.valueOf(argumentNumber))); last = result.length(); } } diff --git a/jdk/src/share/classes/javax/imageio/stream/ImageInputStreamImpl.java b/jdk/src/share/classes/javax/imageio/stream/ImageInputStreamImpl.java index b6a146c3dfd..a43578f8c66 100644 --- a/jdk/src/share/classes/javax/imageio/stream/ImageInputStreamImpl.java +++ b/jdk/src/share/classes/javax/imageio/stream/ImageInputStreamImpl.java @@ -778,8 +778,8 @@ public abstract class ImageInputStreamImpl implements ImageInputStream { */ public void mark() { try { - markByteStack.push(new Long(getStreamPosition())); - markBitStack.push(new Integer(getBitOffset())); + markByteStack.push(Long.valueOf(getStreamPosition())); + markBitStack.push(Integer.valueOf(getBitOffset())); } catch (IOException e) { } } diff --git a/jdk/src/share/classes/javax/swing/AbstractButton.java b/jdk/src/share/classes/javax/swing/AbstractButton.java index b4d4ae1e29a..6522cef8315 100644 --- a/jdk/src/share/classes/javax/swing/AbstractButton.java +++ b/jdk/src/share/classes/javax/swing/AbstractButton.java @@ -2047,14 +2047,14 @@ public abstract class AbstractButton extends JComponent implements ItemSelectabl null, AccessibleState.SELECTED); accessibleContext.firePropertyChange( AccessibleContext.ACCESSIBLE_VALUE_PROPERTY, - new Integer(0), new Integer(1)); + Integer.valueOf(0), Integer.valueOf(1)); } else { accessibleContext.firePropertyChange( AccessibleContext.ACCESSIBLE_STATE_PROPERTY, AccessibleState.SELECTED, null); accessibleContext.firePropertyChange( AccessibleContext.ACCESSIBLE_VALUE_PROPERTY, - new Integer(1), new Integer(0)); + Integer.valueOf(1), Integer.valueOf(0)); } } } @@ -2552,9 +2552,9 @@ public abstract class AbstractButton extends JComponent implements ItemSelectabl */ public Number getCurrentAccessibleValue() { if (isSelected()) { - return new Integer(1); + return Integer.valueOf(1); } else { - return new Integer(0); + return Integer.valueOf(0); } } @@ -2583,7 +2583,7 @@ public abstract class AbstractButton extends JComponent implements ItemSelectabl * @return an Integer of 0. */ public Number getMinimumAccessibleValue() { - return new Integer(0); + return Integer.valueOf(0); } /** @@ -2592,7 +2592,7 @@ public abstract class AbstractButton extends JComponent implements ItemSelectabl * @return An Integer of 1. */ public Number getMaximumAccessibleValue() { - return new Integer(1); + return Integer.valueOf(1); } diff --git a/jdk/src/share/classes/javax/swing/DebugGraphicsInfo.java b/jdk/src/share/classes/javax/swing/DebugGraphicsInfo.java index 72bf9445bd0..635be42475e 100644 --- a/jdk/src/share/classes/javax/swing/DebugGraphicsInfo.java +++ b/jdk/src/share/classes/javax/swing/DebugGraphicsInfo.java @@ -49,7 +49,7 @@ class DebugGraphicsInfo { componentToDebug = new Hashtable(); } if (debug > 0) { - componentToDebug.put(component, new Integer(debug)); + componentToDebug.put(component, Integer.valueOf(debug)); } else { componentToDebug.remove(component); } diff --git a/jdk/src/share/classes/javax/swing/JInternalFrame.java b/jdk/src/share/classes/javax/swing/JInternalFrame.java index cc8480fc455..67d39b0cbb7 100644 --- a/jdk/src/share/classes/javax/swing/JInternalFrame.java +++ b/jdk/src/share/classes/javax/swing/JInternalFrame.java @@ -1285,7 +1285,7 @@ public class JInternalFrame extends JComponent implements * description: Specifies what desktop layer is used. */ public void setLayer(int layer) { - this.setLayer(new Integer(layer)); + this.setLayer(Integer.valueOf(layer)); } /** @@ -2092,7 +2092,7 @@ public class JInternalFrame extends JComponent implements * have a value */ public Number getCurrentAccessibleValue() { - return new Integer(getLayer()); + return Integer.valueOf(getLayer()); } /** @@ -2116,7 +2116,7 @@ public class JInternalFrame extends JComponent implements * have a minimum value */ public Number getMinimumAccessibleValue() { - return new Integer(Integer.MIN_VALUE); + return Integer.MIN_VALUE; } /** @@ -2126,7 +2126,7 @@ public class JInternalFrame extends JComponent implements * have a maximum value */ public Number getMaximumAccessibleValue() { - return new Integer(Integer.MAX_VALUE); + return Integer.MAX_VALUE; } } // AccessibleJInternalFrame diff --git a/jdk/src/share/classes/javax/swing/JOptionPane.java b/jdk/src/share/classes/javax/swing/JOptionPane.java index 0591f3dface..130d9f666a0 100644 --- a/jdk/src/share/classes/javax/swing/JOptionPane.java +++ b/jdk/src/share/classes/javax/swing/JOptionPane.java @@ -1512,7 +1512,7 @@ public class JOptionPane extends JComponent implements Accessible iFrame.putClientProperty("JInternalFrame.frameType", "optionDialog"); iFrame.putClientProperty("JInternalFrame.messageType", - new Integer(getMessageType())); + Integer.valueOf(getMessageType())); iFrame.addInternalFrameListener(new InternalFrameAdapter() { public void internalFrameClosing(InternalFrameEvent e) { diff --git a/jdk/src/share/classes/javax/swing/JProgressBar.java b/jdk/src/share/classes/javax/swing/JProgressBar.java index 337f5b118ef..68a6322c39a 100644 --- a/jdk/src/share/classes/javax/swing/JProgressBar.java +++ b/jdk/src/share/classes/javax/swing/JProgressBar.java @@ -775,9 +775,9 @@ public class JProgressBar extends JComponent implements SwingConstants, Accessib accessibleContext.firePropertyChange( AccessibleContext.ACCESSIBLE_VALUE_PROPERTY, (oldModel== null - ? null : new Integer(oldModel.getValue())), + ? null : Integer.valueOf(oldModel.getValue())), (newModel== null - ? null : new Integer(newModel.getValue()))); + ? null : Integer.valueOf(newModel.getValue()))); } if (model != null) { @@ -850,8 +850,8 @@ public class JProgressBar extends JComponent implements SwingConstants, Accessib if (accessibleContext != null) { accessibleContext.firePropertyChange( AccessibleContext.ACCESSIBLE_VALUE_PROPERTY, - new Integer(oldValue), - new Integer(brm.getValue())); + Integer.valueOf(oldValue), + Integer.valueOf(brm.getValue())); } } @@ -1087,7 +1087,7 @@ public class JProgressBar extends JComponent implements SwingConstants, Accessib * @return the current value of this object */ public Number getCurrentAccessibleValue() { - return new Integer(getValue()); + return Integer.valueOf(getValue()); } /** @@ -1110,7 +1110,7 @@ public class JProgressBar extends JComponent implements SwingConstants, Accessib * @return the minimum value of this object */ public Number getMinimumAccessibleValue() { - return new Integer(getMinimum()); + return Integer.valueOf(getMinimum()); } /** @@ -1120,7 +1120,7 @@ public class JProgressBar extends JComponent implements SwingConstants, Accessib */ public Number getMaximumAccessibleValue() { // TIGER - 4422362 - return new Integer(model.getMaximum() - model.getExtent()); + return Integer.valueOf(model.getMaximum() - model.getExtent()); } } // AccessibleJProgressBar diff --git a/jdk/src/share/classes/javax/swing/JScrollBar.java b/jdk/src/share/classes/javax/swing/JScrollBar.java index 0b646ac90b2..2136fe62975 100644 --- a/jdk/src/share/classes/javax/swing/JScrollBar.java +++ b/jdk/src/share/classes/javax/swing/JScrollBar.java @@ -314,7 +314,7 @@ public class JScrollBar extends JComponent implements Adjustable, Accessible BoundedRangeModel oldModel = model; if (model != null) { model.removeChangeListener(fwdAdjustmentEvents); - oldValue = new Integer(model.getValue()); + oldValue = Integer.valueOf(model.getValue()); } model = newModel; if (model != null) { @@ -465,8 +465,8 @@ public class JScrollBar extends JComponent implements Adjustable, Accessible if (accessibleContext != null) { accessibleContext.firePropertyChange( AccessibleContext.ACCESSIBLE_VALUE_PROPERTY, - new Integer(oldValue), - new Integer(m.getValue())); + Integer.valueOf(oldValue), + Integer.valueOf(m.getValue())); } } @@ -611,8 +611,8 @@ public class JScrollBar extends JComponent implements Adjustable, Accessible if (accessibleContext != null) { accessibleContext.firePropertyChange( AccessibleContext.ACCESSIBLE_VALUE_PROPERTY, - new Integer(oldValue), - new Integer(m.getValue())); + Integer.valueOf(oldValue), + Integer.valueOf(m.getValue())); } } @@ -880,7 +880,7 @@ public class JScrollBar extends JComponent implements Adjustable, Accessible * @return The current value of this object. */ public Number getCurrentAccessibleValue() { - return new Integer(getValue()); + return Integer.valueOf(getValue()); } /** @@ -903,7 +903,7 @@ public class JScrollBar extends JComponent implements Adjustable, Accessible * @return The minimum value of this object. */ public Number getMinimumAccessibleValue() { - return new Integer(getMinimum()); + return Integer.valueOf(getMinimum()); } /** diff --git a/jdk/src/share/classes/javax/swing/JSlider.java b/jdk/src/share/classes/javax/swing/JSlider.java index 7a9c4439f24..e1a7909b073 100644 --- a/jdk/src/share/classes/javax/swing/JSlider.java +++ b/jdk/src/share/classes/javax/swing/JSlider.java @@ -485,9 +485,9 @@ public class JSlider extends JComponent implements SwingConstants, Accessible { accessibleContext.firePropertyChange( AccessibleContext.ACCESSIBLE_VALUE_PROPERTY, (oldModel == null - ? null : new Integer(oldModel.getValue())), + ? null : Integer.valueOf(oldModel.getValue())), (newModel == null - ? null : new Integer(newModel.getValue()))); + ? null : Integer.valueOf(newModel.getValue()))); } } @@ -538,8 +538,8 @@ public class JSlider extends JComponent implements SwingConstants, Accessible { if (accessibleContext != null) { accessibleContext.firePropertyChange( AccessibleContext.ACCESSIBLE_VALUE_PROPERTY, - new Integer(oldValue), - new Integer(m.getValue())); + Integer.valueOf(oldValue), + Integer.valueOf(m.getValue())); } } @@ -581,7 +581,7 @@ public class JSlider extends JComponent implements SwingConstants, Accessible { public void setMinimum(int minimum) { int oldMin = getModel().getMinimum(); getModel().setMinimum(minimum); - firePropertyChange( "minimum", new Integer( oldMin ), new Integer( minimum ) ); + firePropertyChange( "minimum", Integer.valueOf( oldMin ), Integer.valueOf( minimum ) ); } @@ -622,7 +622,7 @@ public class JSlider extends JComponent implements SwingConstants, Accessible { public void setMaximum(int maximum) { int oldMax = getModel().getMaximum(); getModel().setMaximum(maximum); - firePropertyChange( "maximum", new Integer( oldMax ), new Integer( maximum ) ); + firePropertyChange( "maximum", Integer.valueOf( oldMax ), Integer.valueOf( maximum ) ); } @@ -989,7 +989,7 @@ public class JSlider extends JComponent implements SwingConstants, Accessible { void createLabels() { for ( int labelIndex = start; labelIndex <= getMaximum(); labelIndex += increment ) { - put( new Integer( labelIndex ), new LabelUIResource( ""+labelIndex, JLabel.CENTER ) ); + put( Integer.valueOf( labelIndex ), new LabelUIResource( ""+labelIndex, JLabel.CENTER ) ); } } } @@ -1463,7 +1463,7 @@ public class JSlider extends JComponent implements SwingConstants, Accessible { * @return The current value of this object. */ public Number getCurrentAccessibleValue() { - return new Integer(getValue()); + return Integer.valueOf(getValue()); } /** @@ -1486,7 +1486,7 @@ public class JSlider extends JComponent implements SwingConstants, Accessible { * @return The minimum value of this object. */ public Number getMinimumAccessibleValue() { - return new Integer(getMinimum()); + return Integer.valueOf(getMinimum()); } /** @@ -1497,7 +1497,7 @@ public class JSlider extends JComponent implements SwingConstants, Accessible { public Number getMaximumAccessibleValue() { // TIGER - 4422362 BoundedRangeModel model = JSlider.this.getModel(); - return new Integer(model.getMaximum() - model.getExtent()); + return Integer.valueOf(model.getMaximum() - model.getExtent()); } } // AccessibleJSlider } diff --git a/jdk/src/share/classes/javax/swing/JSplitPane.java b/jdk/src/share/classes/javax/swing/JSplitPane.java index 22465c4805a..d96a7ee7445 100644 --- a/jdk/src/share/classes/javax/swing/JSplitPane.java +++ b/jdk/src/share/classes/javax/swing/JSplitPane.java @@ -1195,7 +1195,7 @@ public class JSplitPane extends JComponent implements Accessible * @return a localized String describing the value of this object */ public Number getCurrentAccessibleValue() { - return new Integer(getDividerLocation()); + return Integer.valueOf(getDividerLocation()); } @@ -1220,7 +1220,7 @@ public class JSplitPane extends JComponent implements Accessible * @return The minimum value of this object. */ public Number getMinimumAccessibleValue() { - return new Integer(getUI().getMinimumDividerLocation( + return Integer.valueOf(getUI().getMinimumDividerLocation( JSplitPane.this)); } @@ -1231,7 +1231,7 @@ public class JSplitPane extends JComponent implements Accessible * @return The maximum value of this object. */ public Number getMaximumAccessibleValue() { - return new Integer(getUI().getMaximumDividerLocation( + return Integer.valueOf(getUI().getMaximumDividerLocation( JSplitPane.this)); } diff --git a/jdk/src/share/classes/javax/swing/JTabbedPane.java b/jdk/src/share/classes/javax/swing/JTabbedPane.java index defffc711a4..fb058ccaed7 100644 --- a/jdk/src/share/classes/javax/swing/JTabbedPane.java +++ b/jdk/src/share/classes/javax/swing/JTabbedPane.java @@ -967,7 +967,7 @@ public class JTabbedPane extends JComponent // currently no IndexPropertyChangeEvent. Once // IndexPropertyChangeEvents have been added this code should be // modified to use it. - putClientProperty("__index_to_remove__", new Integer(index)); + putClientProperty("__index_to_remove__", Integer.valueOf(index)); /* if the selected tab is after the removal */ if (selected > index) { diff --git a/jdk/src/share/classes/javax/swing/JTable.java b/jdk/src/share/classes/javax/swing/JTable.java index 562208939c9..62485a1c925 100644 --- a/jdk/src/share/classes/javax/swing/JTable.java +++ b/jdk/src/share/classes/javax/swing/JTable.java @@ -7680,7 +7680,7 @@ public class JTable extends JComponent implements TableModelListener, Scrollable */ public Accessible getAccessibleRowDescription(int r) { if (r < 0 || r >= getAccessibleRowCount()) { - throw new IllegalArgumentException(new Integer(r).toString()); + throw new IllegalArgumentException(Integer.toString(r)); } if (rowDescription == null) { return null; @@ -7698,7 +7698,7 @@ public class JTable extends JComponent implements TableModelListener, Scrollable */ public void setAccessibleRowDescription(int r, Accessible a) { if (r < 0 || r >= getAccessibleRowCount()) { - throw new IllegalArgumentException(new Integer(r).toString()); + throw new IllegalArgumentException(Integer.toString(r)); } if (rowDescription == null) { int numRows = getAccessibleRowCount(); @@ -7716,7 +7716,7 @@ public class JTable extends JComponent implements TableModelListener, Scrollable */ public Accessible getAccessibleColumnDescription(int c) { if (c < 0 || c >= getAccessibleColumnCount()) { - throw new IllegalArgumentException(new Integer(c).toString()); + throw new IllegalArgumentException(Integer.toString(c)); } if (columnDescription == null) { return null; @@ -7734,7 +7734,7 @@ public class JTable extends JComponent implements TableModelListener, Scrollable */ public void setAccessibleColumnDescription(int c, Accessible a) { if (c < 0 || c >= getAccessibleColumnCount()) { - throw new IllegalArgumentException(new Integer(c).toString()); + throw new IllegalArgumentException(Integer.toString(c)); } if (columnDescription == null) { int numColumns = getAccessibleColumnCount(); diff --git a/jdk/src/share/classes/javax/swing/JTextArea.java b/jdk/src/share/classes/javax/swing/JTextArea.java index 8f53daf2aca..18e3b45c35b 100644 --- a/jdk/src/share/classes/javax/swing/JTextArea.java +++ b/jdk/src/share/classes/javax/swing/JTextArea.java @@ -267,7 +267,7 @@ public class JTextArea extends JTextComponent { Document doc = getDocument(); if (doc != null) { int old = getTabSize(); - doc.putProperty(PlainDocument.tabSizeAttribute, new Integer(size)); + doc.putProperty(PlainDocument.tabSizeAttribute, Integer.valueOf(size)); firePropertyChange("tabSize", old, size); } } diff --git a/jdk/src/share/classes/javax/swing/SpinnerNumberModel.java b/jdk/src/share/classes/javax/swing/SpinnerNumberModel.java index e9b89b68ecf..fb8521b16f4 100644 --- a/jdk/src/share/classes/javax/swing/SpinnerNumberModel.java +++ b/jdk/src/share/classes/javax/swing/SpinnerNumberModel.java @@ -144,7 +144,7 @@ public class SpinnerNumberModel extends AbstractSpinnerModel implements Serializ * minimum <= value <= maximum */ public SpinnerNumberModel(int value, int minimum, int maximum, int stepSize) { - this(new Integer(value), new Integer(minimum), new Integer(maximum), new Integer(stepSize)); + this(Integer.valueOf(value), Integer.valueOf(minimum), Integer.valueOf(maximum), Integer.valueOf(stepSize)); } @@ -171,7 +171,7 @@ public class SpinnerNumberModel extends AbstractSpinnerModel implements Serializ * stepSize equal to one, and an initial value of zero. */ public SpinnerNumberModel() { - this(new Integer(0), null, null, new Integer(1)); + this(Integer.valueOf(0), null, null, Integer.valueOf(1)); } @@ -333,16 +333,16 @@ public class SpinnerNumberModel extends AbstractSpinnerModel implements Serializ long v = value.longValue() + (stepSize.longValue() * (long)dir); if (value instanceof Long) { - newValue = new Long(v); + newValue = Long.valueOf(v); } else if (value instanceof Integer) { - newValue = new Integer((int)v); + newValue = Integer.valueOf((int)v); } else if (value instanceof Short) { - newValue = new Short((short)v); + newValue = Short.valueOf((short)v); } else { - newValue = new Byte((byte)v); + newValue = Byte.valueOf((byte)v); } } diff --git a/jdk/src/share/classes/javax/swing/TablePrintable.java b/jdk/src/share/classes/javax/swing/TablePrintable.java index ffef3054735..864b550b3c8 100644 --- a/jdk/src/share/classes/javax/swing/TablePrintable.java +++ b/jdk/src/share/classes/javax/swing/TablePrintable.java @@ -215,7 +215,7 @@ class TablePrintable implements Printable { } // to pass the page number when formatting the header and footer text - Object[] pageNumber = new Object[]{new Integer(pageIndex + 1)}; + Object[] pageNumber = new Object[]{Integer.valueOf(pageIndex + 1)}; // fetch the formatted header text, if any String headerText = null; diff --git a/jdk/src/share/classes/javax/swing/plaf/basic/BasicButtonUI.java b/jdk/src/share/classes/javax/swing/plaf/basic/BasicButtonUI.java index fd3d84b2833..d6ad0643c1e 100644 --- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicButtonUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicButtonUI.java @@ -109,7 +109,7 @@ public class BasicButtonUI extends ButtonUI{ LookAndFeel.installProperty(b, "rolloverEnabled", rollover); } - LookAndFeel.installProperty(b, "iconTextGap", new Integer(4)); + LookAndFeel.installProperty(b, "iconTextGap", Integer.valueOf(4)); } protected void installListeners(AbstractButton b) { diff --git a/jdk/src/share/classes/javax/swing/plaf/basic/BasicLookAndFeel.java b/jdk/src/share/classes/javax/swing/plaf/basic/BasicLookAndFeel.java index 77f46be88c1..87ade48cd78 100644 --- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicLookAndFeel.java +++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicLookAndFeel.java @@ -654,7 +654,7 @@ public abstract class BasicLookAndFeel extends LookAndFeel implements Serializab "javax.swing.plaf.basic.BasicIconFactory", "getRadioButtonMenuItemIcon"); - Object menuItemAcceleratorDelimiter = new String("+"); + Object menuItemAcceleratorDelimiter = "+"; // *** OptionPane value objects diff --git a/jdk/src/share/classes/javax/swing/plaf/basic/BasicMenuItemUI.java b/jdk/src/share/classes/javax/swing/plaf/basic/BasicMenuItemUI.java index afe007aeb78..c56a1b49d39 100644 --- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicMenuItemUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicMenuItemUI.java @@ -146,7 +146,7 @@ public class BasicMenuItemUI extends MenuItemUI menuItem.setMargin(UIManager.getInsets(prefix + ".margin")); } - LookAndFeel.installProperty(menuItem, "iconTextGap", new Integer(4)); + LookAndFeel.installProperty(menuItem, "iconTextGap", Integer.valueOf(4)); defaultTextIconGap = menuItem.getIconTextGap(); LookAndFeel.installBorder(menuItem, prefix + ".border"); diff --git a/jdk/src/share/classes/javax/swing/plaf/basic/BasicOptionPaneUI.java b/jdk/src/share/classes/javax/swing/plaf/basic/BasicOptionPaneUI.java index 86e458f3162..5ad6c2b92df 100644 --- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicOptionPaneUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicOptionPaneUI.java @@ -1195,10 +1195,10 @@ public class BasicOptionPaneUI extends OptionPaneUI { if (options == null) { if (optionType == JOptionPane.OK_CANCEL_OPTION && buttonIndex == 1) { - optionPane.setValue(new Integer(2)); + optionPane.setValue(Integer.valueOf(2)); } else { - optionPane.setValue(new Integer(buttonIndex)); + optionPane.setValue(Integer.valueOf(buttonIndex)); } } else { optionPane.setValue(options[buttonIndex]); @@ -1393,7 +1393,7 @@ public class BasicOptionPaneUI extends OptionPaneUI { if (getName() == CLOSE) { JOptionPane optionPane = (JOptionPane)e.getSource(); - optionPane.setValue(new Integer(JOptionPane.CLOSED_OPTION)); + optionPane.setValue(Integer.valueOf(JOptionPane.CLOSED_OPTION)); } } } diff --git a/jdk/src/share/classes/javax/swing/plaf/basic/BasicTabbedPaneUI.java b/jdk/src/share/classes/javax/swing/plaf/basic/BasicTabbedPaneUI.java index 3afdc74d16e..2d0873cfcd2 100644 --- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicTabbedPaneUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicTabbedPaneUI.java @@ -539,7 +539,7 @@ public class BasicTabbedPaneUI extends TabbedPaneUI implements SwingConstants { } mnemonicInputMap.put(KeyStroke.getKeyStroke(mnemonic, Event.ALT_MASK), "setSelectedIndex"); - mnemonicToIndexMap.put(new Integer(mnemonic), new Integer(index)); + mnemonicToIndexMap.put(Integer.valueOf(mnemonic), Integer.valueOf(index)); } /** @@ -2231,7 +2231,7 @@ public class BasicTabbedPaneUI extends TabbedPaneUI implements SwingConstants { mnemonic -= ('a' - 'A'); } Integer index = (Integer)ui.mnemonicToIndexMap. - get(new Integer(mnemonic)); + get(Integer.valueOf(mnemonic)); if (index != null && pane.isEnabledAt(index.intValue())) { pane.setSelectedIndex(index.intValue()); } diff --git a/jdk/src/share/classes/javax/swing/plaf/basic/BasicToolBarUI.java b/jdk/src/share/classes/javax/swing/plaf/basic/BasicToolBarUI.java index c2dff6035c4..e039d1b425b 100644 --- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicToolBarUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicToolBarUI.java @@ -178,7 +178,7 @@ public class BasicToolBarUI extends ToolBarUI implements SwingConstants dragWindow = null; dockingSource = null; - c.putClientProperty( FOCUSED_COMP_INDEX, new Integer( focusedCompIndex ) ); + c.putClientProperty( FOCUSED_COMP_INDEX, Integer.valueOf( focusedCompIndex ) ); } protected void installDefaults( ) diff --git a/jdk/src/share/classes/javax/swing/plaf/metal/MetalLookAndFeel.java b/jdk/src/share/classes/javax/swing/plaf/metal/MetalLookAndFeel.java index af0405f5774..d1f7c05935d 100644 --- a/jdk/src/share/classes/javax/swing/plaf/metal/MetalLookAndFeel.java +++ b/jdk/src/share/classes/javax/swing/plaf/metal/MetalLookAndFeel.java @@ -455,7 +455,7 @@ public class MetalLookAndFeel extends BasicLookAndFeel Insets zeroInsets = new InsetsUIResource(0, 0, 0, 0); - Integer zero = new Integer(0); + Integer zero = Integer.valueOf(0); Object textFieldBorder = new SwingLazyValue("javax.swing.plaf.metal.MetalBorders", @@ -904,7 +904,7 @@ public class MetalLookAndFeel extends BasicLookAndFeel "ProgressBar.selectionBackground", primaryControlDarkShadow, "ProgressBar.border", progressBarBorder, "ProgressBar.cellSpacing", zero, - "ProgressBar.cellLength", new Integer(1), + "ProgressBar.cellLength", Integer.valueOf(1), // Combo Box "ComboBox.background", control, @@ -971,7 +971,7 @@ public class MetalLookAndFeel extends BasicLookAndFeel "DesktopIcon.font", controlTextValue, "DesktopIcon.foreground", controlTextColor, "DesktopIcon.background", control, - "DesktopIcon.width", new Integer(160), + "DesktopIcon.width", Integer.valueOf(160), "Desktop.ancestorInputMap", new UIDefaults.LazyInputMap(new Object[] { diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/SynthArrowButton.java b/jdk/src/share/classes/javax/swing/plaf/synth/SynthArrowButton.java index 51cc619a41b..dd703d0b517 100644 --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthArrowButton.java +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthArrowButton.java @@ -53,7 +53,7 @@ class SynthArrowButton extends JButton implements SwingConstants, UIResource { public void setDirection(int dir) { direction = dir; - putClientProperty("__arrow_direction__", new Integer(dir)); + putClientProperty("__arrow_direction__", Integer.valueOf(dir)); repaint(); } diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/SynthDesktopPaneUI.java b/jdk/src/share/classes/javax/swing/plaf/synth/SynthDesktopPaneUI.java index 88e15c6bcf9..e41fead8add 100644 --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthDesktopPaneUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthDesktopPaneUI.java @@ -96,7 +96,7 @@ class SynthDesktopPaneUI extends BasicDesktopPaneUI implements } taskBar.setBackground(desktop.getBackground()); desktop.add(taskBar, - new Integer(JLayeredPane.PALETTE_LAYER.intValue() + 1)); + Integer.valueOf(JLayeredPane.PALETTE_LAYER.intValue() + 1)); if (desktop.isShowing()) { taskBar.adjustSize(); } diff --git a/jdk/src/share/classes/javax/swing/plaf/synth/SynthSplitPaneUI.java b/jdk/src/share/classes/javax/swing/plaf/synth/SynthSplitPaneUI.java index 84c84de4912..ddbc7ae7e69 100644 --- a/jdk/src/share/classes/javax/swing/plaf/synth/SynthSplitPaneUI.java +++ b/jdk/src/share/classes/javax/swing/plaf/synth/SynthSplitPaneUI.java @@ -127,7 +127,7 @@ class SynthSplitPaneUI extends BasicSplitPaneUI implements if (style != oldStyle) { Object value = style.get(context, "SplitPane.size"); if (value == null) { - value = new Integer(6); + value = Integer.valueOf(6); } LookAndFeel.installProperty(splitPane, "dividerSize", value); diff --git a/jdk/src/share/classes/javax/swing/table/TableColumn.java b/jdk/src/share/classes/javax/swing/table/TableColumn.java index dddcdc3312d..890b855c746 100644 --- a/jdk/src/share/classes/javax/swing/table/TableColumn.java +++ b/jdk/src/share/classes/javax/swing/table/TableColumn.java @@ -281,7 +281,7 @@ public class TableColumn extends Object implements Serializable { private void firePropertyChange(String propertyName, int oldValue, int newValue) { if (oldValue != newValue) { - firePropertyChange(propertyName, new Integer(oldValue), new Integer(newValue)); + firePropertyChange(propertyName, Integer.valueOf(oldValue), Integer.valueOf(newValue)); } } diff --git a/jdk/src/share/classes/javax/swing/text/AbstractDocument.java b/jdk/src/share/classes/javax/swing/text/AbstractDocument.java index d9ca3f387dc..406350a9b10 100644 --- a/jdk/src/share/classes/javax/swing/text/AbstractDocument.java +++ b/jdk/src/share/classes/javax/swing/text/AbstractDocument.java @@ -351,7 +351,7 @@ public abstract class AbstractDocument implements Document, Serializable { * loaded asynchronously */ public void setAsynchronousLoadPriority(int p) { - Integer loadPriority = (p >= 0) ? new Integer(p) : null; + Integer loadPriority = (p >= 0) ? Integer.valueOf(p) : null; putProperty(AbstractDocument.AsyncLoadPriority, loadPriority); } @@ -2675,7 +2675,7 @@ public abstract class AbstractDocument implements Document, Serializable { */ BidiElement(Element parent, int start, int end, int level) { super(parent, new SimpleAttributeSet(), start, end); - addAttribute(StyleConstants.BidiLevel, new Integer(level)); + addAttribute(StyleConstants.BidiLevel, Integer.valueOf(level)); //System.out.println("BidiElement: start = " + start // + " end = " + end + " level = " + level ); } diff --git a/jdk/src/share/classes/javax/swing/text/NumberFormatter.java b/jdk/src/share/classes/javax/swing/text/NumberFormatter.java index c9c47193825..76e3a24029e 100644 --- a/jdk/src/share/classes/javax/swing/text/NumberFormatter.java +++ b/jdk/src/share/classes/javax/swing/text/NumberFormatter.java @@ -173,23 +173,24 @@ public class NumberFormatter extends InternationalFormatter { */ private Object convertValueToValueClass(Object value, Class valueClass) { if (valueClass != null && (value instanceof Number)) { + Number numberValue = (Number)value; if (valueClass == Integer.class) { - return new Integer(((Number)value).intValue()); + return Integer.valueOf(numberValue.intValue()); } else if (valueClass == Long.class) { - return new Long(((Number)value).longValue()); + return Long.valueOf(numberValue.longValue()); } else if (valueClass == Float.class) { - return new Float(((Number)value).floatValue()); + return Float.valueOf(numberValue.floatValue()); } else if (valueClass == Double.class) { - return new Double(((Number)value).doubleValue()); + return Double.valueOf(numberValue.doubleValue()); } else if (valueClass == Byte.class) { - return new Byte(((Number)value).byteValue()); + return Byte.valueOf(numberValue.byteValue()); } else if (valueClass == Short.class) { - return new Short(((Number)value).shortValue()); + return Short.valueOf(numberValue.shortValue()); } } return value; diff --git a/jdk/src/share/classes/javax/swing/text/PlainDocument.java b/jdk/src/share/classes/javax/swing/text/PlainDocument.java index 85ea6c8d262..2a3b6dbea92 100644 --- a/jdk/src/share/classes/javax/swing/text/PlainDocument.java +++ b/jdk/src/share/classes/javax/swing/text/PlainDocument.java @@ -89,7 +89,7 @@ public class PlainDocument extends AbstractDocument { */ public PlainDocument(Content c) { super(c); - putProperty(tabSizeAttribute, new Integer(8)); + putProperty(tabSizeAttribute, Integer.valueOf(8)); defaultRoot = createDefaultRoot(); } diff --git a/jdk/src/share/classes/javax/swing/text/Segment.java b/jdk/src/share/classes/javax/swing/text/Segment.java index 0186c900d4e..55d17a9a5cd 100644 --- a/jdk/src/share/classes/javax/swing/text/Segment.java +++ b/jdk/src/share/classes/javax/swing/text/Segment.java @@ -118,7 +118,7 @@ public class Segment implements Cloneable, CharacterIterator, CharSequence { if (array != null) { return new String(array, offset, count); } - return new String(); + return ""; } // --- CharacterIterator methods ------------------------------------- diff --git a/jdk/src/share/classes/javax/swing/text/StyleConstants.java b/jdk/src/share/classes/javax/swing/text/StyleConstants.java index fa59a783f5d..aaefef88f50 100644 --- a/jdk/src/share/classes/javax/swing/text/StyleConstants.java +++ b/jdk/src/share/classes/javax/swing/text/StyleConstants.java @@ -296,7 +296,7 @@ public class StyleConstants { * @param o the bidi level value */ public static void setBidiLevel(MutableAttributeSet a, int o) { - a.addAttribute(BidiLevel, new Integer(o)); + a.addAttribute(BidiLevel, Integer.valueOf(o)); } /** @@ -386,7 +386,7 @@ public class StyleConstants { * @param s the font size */ public static void setFontSize(MutableAttributeSet a, int s) { - a.addAttribute(FontSize, new Integer(s)); + a.addAttribute(FontSize, Integer.valueOf(s)); } /** @@ -753,7 +753,7 @@ public class StyleConstants { * @param align the alignment value */ public static void setAlignment(MutableAttributeSet a, int align) { - a.addAttribute(Alignment, new Integer(align)); + a.addAttribute(Alignment, Integer.valueOf(align)); } /** diff --git a/jdk/src/share/classes/javax/swing/text/html/AccessibleHTML.java b/jdk/src/share/classes/javax/swing/text/html/AccessibleHTML.java index a4680179c38..d0643bf342c 100644 --- a/jdk/src/share/classes/javax/swing/text/html/AccessibleHTML.java +++ b/jdk/src/share/classes/javax/swing/text/html/AccessibleHTML.java @@ -1970,7 +1970,7 @@ class AccessibleHTML implements Accessible { for (int i = 0; i < nRows; i++) { if (isAccessibleRowSelected(i)) { - vec.addElement(new Integer(i)); + vec.addElement(Integer.valueOf(i)); } } int retval[] = new int[vec.size()]; @@ -1995,7 +1995,7 @@ class AccessibleHTML implements Accessible { for (int i = 0; i < nColumns; i++) { if (isAccessibleColumnSelected(i)) { - vec.addElement(new Integer(i)); + vec.addElement(Integer.valueOf(i)); } } int retval[] = new int[vec.size()]; @@ -2139,7 +2139,7 @@ class AccessibleHTML implements Accessible { private int columnCount = 0; public void addHeader(TableCellElementInfo cellInfo, int rowNumber) { - Integer rowInteger = new Integer(rowNumber); + Integer rowInteger = Integer.valueOf(rowNumber); ArrayList list = (ArrayList)headers.get(rowInteger); if (list == null) { list = new ArrayList(); @@ -2201,7 +2201,7 @@ class AccessibleHTML implements Accessible { } private TableCellElementInfo getElementInfoAt(int r, int c) { - ArrayList list = (ArrayList)headers.get(new Integer(r)); + ArrayList list = (ArrayList)headers.get(Integer.valueOf(r)); if (list != null) { return (TableCellElementInfo)list.get(c); } else { diff --git a/jdk/src/share/classes/javax/swing/text/html/CSS.java b/jdk/src/share/classes/javax/swing/text/html/CSS.java index 40b5977e07a..56cb0fcb26c 100644 --- a/jdk/src/share/classes/javax/swing/text/html/CSS.java +++ b/jdk/src/share/classes/javax/swing/text/html/CSS.java @@ -1099,7 +1099,7 @@ public class CSS implements Serializable { */ static String colorToHex(Color color) { - String colorstr = new String("#"); + String colorstr = "#"; // Red String str = Integer.toHexString(color.getRed()); diff --git a/jdk/src/share/classes/javax/swing/text/html/HTMLEditorKit.java b/jdk/src/share/classes/javax/swing/text/html/HTMLEditorKit.java index 980817d964a..1f5d498f812 100644 --- a/jdk/src/share/classes/javax/swing/text/html/HTMLEditorKit.java +++ b/jdk/src/share/classes/javax/swing/text/html/HTMLEditorKit.java @@ -1899,8 +1899,8 @@ public class HTMLEditorKit extends StyledEditorKit implements Accessible { // assistive technologies listening for such events. comp.getAccessibleContext().firePropertyChange( AccessibleContext.ACCESSIBLE_HYPERTEXT_OFFSET, - new Integer(kit.prevHypertextOffset), - new Integer(e.getDot())); + Integer.valueOf(kit.prevHypertextOffset), + Integer.valueOf(e.getDot())); } } } diff --git a/jdk/src/share/classes/javax/swing/text/html/parser/AttributeList.java b/jdk/src/share/classes/javax/swing/text/html/parser/AttributeList.java index a2d48603da7..3eb1cdb3d90 100644 --- a/jdk/src/share/classes/javax/swing/text/html/parser/AttributeList.java +++ b/jdk/src/share/classes/javax/swing/text/html/parser/AttributeList.java @@ -132,7 +132,7 @@ class AttributeList implements DTDConstants, Serializable { static Hashtable attributeTypes = new Hashtable(); static void defineAttributeType(String nm, int val) { - Integer num = new Integer(val); + Integer num = Integer.valueOf(val); attributeTypes.put(nm, num); attributeTypes.put(num, nm); } @@ -154,11 +154,11 @@ class AttributeList implements DTDConstants, Serializable { defineAttributeType("NUTOKEN", NUTOKEN); defineAttributeType("NUTOKENS", NUTOKENS); - attributeTypes.put("fixed", new Integer(FIXED)); - attributeTypes.put("required", new Integer(REQUIRED)); - attributeTypes.put("current", new Integer(CURRENT)); - attributeTypes.put("conref", new Integer(CONREF)); - attributeTypes.put("implied", new Integer(IMPLIED)); + attributeTypes.put("fixed", Integer.valueOf(FIXED)); + attributeTypes.put("required", Integer.valueOf(REQUIRED)); + attributeTypes.put("current", Integer.valueOf(CURRENT)); + attributeTypes.put("conref", Integer.valueOf(CONREF)); + attributeTypes.put("implied", Integer.valueOf(IMPLIED)); } public static int name2type(String nm) { @@ -167,6 +167,6 @@ class AttributeList implements DTDConstants, Serializable { } public static String type2name(int tp) { - return (String)attributeTypes.get(new Integer(tp)); + return (String)attributeTypes.get(Integer.valueOf(tp)); } } diff --git a/jdk/src/share/classes/javax/swing/text/html/parser/DTD.java b/jdk/src/share/classes/javax/swing/text/html/parser/DTD.java index 3fd48f16b20..9ee714371cb 100644 --- a/jdk/src/share/classes/javax/swing/text/html/parser/DTD.java +++ b/jdk/src/share/classes/javax/swing/text/html/parser/DTD.java @@ -113,7 +113,7 @@ class DTD implements DTDConstants { * ch character */ public Entity getEntity(int ch) { - return (Entity)entityHash.get(new Integer(ch)); + return (Entity)entityHash.get(Integer.valueOf(ch)); } /** @@ -178,7 +178,7 @@ class DTD implements DTDConstants { switch (type & ~GENERAL) { case CDATA: case SDATA: - entityHash.put(new Integer(data[0]), ent); + entityHash.put(Integer.valueOf(data[0]), ent); break; } } diff --git a/jdk/src/share/classes/javax/swing/text/html/parser/Element.java b/jdk/src/share/classes/javax/swing/text/html/parser/Element.java index 54b68618d50..7807b430632 100644 --- a/jdk/src/share/classes/javax/swing/text/html/parser/Element.java +++ b/jdk/src/share/classes/javax/swing/text/html/parser/Element.java @@ -162,10 +162,10 @@ class Element implements DTDConstants, Serializable { static Hashtable contentTypes = new Hashtable(); static { - contentTypes.put("CDATA", new Integer(CDATA)); - contentTypes.put("RCDATA", new Integer(RCDATA)); - contentTypes.put("EMPTY", new Integer(EMPTY)); - contentTypes.put("ANY", new Integer(ANY)); + contentTypes.put("CDATA", Integer.valueOf(CDATA)); + contentTypes.put("RCDATA", Integer.valueOf(RCDATA)); + contentTypes.put("EMPTY", Integer.valueOf(EMPTY)); + contentTypes.put("ANY", Integer.valueOf(ANY)); } public static int name2type(String nm) { diff --git a/jdk/src/share/classes/javax/swing/text/html/parser/Entity.java b/jdk/src/share/classes/javax/swing/text/html/parser/Entity.java index f4a5cb9a73c..01e56125ae8 100644 --- a/jdk/src/share/classes/javax/swing/text/html/parser/Entity.java +++ b/jdk/src/share/classes/javax/swing/text/html/parser/Entity.java @@ -110,15 +110,15 @@ class Entity implements DTDConstants { static Hashtable entityTypes = new Hashtable(); static { - entityTypes.put("PUBLIC", new Integer(PUBLIC)); - entityTypes.put("CDATA", new Integer(CDATA)); - entityTypes.put("SDATA", new Integer(SDATA)); - entityTypes.put("PI", new Integer(PI)); - entityTypes.put("STARTTAG", new Integer(STARTTAG)); - entityTypes.put("ENDTAG", new Integer(ENDTAG)); - entityTypes.put("MS", new Integer(MS)); - entityTypes.put("MD", new Integer(MD)); - entityTypes.put("SYSTEM", new Integer(SYSTEM)); + entityTypes.put("PUBLIC", Integer.valueOf(PUBLIC)); + entityTypes.put("CDATA", Integer.valueOf(CDATA)); + entityTypes.put("SDATA", Integer.valueOf(SDATA)); + entityTypes.put("PI", Integer.valueOf(PI)); + entityTypes.put("STARTTAG", Integer.valueOf(STARTTAG)); + entityTypes.put("ENDTAG", Integer.valueOf(ENDTAG)); + entityTypes.put("MS", Integer.valueOf(MS)); + entityTypes.put("MD", Integer.valueOf(MD)); + entityTypes.put("SYSTEM", Integer.valueOf(SYSTEM)); } /** diff --git a/jdk/src/share/classes/javax/swing/text/html/parser/Parser.java b/jdk/src/share/classes/javax/swing/text/html/parser/Parser.java index 24ba58fffb3..7be7bf5ebf8 100644 --- a/jdk/src/share/classes/javax/swing/text/html/parser/Parser.java +++ b/jdk/src/share/classes/javax/swing/text/html/parser/Parser.java @@ -1842,7 +1842,7 @@ class Parser implements DTDConstants { String elemStr = getString(0); if (elemStr.equals("image")) { - elemStr = new String("img"); + elemStr = "img"; } /* determine if this element is part of the dtd. */ diff --git a/jdk/src/share/classes/javax/swing/text/rtf/RTFAttributes.java b/jdk/src/share/classes/javax/swing/text/rtf/RTFAttributes.java index 2bf54b31b94..fb1b95e9307 100644 --- a/jdk/src/share/classes/javax/swing/text/rtf/RTFAttributes.java +++ b/jdk/src/share/classes/javax/swing/text/rtf/RTFAttributes.java @@ -281,7 +281,7 @@ class RTFAttributes public AssertiveAttribute(int d, Object s, String r, int v) { super(d, s, r); - swingValue = new Integer(v); + swingValue = Integer.valueOf(v); } public boolean set(MutableAttributeSet target) @@ -343,7 +343,7 @@ class RTFAttributes public NumericAttribute(int d, Object s, String r, int ds, int dr) { - this(d, s, r, new Integer(ds), dr, 1f); + this(d, s, r, Integer.valueOf(ds), dr, 1f); } public NumericAttribute(int d, Object s, @@ -377,7 +377,7 @@ class RTFAttributes Number swingValue; if (scale == 1f) - swingValue = new Integer(parameter); + swingValue = Integer.valueOf(parameter); else swingValue = new Float(parameter / scale); target.addAttribute(swingName, swingValue); diff --git a/jdk/src/share/classes/javax/swing/text/rtf/RTFGenerator.java b/jdk/src/share/classes/javax/swing/text/rtf/RTFGenerator.java index 0c7a92f911d..201ba5364ad 100644 --- a/jdk/src/share/classes/javax/swing/text/rtf/RTFGenerator.java +++ b/jdk/src/share/classes/javax/swing/text/rtf/RTFGenerator.java @@ -83,11 +83,7 @@ class RTFGenerator extends Object static public final String defaultFontFamily = "Helvetica"; /* constants so we can avoid allocating objects in inner loops */ - /* these should all be final, but javac seems to be a bit buggy */ - static protected Integer One, Zero; - static protected Boolean False; - static protected Float ZeroPointZero; - static private Object MagicToken; + final static private Object MagicToken; /* An array of character-keyword pairs. This could be done as a dictionary (and lookup would be quicker), but that @@ -98,11 +94,7 @@ class RTFGenerator extends Object static protected CharacterKeywordPair[] textKeywords; static { - One = new Integer(1); - Zero = new Integer(0); - False = Boolean.valueOf(false); MagicToken = new Object(); - ZeroPointZero = new Float(0); Dictionary textKeywordDictionary = RTFReader.textKeywords; Enumeration keys = textKeywordDictionary.keys(); @@ -142,7 +134,7 @@ static public void writeDocument(Document d, OutputStream to) public RTFGenerator(OutputStream to) { colorTable = new Hashtable(); - colorTable.put(defaultRTFColor, new Integer(0)); + colorTable.put(defaultRTFColor, Integer.valueOf(0)); colorCount = 1; fontTable = new Hashtable(); @@ -693,7 +685,7 @@ protected void resetParagraphAttributes(MutableAttributeSet currentAttributes) { writeControlWord("pard"); - currentAttributes.addAttribute(StyleConstants.Alignment, Zero); + currentAttributes.addAttribute(StyleConstants.Alignment, Integer.valueOf(0)); int wordIndex; int wordCount = RTFAttributes.attributes.length; diff --git a/jdk/src/share/classes/javax/swing/tree/DefaultTreeSelectionModel.java b/jdk/src/share/classes/javax/swing/tree/DefaultTreeSelectionModel.java index 8ca40d8beab..cbf9ead8c37 100644 --- a/jdk/src/share/classes/javax/swing/tree/DefaultTreeSelectionModel.java +++ b/jdk/src/share/classes/javax/swing/tree/DefaultTreeSelectionModel.java @@ -157,8 +157,8 @@ public class DefaultTreeSelectionModel extends Object implements Cloneable, Seri selectionMode = TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION; if(oldMode != selectionMode && changeSupport != null) changeSupport.firePropertyChange(SELECTION_MODE_PROPERTY, - new Integer(oldMode), - new Integer(selectionMode)); + Integer.valueOf(oldMode), + Integer.valueOf(selectionMode)); } /** diff --git a/jdk/src/share/classes/sun/applet/AppletPanel.java b/jdk/src/share/classes/sun/applet/AppletPanel.java index fe4c356fe03..e02428b146b 100644 --- a/jdk/src/share/classes/sun/applet/AppletPanel.java +++ b/jdk/src/share/classes/sun/applet/AppletPanel.java @@ -285,7 +285,7 @@ abstract class AppletPanel extends Panel implements AppletStub, Runnable { //System.out.println("SEND0= " + id); queue = new Queue(); } - Integer eventId = new Integer(id); + Integer eventId = Integer.valueOf(id); queue.enqueue(eventId); notifyAll(); } diff --git a/jdk/src/share/classes/sun/applet/AppletViewer.java b/jdk/src/share/classes/sun/applet/AppletViewer.java index 5170b0258a1..69bd80e261c 100644 --- a/jdk/src/share/classes/sun/applet/AppletViewer.java +++ b/jdk/src/share/classes/sun/applet/AppletViewer.java @@ -587,9 +587,9 @@ public class AppletViewer extends Frame implements AppletContext, Dimension d = panel.size(); Insets in = panel.insets(); panel.atts.put("width", - new Integer(d.width - (in.left + in.right)).toString()); + Integer.toString(d.width - (in.left + in.right))); panel.atts.put("height", - new Integer(d.height - (in.top + in.bottom)).toString()); + Integer.toString(d.height - (in.top + in.bottom))); } /** diff --git a/jdk/src/share/classes/sun/awt/FontConfiguration.java b/jdk/src/share/classes/sun/awt/FontConfiguration.java index 9a1effd39a8..a6b94870b3f 100644 --- a/jdk/src/share/classes/sun/awt/FontConfiguration.java +++ b/jdk/src/share/classes/sun/awt/FontConfiguration.java @@ -1956,7 +1956,7 @@ public abstract class FontConfiguration { /*Init these tables to allow componentFontNameID, fontfileNameIDs to start from "1". */ - componentFontNameIDs.put("", new Short((short)0)); + componentFontNameIDs.put("", Short.valueOf((short)0)); fontfileNameIDs = new HashMap(); filenames = new HashMap(); diff --git a/jdk/src/share/classes/sun/awt/im/InputContext.java b/jdk/src/share/classes/sun/awt/im/InputContext.java index 5cb7e26705d..1ef31f1ded4 100644 --- a/jdk/src/share/classes/sun/awt/im/InputContext.java +++ b/jdk/src/share/classes/sun/awt/im/InputContext.java @@ -556,7 +556,7 @@ public class InputContext extends java.awt.im.InputContext } usedInputMethods.put(inputMethodLocator.deriveLocator(null), inputMethod); perInputMethodState.put(inputMethod, - new Boolean(clientWindowNotificationEnabled)); + Boolean.valueOf(clientWindowNotificationEnabled)); enableClientWindowNotification(inputMethod, false); if (this == inputMethodWindowContext) { inputMethod.hideWindows(); @@ -921,7 +921,7 @@ public class InputContext extends java.awt.im.InputContext if (perInputMethodState == null) { perInputMethodState = new HashMap(5); } - perInputMethodState.put(requester, new Boolean(enable)); + perInputMethodState.put(requester, Boolean.valueOf(enable)); return; } diff --git a/jdk/src/share/classes/sun/font/FileFontStrike.java b/jdk/src/share/classes/sun/font/FileFontStrike.java index edc9e67b6cb..76616d8ce39 100644 --- a/jdk/src/share/classes/sun/font/FileFontStrike.java +++ b/jdk/src/share/classes/sun/font/FileFontStrike.java @@ -657,7 +657,7 @@ public class FileFontStrike extends PhysicalStrike { * we first obtain this information, then the image, and never * will access this value again. */ - Integer key = new Integer(glyphCode); + Integer key = Integer.valueOf(glyphCode); Point2D.Float value = null; ConcurrentHashMap glyphMetricsMap = null; if (glyphMetricsMapRef != null) { @@ -724,7 +724,7 @@ public class FileFontStrike extends PhysicalStrike { boundsMap = new ConcurrentHashMap(); } - Integer key = new Integer(glyphCode); + Integer key = Integer.valueOf(glyphCode); Rectangle2D.Float bounds = boundsMap.get(key); if (bounds == null) { diff --git a/jdk/src/share/classes/sun/font/FontManager.java b/jdk/src/share/classes/sun/font/FontManager.java index 820c72728d3..d7fddd16d2b 100644 --- a/jdk/src/share/classes/sun/font/FontManager.java +++ b/jdk/src/share/classes/sun/font/FontManager.java @@ -2124,7 +2124,7 @@ public final class FontManager { private static void addLCIDMapEntry(Map map, String key, short value) { - map.put(key, new Short(value)); + map.put(key, Short.valueOf(value)); } private static synchronized void createLCIDMap() { diff --git a/jdk/src/share/classes/sun/font/FontResolver.java b/jdk/src/share/classes/sun/font/FontResolver.java index 5d130236e77..938fe3cade5 100644 --- a/jdk/src/share/classes/sun/font/FontResolver.java +++ b/jdk/src/share/classes/sun/font/FontResolver.java @@ -117,7 +117,7 @@ public final class FontResolver { Font2D font2D = FontManager.getFont2D(font); if (font2D.hasSupplementaryChars()) { fonts.add(font); - indices.add(new Integer(i)); + indices.add(Integer.valueOf(i)); } } diff --git a/jdk/src/share/classes/sun/font/PhysicalStrike.java b/jdk/src/share/classes/sun/font/PhysicalStrike.java index 31d8ff66281..b6f326bef53 100644 --- a/jdk/src/share/classes/sun/font/PhysicalStrike.java +++ b/jdk/src/share/classes/sun/font/PhysicalStrike.java @@ -114,7 +114,7 @@ public abstract class PhysicalStrike extends FontStrike { */ Point2D.Float getGlyphPoint(int glyphCode, int ptNumber) { Point2D.Float gp = null; - Integer ptKey = new Integer(glyphCode<<16|ptNumber); + Integer ptKey = Integer.valueOf(glyphCode<<16|ptNumber); if (glyphPointMapCache == null) { synchronized (this) { if (glyphPointMapCache == null) { diff --git a/jdk/src/share/classes/sun/java2d/SunGraphics2D.java b/jdk/src/share/classes/sun/java2d/SunGraphics2D.java index 887f4c91e97..018fad4b9bf 100644 --- a/jdk/src/share/classes/sun/java2d/SunGraphics2D.java +++ b/jdk/src/share/classes/sun/java2d/SunGraphics2D.java @@ -1374,7 +1374,7 @@ public final class SunGraphics2D SunHints.Value.get(SunHints.INTKEY_FRACTIONALMETRICS, fractionalMetricsHint)); model.put(SunHints.KEY_TEXT_ANTIALIAS_LCD_CONTRAST, - new Integer(lcdTextContrast)); + Integer.valueOf(lcdTextContrast)); Object value; switch (interpolationHint) { case SunHints.INTVAL_INTERPOLATION_NEAREST_NEIGHBOR: diff --git a/jdk/src/share/classes/sun/java2d/loops/SurfaceType.java b/jdk/src/share/classes/sun/java2d/loops/SurfaceType.java index c89d95a6a70..fc56cd9c77c 100644 --- a/jdk/src/share/classes/sun/java2d/loops/SurfaceType.java +++ b/jdk/src/share/classes/sun/java2d/loops/SurfaceType.java @@ -408,7 +408,7 @@ public final class SurfaceType { if (unusedUID > 255) { throw new InternalError("surface type id overflow"); } - i = new Integer(unusedUID++); + i = Integer.valueOf(unusedUID++); surfaceUIDMap.put(desc, i); } return i.intValue(); diff --git a/jdk/src/share/classes/sun/print/PSPrinterJob.java b/jdk/src/share/classes/sun/print/PSPrinterJob.java index 0b519599d13..5c2a9a5f216 100644 --- a/jdk/src/share/classes/sun/print/PSPrinterJob.java +++ b/jdk/src/share/classes/sun/print/PSPrinterJob.java @@ -1536,16 +1536,16 @@ public class PSPrinterJob extends RasterPrinterJob { execCmd = new String[ncomps]; execCmd[n++] = "/usr/bin/lpr"; if ((pFlags & PRINTER) != 0) { - execCmd[n++] = new String("-P" + printer); + execCmd[n++] = "-P" + printer; } if ((pFlags & BANNER) != 0) { - execCmd[n++] = new String("-J" + banner); + execCmd[n++] = "-J" + banner; } if ((pFlags & COPIES) != 0) { - execCmd[n++] = new String("-#" + new Integer(copies).toString()); + execCmd[n++] = "-#" + copies; } if ((pFlags & NOSHEET) != 0) { - execCmd[n++] = new String("-h"); + execCmd[n++] = "-h"; } if ((pFlags & OPTIONS) != 0) { execCmd[n++] = new String(options); @@ -1556,19 +1556,19 @@ public class PSPrinterJob extends RasterPrinterJob { execCmd[n++] = "/usr/bin/lp"; execCmd[n++] = "-c"; // make a copy of the spool file if ((pFlags & PRINTER) != 0) { - execCmd[n++] = new String("-d" + printer); + execCmd[n++] = "-d" + printer; } if ((pFlags & BANNER) != 0) { - execCmd[n++] = new String("-t" + banner); + execCmd[n++] = "-t" + banner; } if ((pFlags & COPIES) != 0) { - execCmd[n++] = new String("-n" + new Integer(copies).toString()); + execCmd[n++] = "-n" + copies; } if ((pFlags & NOSHEET) != 0) { - execCmd[n++] = new String("-o nobanner"); + execCmd[n++] = "-o nobanner"; } if ((pFlags & OPTIONS) != 0) { - execCmd[n++] = new String("-o" + options); + execCmd[n++] = "-o" + options; } } execCmd[n++] = spoolFile; diff --git a/jdk/src/share/classes/sun/print/RasterPrinterJob.java b/jdk/src/share/classes/sun/print/RasterPrinterJob.java index 9e2d2ffcfb5..1c0c0a8a2f4 100644 --- a/jdk/src/share/classes/sun/print/RasterPrinterJob.java +++ b/jdk/src/share/classes/sun/print/RasterPrinterJob.java @@ -245,7 +245,7 @@ public abstract class RasterPrinterJob extends PrinterJob { /** * The name of the job being printed. */ - private String mDocName = new String("Java Printing"); + private String mDocName = "Java Printing"; /** diff --git a/jdk/src/share/classes/sun/text/normalizer/VersionInfo.java b/jdk/src/share/classes/sun/text/normalizer/VersionInfo.java index e6039722316..3b3cc4d24b9 100644 --- a/jdk/src/share/classes/sun/text/normalizer/VersionInfo.java +++ b/jdk/src/share/classes/sun/text/normalizer/VersionInfo.java @@ -116,7 +116,7 @@ public final class VersionInfo throw new IllegalArgumentException(INVALID_VERSION_NUMBER_); } int version = getInt(major, minor, milli, micro); - Integer key = new Integer(version); + Integer key = Integer.valueOf(version); Object result = MAP_.get(key); if (result == null) { result = new VersionInfo(version); diff --git a/jdk/src/solaris/classes/sun/awt/X11/XDropTargetProtocol.java b/jdk/src/solaris/classes/sun/awt/X11/XDropTargetProtocol.java index bc6bacb2417..658b7cbf3d5 100644 --- a/jdk/src/solaris/classes/sun/awt/X11/XDropTargetProtocol.java +++ b/jdk/src/solaris/classes/sun/awt/X11/XDropTargetProtocol.java @@ -317,7 +317,7 @@ abstract class XDropTargetProtocol { protected final void removeEmbedderRegistryEntry(long embedder) { synchronized (this) { - embedderRegistry.remove(new Long(embedder)); + embedderRegistry.remove(Long.valueOf(embedder)); } } } diff --git a/jdk/src/solaris/classes/sun/awt/X11/XDropTargetRegistry.java b/jdk/src/solaris/classes/sun/awt/X11/XDropTargetRegistry.java index eecad17af89..2d05578dd04 100644 --- a/jdk/src/solaris/classes/sun/awt/X11/XDropTargetRegistry.java +++ b/jdk/src/solaris/classes/sun/awt/X11/XDropTargetRegistry.java @@ -329,7 +329,7 @@ final class XDropTargetRegistry { embedderProtocols = Collections.unmodifiableList(embedderProtocols); - Long lToplevel = new Long(embedder); + Long lToplevel = Long.valueOf(embedder); boolean isXEmbedServer = false; synchronized (this) { EmbeddedDropSiteEntry entry = diff --git a/jdk/src/solaris/classes/sun/awt/X11/XEmbedServerTester.java b/jdk/src/solaris/classes/sun/awt/X11/XEmbedServerTester.java index a5ce2df7404..28fd3c2246a 100644 --- a/jdk/src/solaris/classes/sun/awt/X11/XEmbedServerTester.java +++ b/jdk/src/solaris/classes/sun/awt/X11/XEmbedServerTester.java @@ -383,11 +383,11 @@ public class XEmbedServerTester implements XEventDispatcher { try { XCreateWindowParams params = new XCreateWindowParams(new Object[] { - XBaseWindow.PARENT_WINDOW, new Long(reparent?XToolkit.getDefaultRootWindow():parent), + XBaseWindow.PARENT_WINDOW, Long.valueOf(reparent?XToolkit.getDefaultRootWindow():parent), XBaseWindow.BOUNDS, initialBounds, XBaseWindow.EMBEDDED, Boolean.TRUE, XBaseWindow.VISIBLE, Boolean.valueOf(mapped == XEmbedHelper.XEMBED_MAPPED), - XBaseWindow.EVENT_MASK, new Long(VisibilityChangeMask | StructureNotifyMask | + XBaseWindow.EVENT_MASK, Long.valueOf(VisibilityChangeMask | StructureNotifyMask | SubstructureNotifyMask | KeyPressMask)}); window = new XBaseWindow(params); diff --git a/jdk/src/solaris/classes/sun/awt/X11/XFileDialogPeer.java b/jdk/src/solaris/classes/sun/awt/X11/XFileDialogPeer.java index d3baad68ed3..4e06328b9ae 100644 --- a/jdk/src/solaris/classes/sun/awt/X11/XFileDialogPeer.java +++ b/jdk/src/solaris/classes/sun/awt/X11/XFileDialogPeer.java @@ -908,7 +908,7 @@ class FileDialogFilter implements FilenameFilter { * Converts the filter into the form which is acceptable by Java's regexps */ private String convert(String filter) { - String regex = new String("^" + filter + "$"); + String regex = "^" + filter + "$"; regex = regex.replaceAll("\\.", "\\\\."); regex = regex.replaceAll("\\?", "."); regex = regex.replaceAll("\\*", ".*"); diff --git a/jdk/src/solaris/classes/sun/awt/X11/XScrollbar.java b/jdk/src/solaris/classes/sun/awt/X11/XScrollbar.java index 14316beed91..8a2d21b7ccd 100644 --- a/jdk/src/solaris/classes/sun/awt/X11/XScrollbar.java +++ b/jdk/src/solaris/classes/sun/awt/X11/XScrollbar.java @@ -458,16 +458,16 @@ abstract class XScrollbar { String type; switch (id) { case MouseEvent.MOUSE_PRESSED: - type = new String("press"); + type = "press"; break; case MouseEvent.MOUSE_RELEASED: - type = new String("release"); + type = "release"; break; case MouseEvent.MOUSE_DRAGGED: - type = new String("drag"); + type = "drag"; break; default: - type = new String("other"); + type = "other"; } log.finer("Mouse " + type + " event in scroll bar " + this + "x = " + x + ", y = " + y + diff --git a/jdk/src/solaris/classes/sun/awt/X11GraphicsConfig.java b/jdk/src/solaris/classes/sun/awt/X11GraphicsConfig.java index 897142223da..78fd9db279b 100644 --- a/jdk/src/solaris/classes/sun/awt/X11GraphicsConfig.java +++ b/jdk/src/solaris/classes/sun/awt/X11GraphicsConfig.java @@ -421,7 +421,7 @@ public class X11GraphicsConfig extends GraphicsConfiguration { return new SunVolatileImage(target, target.getWidth(), target.getHeight(), - new Long(backBuffer)); + Long.valueOf(backBuffer)); } /** diff --git a/jdk/src/solaris/classes/sun/awt/X11GraphicsDevice.java b/jdk/src/solaris/classes/sun/awt/X11GraphicsDevice.java index 755e77aa860..bdb178e8918 100644 --- a/jdk/src/solaris/classes/sun/awt/X11GraphicsDevice.java +++ b/jdk/src/solaris/classes/sun/awt/X11GraphicsDevice.java @@ -164,7 +164,7 @@ public class X11GraphicsDevice if (ret[i] == null) { boolean doubleBuffer = (dbeSupported && - doubleBufferVisuals.contains(new Integer(visNum))); + doubleBufferVisuals.contains(Integer.valueOf(visNum))); ret[i] = X11GraphicsConfig.getConfig(this, visNum, depth, getConfigColormap(i, screen), doubleBuffer); @@ -199,7 +199,7 @@ public class X11GraphicsDevice public static native boolean isDBESupported(); // Callback for adding a new double buffer visual into our set private void addDoubleBufferVisual(int visNum) { - doubleBufferVisuals.add(new Integer(visNum)); + doubleBufferVisuals.add(Integer.valueOf(visNum)); } // Enumerates all visuals that support double buffering private native void getDoubleBufferVisuals(int screen); @@ -239,7 +239,7 @@ public class X11GraphicsDevice doubleBufferVisuals = new HashSet(); getDoubleBufferVisuals(screen); doubleBuffer = - doubleBufferVisuals.contains(new Integer(visNum)); + doubleBufferVisuals.contains(Integer.valueOf(visNum)); } defaultConfig = X11GraphicsConfig.getConfig(this, visNum, depth, getConfigColormap(0, screen), diff --git a/jdk/src/solaris/classes/sun/print/UnixPrintJob.java b/jdk/src/solaris/classes/sun/print/UnixPrintJob.java index b3ab80a6f92..ad86ee2545c 100644 --- a/jdk/src/solaris/classes/sun/print/UnixPrintJob.java +++ b/jdk/src/solaris/classes/sun/print/UnixPrintJob.java @@ -867,39 +867,38 @@ public class UnixPrintJob implements CancelablePrintJob { execCmd[n++] = "/usr/bin/lp"; execCmd[n++] = "-c"; // make a copy of the spool file if ((pFlags & PRINTER) != 0) { - execCmd[n++] = new String("-d" + printer); + execCmd[n++] = "-d" + printer; } if ((pFlags & BANNER) != 0) { String quoteChar = "\""; - execCmd[n++] = new String("-t " + quoteChar+banner+quoteChar); + execCmd[n++] = "-t " + quoteChar+banner+quoteChar; } if ((pFlags & COPIES) != 0) { - execCmd[n++] = new String("-n " + - new Integer(copies).toString()); + execCmd[n++] = "-n " + copies; } if ((pFlags & NOSHEET) != 0) { - execCmd[n++] = new String("-o nobanner"); + execCmd[n++] = "-o nobanner"; } if ((pFlags & OPTIONS) != 0) { - execCmd[n++] = new String("-o " + options); + execCmd[n++] = "-o " + options; } } else { execCmd = new String[ncomps]; execCmd[n++] = "/usr/bin/lpr"; if ((pFlags & PRINTER) != 0) { - execCmd[n++] = new String("-P" + printer); + execCmd[n++] = "-P" + printer; } if ((pFlags & BANNER) != 0) { - execCmd[n++] = new String("-J " + banner); + execCmd[n++] = "-J " + banner; } if ((pFlags & COPIES) != 0) { - execCmd[n++] = new String("-#" + new Integer(copies).toString()); + execCmd[n++] = "-#" + copies; } if ((pFlags & NOSHEET) != 0) { - execCmd[n++] = new String("-h"); + execCmd[n++] = "-h"; } if ((pFlags & OPTIONS) != 0) { - execCmd[n++] = new String("-o" + options); + execCmd[n++] = "-o" + options; } } execCmd[n++] = spoolFile; diff --git a/jdk/src/windows/classes/sun/awt/windows/WDataTransferer.java b/jdk/src/windows/classes/sun/awt/windows/WDataTransferer.java index fbab9e602ab..7e9429d4512 100644 --- a/jdk/src/windows/classes/sun/awt/windows/WDataTransferer.java +++ b/jdk/src/windows/classes/sun/awt/windows/WDataTransferer.java @@ -568,7 +568,7 @@ class HTMLCodec extends InputStream { byte[] headerBytes = null, trailerBytes = null; try { - headerBytes = new String(header).getBytes(ENCODING); + headerBytes = header.toString().getBytes(ENCODING); trailerBytes = htmlSuffix.getBytes(ENCODING); } catch (UnsupportedEncodingException cannotHappen) { } diff --git a/jdk/src/windows/classes/sun/awt/windows/WInputMethod.java b/jdk/src/windows/classes/sun/awt/windows/WInputMethod.java index 1c3600ffb66..494ce4c0f45 100644 --- a/jdk/src/windows/classes/sun/awt/windows/WInputMethod.java +++ b/jdk/src/windows/classes/sun/awt/windows/WInputMethod.java @@ -488,7 +488,7 @@ public class WInputMethod extends InputMethodAdapter attrStr.addAttribute(Attribute.INPUT_METHOD_SEGMENT, new Annotation(null), 0, text.length()); attrStr.addAttribute(Attribute.READING, - new Annotation(new String("")), 0, text.length()); + new Annotation(""), 0, text.length()); } // set Hilight Information diff --git a/jdk/src/windows/classes/sun/awt/windows/WWindowPeer.java b/jdk/src/windows/classes/sun/awt/windows/WWindowPeer.java index 070c67dd15e..2db3e8829ac 100644 --- a/jdk/src/windows/classes/sun/awt/windows/WWindowPeer.java +++ b/jdk/src/windows/classes/sun/awt/windows/WWindowPeer.java @@ -123,7 +123,7 @@ public class WWindowPeer extends WPanelPeer implements WindowPeer { public void setTitle(String title) { // allow a null title to pass as an empty string. if (title == null) { - title = new String(""); + title = ""; } _setTitle(title); } diff --git a/jdk/src/windows/classes/sun/print/Win32PrintService.java b/jdk/src/windows/classes/sun/print/Win32PrintService.java index ea5771b3ad2..f0f05267ae6 100644 --- a/jdk/src/windows/classes/sun/print/Win32PrintService.java +++ b/jdk/src/windows/classes/sun/print/Win32PrintService.java @@ -348,7 +348,7 @@ public class Win32PrintService implements PrintService, AttributeUpdater, idList = new ArrayList(); for (int i=0; i < media.length; i++) { - idList.add(new Integer(media[i])); + idList.add(Integer.valueOf(media[i])); } mediaSizes = getMediaSizes(idList, media); @@ -517,7 +517,7 @@ public class Win32PrintService implements PrintService, AttributeUpdater, if ((wid <= 0) || (ht <= 0)) { //Remove corresponding ID from list if (nMedia == media.length) { - Integer remObj = new Integer(media[i]); + Integer remObj = Integer.valueOf(media[i]); idList.remove(idList.indexOf(remObj)); } continue; @@ -539,7 +539,7 @@ public class Win32PrintService implements PrintService, AttributeUpdater, msList.add(ms); } catch(IllegalArgumentException e) { if (nMedia == media.length) { - Integer remObj = new Integer(media[i]); + Integer remObj = Integer.valueOf(media[i]); idList.remove(idList.indexOf(remObj)); } } @@ -984,7 +984,7 @@ public class Win32PrintService implements PrintService, AttributeUpdater, // cannot be null but to be safe, add a check if ((idList != null) && (mediaSizes != null) && (idList.size() == mediaSizes.length)) { - Integer defIdObj = new Integer(defPaper); + Integer defIdObj = Integer.valueOf(defPaper); int index = idList.indexOf(defIdObj); if (index>=0 && index Date: Mon, 7 Apr 2008 16:52:51 +0400 Subject: [PATCH 145/258] 6623459: Get rid of XConstant, XProtocolConstants and XUtilConstants antipattern Access to interface's fiels via their name rather then implementation Reviewed-by: volk, son --- .../classes/sun/awt/X11/MWMConstants.java | 6 +- .../sun/awt/X11/MotifDnDConstants.java | 38 ++-- .../awt/X11/MotifDnDDragSourceProtocol.java | 32 ++-- .../awt/X11/MotifDnDDropTargetProtocol.java | 40 ++--- .../sun/awt/X11/WindowPropertyGetter.java | 6 +- .../classes/sun/awt/X11/XAWTXSettings.java | 4 +- .../solaris/classes/sun/awt/X11/XAtom.java | 22 +-- .../classes/sun/awt/X11/XBaseMenuWindow.java | 18 +- .../classes/sun/awt/X11/XBaseWindow.java | 166 +++++++++--------- .../classes/sun/awt/X11/XClipboard.java | 8 +- .../classes/sun/awt/X11/XComponentPeer.java | 24 +-- .../classes/sun/awt/X11/XConstants.java | 13 +- .../classes/sun/awt/X11/XContentWindow.java | 16 +- .../sun/awt/X11/XCursorFontConstants.java | 7 +- .../classes/sun/awt/X11/XCustomCursor.java | 6 +- .../classes/sun/awt/X11/XDecoratedPeer.java | 30 ++-- .../classes/sun/awt/X11/XDialogPeer.java | 16 +- .../sun/awt/X11/XDnDDragSourceProtocol.java | 38 ++-- .../sun/awt/X11/XDnDDropTargetProtocol.java | 70 ++++---- .../sun/awt/X11/XDragSourceContextPeer.java | 64 +++---- .../sun/awt/X11/XDragSourceProtocol.java | 8 +- .../awt/X11/XDropTargetEventProcessor.java | 8 +- .../sun/awt/X11/XDropTargetProtocol.java | 4 +- .../sun/awt/X11/XDropTargetRegistry.java | 22 +-- .../classes/sun/awt/X11/XEmbedCanvasPeer.java | 32 ++-- .../sun/awt/X11/XEmbedChildProxyPeer.java | 8 +- .../sun/awt/X11/XEmbedClientHelper.java | 6 +- .../classes/sun/awt/X11/XEmbedHelper.java | 6 +- .../sun/awt/X11/XEmbedServerTester.java | 8 +- .../sun/awt/X11/XEmbeddedFramePeer.java | 6 +- .../sun/awt/X11/XEmbeddingContainer.java | 6 +- .../sun/awt/X11/XFocusProxyWindow.java | 8 +- .../classes/sun/awt/X11/XFramePeer.java | 12 +- .../sun/awt/X11/XGlobalCursorManager.java | 30 ++-- .../classes/sun/awt/X11/XIconWindow.java | 12 +- .../classes/sun/awt/X11/XMSelection.java | 16 +- .../classes/sun/awt/X11/XNETProtocol.java | 8 +- .../classes/sun/awt/X11/XProtocol.java | 4 +- .../sun/awt/X11/XProtocolConstants.java | 7 +- .../classes/sun/awt/X11/XSelection.java | 46 ++--- .../classes/sun/awt/X11/XSystemTrayPeer.java | 6 +- .../solaris/classes/sun/awt/X11/XToolkit.java | 37 ++-- .../classes/sun/awt/X11/XTrayIconPeer.java | 8 +- .../classes/sun/awt/X11/XUtilConstants.java | 7 +- .../classes/sun/awt/X11/XWINProtocol.java | 10 +- jdk/src/solaris/classes/sun/awt/X11/XWM.java | 102 +++++------ .../solaris/classes/sun/awt/X11/XWindow.java | 80 ++++----- .../classes/sun/awt/X11/XWindowPeer.java | 50 +++--- .../solaris/classes/sun/awt/X11/XlibUtil.java | 8 +- .../classes/sun/awt/X11/XlibWrapper.java | 21 ++- 50 files changed, 611 insertions(+), 599 deletions(-) diff --git a/jdk/src/solaris/classes/sun/awt/X11/MWMConstants.java b/jdk/src/solaris/classes/sun/awt/X11/MWMConstants.java index eceeee2622d..4be49190289 100644 --- a/jdk/src/solaris/classes/sun/awt/X11/MWMConstants.java +++ b/jdk/src/solaris/classes/sun/awt/X11/MWMConstants.java @@ -1,5 +1,5 @@ /* - * Copyright 2003 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2003-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,7 +26,9 @@ package sun.awt.X11; -public interface MWMConstants { +final public class MWMConstants { + + private MWMConstants(){} /* bit definitions for MwmHints.flags */ static final int MWM_HINTS_FUNCTIONS= (1 << 0); diff --git a/jdk/src/solaris/classes/sun/awt/X11/MotifDnDConstants.java b/jdk/src/solaris/classes/sun/awt/X11/MotifDnDConstants.java index 9302361b04d..df4e857c6d4 100644 --- a/jdk/src/solaris/classes/sun/awt/X11/MotifDnDConstants.java +++ b/jdk/src/solaris/classes/sun/awt/X11/MotifDnDConstants.java @@ -118,11 +118,11 @@ class MotifDnDConstants { XA_MOTIF_DRAG_WINDOW, 0, 1, false, - XlibWrapper.AnyPropertyType); + XConstants.AnyPropertyType); try { int status = wpg.execute(XToolkit.IgnoreBadWindowHandler); - if (status == XlibWrapper.Success && + if (status == XConstants.Success && wpg.getData() != 0 && wpg.getActualType() == XAtom.XA_WINDOW && wpg.getActualFormat() == 32 && @@ -163,20 +163,20 @@ class MotifDnDConstants { XlibWrapper.XGrabServer(newDisplay); try { - XlibWrapper.XSetCloseDownMode(newDisplay, (int)XlibWrapper.RetainPermanent); + XlibWrapper.XSetCloseDownMode(newDisplay, (int)XConstants.RetainPermanent); XSetWindowAttributes xwa = new XSetWindowAttributes(); try { xwa.set_override_redirect(true); - xwa.set_event_mask(XlibWrapper.PropertyChangeMask); + xwa.set_event_mask(XConstants.PropertyChangeMask); motifWindow = XlibWrapper.XCreateWindow(newDisplay, defaultRootWindow, -10, -10, 1, 1, 0, 0, - XlibWrapper.InputOnly, - XlibWrapper.CopyFromParent, - (XlibWrapper.CWOverrideRedirect | - XlibWrapper.CWEventMask), + XConstants.InputOnly, + XConstants.CopyFromParent, + (XConstants.CWOverrideRedirect | + XConstants.CWEventMask), xwa.pData); if (motifWindow == 0) { @@ -195,13 +195,13 @@ class MotifDnDConstants { defaultRootWindow, XA_MOTIF_DRAG_WINDOW.getAtom(), XAtom.XA_WINDOW, 32, - XlibWrapper.PropModeReplace, + XConstants.PropModeReplace, data, 1); XToolkit.RESTORE_XERROR_HANDLER(); if (XToolkit.saved_error != null && - XToolkit.saved_error.get_error_code() != XlibWrapper.Success) { + XToolkit.saved_error.get_error_code() != XConstants.Success) { throw new XException("Cannot write motif drag window handle."); } @@ -282,7 +282,7 @@ class MotifDnDConstants { try { int status = wpg.execute(XToolkit.IgnoreBadWindowHandler); - if (status != XlibWrapper.Success + if (status != XConstants.Success || wpg.getActualType() != XA_MOTIF_DRAG_TARGETS.getAtom() || wpg.getData() == 0) { @@ -399,13 +399,13 @@ class MotifDnDConstants { motifWindow, XA_MOTIF_DRAG_TARGETS.getAtom(), XA_MOTIF_DRAG_TARGETS.getAtom(), 8, - XlibWrapper.PropModeReplace, + XConstants.PropModeReplace, data, tableSize); XToolkit.RESTORE_XERROR_HANDLER(); if (XToolkit.saved_error != null && - XToolkit.saved_error.get_error_code() != XlibWrapper.Success) { + XToolkit.saved_error.get_error_code() != XConstants.Success) { // Create a new motif window and retry. motifWindow = createMotifWindow(); @@ -415,13 +415,13 @@ class MotifDnDConstants { motifWindow, XA_MOTIF_DRAG_TARGETS.getAtom(), XA_MOTIF_DRAG_TARGETS.getAtom(), 8, - XlibWrapper.PropModeReplace, + XConstants.PropModeReplace, data, tableSize); XToolkit.RESTORE_XERROR_HANDLER(); if (XToolkit.saved_error != null && - XToolkit.saved_error.get_error_code() != XlibWrapper.Success) { + XToolkit.saved_error.get_error_code() != XConstants.Success) { throw new XException("Cannot write motif drag targets property."); } } @@ -538,12 +538,12 @@ class MotifDnDConstants { XlibWrapper.XChangeProperty(XToolkit.getDisplay(), window, XA_MOTIF_ATOM_0.getAtom(), XA_MOTIF_DRAG_INITIATOR_INFO.getAtom(), - 8, XlibWrapper.PropModeReplace, + 8, XConstants.PropModeReplace, structData, MOTIF_INITIATOR_INFO_SIZE); XToolkit.RESTORE_XERROR_HANDLER(); if (XToolkit.saved_error != null && - XToolkit.saved_error.get_error_code() != XlibWrapper.Success) { + XToolkit.saved_error.get_error_code() != XConstants.Success) { throw new XException("Cannot write drag initiator info"); } } finally { @@ -571,12 +571,12 @@ class MotifDnDConstants { XlibWrapper.XChangeProperty(XToolkit.getDisplay(), window, XA_MOTIF_DRAG_RECEIVER_INFO.getAtom(), XA_MOTIF_DRAG_RECEIVER_INFO.getAtom(), - 8, XlibWrapper.PropModeReplace, + 8, XConstants.PropModeReplace, data, dataSize); XToolkit.RESTORE_XERROR_HANDLER(); if (XToolkit.saved_error != null && - XToolkit.saved_error.get_error_code() != XlibWrapper.Success) { + XToolkit.saved_error.get_error_code() != XConstants.Success) { throw new XException("Cannot write Motif receiver info property"); } } finally { diff --git a/jdk/src/solaris/classes/sun/awt/X11/MotifDnDDragSourceProtocol.java b/jdk/src/solaris/classes/sun/awt/X11/MotifDnDDragSourceProtocol.java index a2c07ad226d..b7e534c773f 100644 --- a/jdk/src/solaris/classes/sun/awt/X11/MotifDnDDragSourceProtocol.java +++ b/jdk/src/solaris/classes/sun/awt/X11/MotifDnDDragSourceProtocol.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2007 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2003-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -44,7 +44,7 @@ class MotifDnDDragSourceProtocol extends XDragSourceProtocol private static final Unsafe unsafe = XlibWrapper.unsafe; - private long targetEnterServerTime = XlibWrapper.CurrentTime; + private long targetEnterServerTime = XConstants.CurrentTime; protected MotifDnDDragSourceProtocol(XDragSourceProtocolListener listener) { super(listener); @@ -86,7 +86,7 @@ class MotifDnDDragSourceProtocol extends XDragSourceProtocol if (!MotifDnDConstants.MotifDnDSelection.setOwner(contents, formatMap, formats, - XlibWrapper.CurrentTime)) { + XConstants.CurrentTime)) { cleanup(); throw new InvalidDnDOperationException("Cannot acquire selection ownership"); } @@ -137,7 +137,7 @@ class MotifDnDDragSourceProtocol extends XDragSourceProtocol long time = t; /* Discard events from the previous receiver. */ - if (targetEnterServerTime == XlibWrapper.CurrentTime || + if (targetEnterServerTime == XConstants.CurrentTime || time < targetEnterServerTime) { return true; } @@ -181,7 +181,7 @@ class MotifDnDDragSourceProtocol extends XDragSourceProtocol new WindowPropertyGetter(window, MotifDnDConstants.XA_MOTIF_DRAG_RECEIVER_INFO, 0, 0xFFFF, false, - XlibWrapper.AnyPropertyType); + XConstants.AnyPropertyType); try { int status = wpg.execute(XToolkit.IgnoreBadWindowHandler); @@ -200,7 +200,7 @@ class MotifDnDDragSourceProtocol extends XDragSourceProtocol * CARD32 heap_offset B32; * } xmDragReceiverInfoStruct; */ - if (status == (int)XlibWrapper.Success && wpg.getData() != 0 && + if (status == (int)XConstants.Success && wpg.getData() != 0 && wpg.getActualType() != 0 && wpg.getActualFormat() == 8 && wpg.getNumberOfItems() >= MotifDnDConstants.MOTIF_RECEIVER_INFO_SIZE) { @@ -243,7 +243,7 @@ class MotifDnDDragSourceProtocol extends XDragSourceProtocol XClientMessageEvent msg = new XClientMessageEvent(); try { - msg.set_type(XlibWrapper.ClientMessage); + msg.set_type(XConstants.ClientMessage); msg.set_window(getTargetWindow()); msg.set_format(8); msg.set_message_type(MotifDnDConstants.XA_MOTIF_DRAG_AND_DROP_MESSAGE.getAtom()); @@ -267,7 +267,7 @@ class MotifDnDDragSourceProtocol extends XDragSourceProtocol XlibWrapper.XSendEvent(XToolkit.getDisplay(), getTargetProxyWindow(), - false, XlibWrapper.NoEventMask, + false, XConstants.NoEventMask, msg.pData); } finally { msg.dispose(); @@ -281,7 +281,7 @@ class MotifDnDDragSourceProtocol extends XDragSourceProtocol XClientMessageEvent msg = new XClientMessageEvent(); try { - msg.set_type(XlibWrapper.ClientMessage); + msg.set_type(XConstants.ClientMessage); msg.set_window(getTargetWindow()); msg.set_format(8); msg.set_message_type(MotifDnDConstants.XA_MOTIF_DRAG_AND_DROP_MESSAGE.getAtom()); @@ -305,7 +305,7 @@ class MotifDnDDragSourceProtocol extends XDragSourceProtocol XlibWrapper.XSendEvent(XToolkit.getDisplay(), getTargetProxyWindow(), - false, XlibWrapper.NoEventMask, + false, XConstants.NoEventMask, msg.pData); } finally { msg.dispose(); @@ -318,7 +318,7 @@ class MotifDnDDragSourceProtocol extends XDragSourceProtocol XClientMessageEvent msg = new XClientMessageEvent(); try { - msg.set_type(XlibWrapper.ClientMessage); + msg.set_type(XConstants.ClientMessage); msg.set_window(getTargetWindow()); msg.set_format(8); msg.set_message_type(MotifDnDConstants.XA_MOTIF_DRAG_AND_DROP_MESSAGE.getAtom()); @@ -336,7 +336,7 @@ class MotifDnDDragSourceProtocol extends XDragSourceProtocol XlibWrapper.XSendEvent(XToolkit.getDisplay(), getTargetProxyWindow(), - false, XlibWrapper.NoEventMask, + false, XConstants.NoEventMask, msg.pData); } finally { msg.dispose(); @@ -356,7 +356,7 @@ class MotifDnDDragSourceProtocol extends XDragSourceProtocol XClientMessageEvent msg = new XClientMessageEvent(); try { - msg.set_type(XlibWrapper.ClientMessage); + msg.set_type(XConstants.ClientMessage); msg.set_window(getTargetWindow()); msg.set_format(8); msg.set_message_type(MotifDnDConstants.XA_MOTIF_DRAG_AND_DROP_MESSAGE.getAtom()); @@ -382,7 +382,7 @@ class MotifDnDDragSourceProtocol extends XDragSourceProtocol XlibWrapper.XSendEvent(XToolkit.getDisplay(), getTargetProxyWindow(), - false, XlibWrapper.NoEventMask, + false, XConstants.NoEventMask, msg.pData); } finally { msg.dispose(); @@ -397,12 +397,12 @@ class MotifDnDDragSourceProtocol extends XDragSourceProtocol public void cleanupTargetInfo() { super.cleanupTargetInfo(); - targetEnterServerTime = XlibWrapper.CurrentTime; + targetEnterServerTime = XConstants.CurrentTime; } public void dispatchEvent(XEvent ev) { switch (ev.get_type()) { - case XlibWrapper.SelectionRequest: + case XConstants.SelectionRequest: XSelectionRequestEvent xsre = ev.get_xselectionrequest(); long atom = xsre.get_selection(); diff --git a/jdk/src/solaris/classes/sun/awt/X11/MotifDnDDropTargetProtocol.java b/jdk/src/solaris/classes/sun/awt/X11/MotifDnDDropTargetProtocol.java index df348594fc5..383c21ec1ea 100644 --- a/jdk/src/solaris/classes/sun/awt/X11/MotifDnDDropTargetProtocol.java +++ b/jdk/src/solaris/classes/sun/awt/X11/MotifDnDDropTargetProtocol.java @@ -99,7 +99,7 @@ class MotifDnDDropTargetProtocol extends XDropTargetProtocol { new WindowPropertyGetter(embedder, MotifDnDConstants.XA_MOTIF_DRAG_RECEIVER_INFO, 0, 0xFFFF, false, - XlibWrapper.AnyPropertyType); + XConstants.AnyPropertyType); try { status = wpg.execute(XToolkit.IgnoreBadWindowHandler); @@ -118,7 +118,7 @@ class MotifDnDDropTargetProtocol extends XDropTargetProtocol { * CARD32 heap_offset B32; * } xmDragReceiverInfoStruct; */ - if (status == (int)XlibWrapper.Success && wpg.getData() != 0 && + if (status == (int)XConstants.Success && wpg.getData() != 0 && wpg.getActualType() != 0 && wpg.getActualFormat() == 8 && wpg.getNumberOfItems() >= MotifDnDConstants.MOTIF_RECEIVER_INFO_SIZE) { @@ -166,12 +166,12 @@ class MotifDnDDropTargetProtocol extends XDropTargetProtocol { XlibWrapper.XChangeProperty(XToolkit.getDisplay(), embedder, MotifDnDConstants.XA_MOTIF_DRAG_RECEIVER_INFO.getAtom(), MotifDnDConstants.XA_MOTIF_DRAG_RECEIVER_INFO.getAtom(), - 8, XlibWrapper.PropModeReplace, + 8, XConstants.PropModeReplace, data, dataSize); XToolkit.RESTORE_XERROR_HANDLER(); if (XToolkit.saved_error != null && - XToolkit.saved_error.get_error_code() != XlibWrapper.Success) { + XToolkit.saved_error.get_error_code() != XConstants.Success) { throw new XException("Cannot write Motif receiver info property"); } } finally { @@ -201,7 +201,7 @@ class MotifDnDDropTargetProtocol extends XDropTargetProtocol { new WindowPropertyGetter(embedder, MotifDnDConstants.XA_MOTIF_DRAG_RECEIVER_INFO, 0, 0xFFFF, false, - XlibWrapper.AnyPropertyType); + XConstants.AnyPropertyType); try { status = wpg.execute(XToolkit.IgnoreBadWindowHandler); @@ -220,7 +220,7 @@ class MotifDnDDropTargetProtocol extends XDropTargetProtocol { * CARD32 heap_offset B32; * } xmDragReceiverInfoStruct; */ - if (status == (int)XlibWrapper.Success && wpg.getData() != 0 && + if (status == (int)XConstants.Success && wpg.getData() != 0 && wpg.getActualType() != 0 && wpg.getActualFormat() == 8 && wpg.getNumberOfItems() >= MotifDnDConstants.MOTIF_RECEIVER_INFO_SIZE) { @@ -240,12 +240,12 @@ class MotifDnDDropTargetProtocol extends XDropTargetProtocol { XlibWrapper.XChangeProperty(XToolkit.getDisplay(), embedder, MotifDnDConstants.XA_MOTIF_DRAG_RECEIVER_INFO.getAtom(), MotifDnDConstants.XA_MOTIF_DRAG_RECEIVER_INFO.getAtom(), - 8, XlibWrapper.PropModeReplace, + 8, XConstants.PropModeReplace, data, dataSize); XToolkit.RESTORE_XERROR_HANDLER(); if (XToolkit.saved_error != null && - XToolkit.saved_error.get_error_code() != XlibWrapper.Success) { + XToolkit.saved_error.get_error_code() != XConstants.Success) { throw new XException("Cannot write Motif receiver info property"); } } @@ -273,7 +273,7 @@ class MotifDnDDropTargetProtocol extends XDropTargetProtocol { new WindowPropertyGetter(embedded, MotifDnDConstants.XA_MOTIF_DRAG_RECEIVER_INFO, 0, 0xFFFF, false, - XlibWrapper.AnyPropertyType); + XConstants.AnyPropertyType); try { status = wpg.execute(XToolkit.IgnoreBadWindowHandler); @@ -292,7 +292,7 @@ class MotifDnDDropTargetProtocol extends XDropTargetProtocol { * CARD32 heap_offset B32; * } xmDragReceiverInfoStruct; */ - if (status == (int)XlibWrapper.Success && wpg.getData() != 0 && + if (status == (int)XConstants.Success && wpg.getData() != 0 && wpg.getActualType() != 0 && wpg.getActualFormat() == 8 && wpg.getNumberOfItems() >= MotifDnDConstants.MOTIF_RECEIVER_INFO_SIZE) { @@ -322,12 +322,12 @@ class MotifDnDDropTargetProtocol extends XDropTargetProtocol { new WindowPropertyGetter(window, MotifDnDConstants.XA_MOTIF_DRAG_RECEIVER_INFO, 0, 0xFFFF, false, - XlibWrapper.AnyPropertyType); + XConstants.AnyPropertyType); try { int status = wpg.execute(XToolkit.IgnoreBadWindowHandler); - if (status == (int)XlibWrapper.Success && wpg.getData() != 0 && + if (status == (int)XConstants.Success && wpg.getData() != 0 && wpg.getActualType() != 0 && wpg.getActualFormat() == 8 && wpg.getNumberOfItems() >= MotifDnDConstants.MOTIF_RECEIVER_INFO_SIZE) { @@ -377,7 +377,7 @@ class MotifDnDDropTargetProtocol extends XDropTargetProtocol { try { int status = wpg.execute(XToolkit.IgnoreBadWindowHandler); - if (status == XlibWrapper.Success && wpg.getData() != 0 && + if (status == XConstants.Success && wpg.getData() != 0 && wpg.getActualType() == MotifDnDConstants.XA_MOTIF_DRAG_INITIATOR_INFO.getAtom() && wpg.getActualFormat() == 8 && @@ -420,7 +420,7 @@ class MotifDnDDropTargetProtocol extends XDropTargetProtocol { if (status == 0 || (XToolkit.saved_error != null && - XToolkit.saved_error.get_error_code() != XlibWrapper.Success)) { + XToolkit.saved_error.get_error_code() != XConstants.Success)) { throw new XException("XGetWindowAttributes failed"); } @@ -432,12 +432,12 @@ class MotifDnDDropTargetProtocol extends XDropTargetProtocol { XToolkit.WITH_XERROR_HANDLER(XToolkit.IgnoreBadWindowHandler); XlibWrapper.XSelectInput(XToolkit.getDisplay(), source_win, source_win_mask | - XlibWrapper.StructureNotifyMask); + XConstants.StructureNotifyMask); XToolkit.RESTORE_XERROR_HANDLER(); if (XToolkit.saved_error != null && - XToolkit.saved_error.get_error_code() != XlibWrapper.Success) { + XToolkit.saved_error.get_error_code() != XConstants.Success) { throw new XException("XSelectInput failed"); } @@ -590,7 +590,7 @@ class MotifDnDDropTargetProtocol extends XDropTargetProtocol { XClientMessageEvent dummy = new XClientMessageEvent(); try { - dummy.set_type(XlibWrapper.ClientMessage); + dummy.set_type(XConstants.ClientMessage); dummy.set_window(xclient.get_window()); dummy.set_format(32); dummy.set_message_type(0); @@ -600,7 +600,7 @@ class MotifDnDDropTargetProtocol extends XDropTargetProtocol { dummy.set_data(3, 0); dummy.set_data(4, 0); XlibWrapper.XSendEvent(XToolkit.getDisplay(), - proxy, false, XlibWrapper.NoEventMask, + proxy, false, XConstants.NoEventMask, dummy.pData); } finally { dummy.dispose(); @@ -821,7 +821,7 @@ class MotifDnDDropTargetProtocol extends XDropTargetProtocol { XClientMessageEvent msg = new XClientMessageEvent(); try { - msg.set_type(XlibWrapper.ClientMessage); + msg.set_type(XConstants.ClientMessage); msg.set_window(MotifDnDConstants.Swapper.getInt(data + 12, eventByteOrder)); msg.set_format(8); msg.set_message_type(MotifDnDConstants.XA_MOTIF_DRAG_AND_DROP_MESSAGE.getAtom()); @@ -878,7 +878,7 @@ class MotifDnDDropTargetProtocol extends XDropTargetProtocol { try { XlibWrapper.XSendEvent(XToolkit.getDisplay(), msg.get_window(), - false, XlibWrapper.NoEventMask, + false, XConstants.NoEventMask, msg.pData); } finally { XToolkit.awtUnlock(); diff --git a/jdk/src/solaris/classes/sun/awt/X11/WindowPropertyGetter.java b/jdk/src/solaris/classes/sun/awt/X11/WindowPropertyGetter.java index ba5f3837bd7..6926f8c8271 100644 --- a/jdk/src/solaris/classes/sun/awt/X11/WindowPropertyGetter.java +++ b/jdk/src/solaris/classes/sun/awt/X11/WindowPropertyGetter.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2005 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2003-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -89,7 +89,7 @@ public class WindowPropertyGetter { if (isCachingSupported() && isCached()) { readFromCache(); - return XlibWrapper.Success; + return XConstants.Success; } // Fix for performance problem - IgnodeBadWindowHandler is @@ -106,7 +106,7 @@ public class WindowPropertyGetter { offset, length, (auto_delete?1:0), type, actual_type, actual_format, nitems_ptr, bytes_after, data); - if (isCachingSupported() && status == XlibWrapper.Success && getData() != 0 && isCacheableProperty(property)) { + if (isCachingSupported() && status == XConstants.Success && getData() != 0 && isCacheableProperty(property)) { // Property has some data, we cache them cacheProperty(); } diff --git a/jdk/src/solaris/classes/sun/awt/X11/XAWTXSettings.java b/jdk/src/solaris/classes/sun/awt/X11/XAWTXSettings.java index 2db97c44a95..6727912c9a7 100644 --- a/jdk/src/solaris/classes/sun/awt/X11/XAWTXSettings.java +++ b/jdk/src/solaris/classes/sun/awt/X11/XAWTXSettings.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2007 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2003-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -128,7 +128,7 @@ class XAWTXSettings extends XSettings implements XMSelectionListener { try { int status = getter.execute(XToolkit.IgnoreBadWindowHandler); - if (status != XlibWrapper.Success || getter.getData() == 0) { + if (status != XConstants.Success || getter.getData() == 0) { if (log.isLoggable(Level.FINE)) log.fine("OH OH : getter failed status = " + status ); settings = null; } diff --git a/jdk/src/solaris/classes/sun/awt/X11/XAtom.java b/jdk/src/solaris/classes/sun/awt/X11/XAtom.java index b72e790a043..335917abf79 100644 --- a/jdk/src/solaris/classes/sun/awt/X11/XAtom.java +++ b/jdk/src/solaris/classes/sun/awt/X11/XAtom.java @@ -370,7 +370,7 @@ public final class XAtom { false, property_type); try { int status = getter.execute(); - if (status != XlibWrapper.Success || getter.getData() == 0) { + if (status != XConstants.Success || getter.getData() == 0) { return 0; } if (getter.getActualType() != property_type || getter.getActualFormat() != 32) { @@ -401,7 +401,7 @@ public final class XAtom { try { Native.putCard32(XlibWrapper.larg1, value); XlibWrapper.XChangeProperty(XToolkit.getDisplay(), window, - atom, XA_CARDINAL, 32, XlibWrapper.PropModeReplace, + atom, XA_CARDINAL, 32, XConstants.PropModeReplace, XlibWrapper.larg1, 1); } finally { XToolkit.awtUnlock(); @@ -432,7 +432,7 @@ public final class XAtom { false, this); try { int status = getter.execute(); - if (status != XlibWrapper.Success || getter.getData() == 0) { + if (status != XConstants.Success || getter.getData() == 0) { return false; } if (getter.getActualType() != atom @@ -466,7 +466,7 @@ public final class XAtom { false, type); try { int status = getter.execute(); - if (status != XlibWrapper.Success || getter.getData() == 0) { + if (status != XConstants.Success || getter.getData() == 0) { return false; } if (getter.getActualType() != type @@ -497,7 +497,7 @@ public final class XAtom { XToolkit.awtLock(); try { XlibWrapper.XChangeProperty(XToolkit.getDisplay(), window, - atom, atom, 32, XlibWrapper.PropModeReplace, + atom, atom, 32, XConstants.PropModeReplace, data_ptr, length); } finally { XToolkit.awtUnlock(); @@ -518,7 +518,7 @@ public final class XAtom { XToolkit.awtLock(); try { XlibWrapper.XChangeProperty(XToolkit.getDisplay(), window, - atom, type, 32, XlibWrapper.PropModeReplace, + atom, type, 32, XConstants.PropModeReplace, data_ptr, length); } finally { XToolkit.awtUnlock(); @@ -539,7 +539,7 @@ public final class XAtom { XToolkit.awtLock(); try { XlibWrapper.XChangeProperty(XToolkit.getDisplay(), window, - atom, type, 8, XlibWrapper.PropModeReplace, + atom, type, 8, XConstants.PropModeReplace, data_ptr, length); } finally { XToolkit.awtUnlock(); @@ -602,7 +602,7 @@ public final class XAtom { false, property_type); try { int status = getter.execute(); - if (status != XlibWrapper.Success || getter.getData() == 0) { + if (status != XConstants.Success || getter.getData() == 0) { return null; } if (getter.getActualType() != property_type || getter.getActualFormat() != 8) { @@ -674,7 +674,7 @@ public final class XAtom { false, XA_ATOM); try { int status = getter.execute(); - if (status != XlibWrapper.Success || getter.getData() == 0) { + if (status != XConstants.Success || getter.getData() == 0) { return emptyList; } if (getter.getActualType() != XA_ATOM || getter.getActualFormat() != 32) { @@ -797,7 +797,7 @@ public final class XAtom { try { Native.putWindow(XlibWrapper.larg1, window_value); XlibWrapper.XChangeProperty(XToolkit.getDisplay(), window, - atom, XA_WINDOW, 32, XlibWrapper.PropModeReplace, + atom, XA_WINDOW, 32, XConstants.PropModeReplace, XlibWrapper.larg1, 1); } finally { XToolkit.awtUnlock(); @@ -821,7 +821,7 @@ public final class XAtom { false, XA_WINDOW); try { int status = getter.execute(); - if (status != XlibWrapper.Success || getter.getData() == 0) { + if (status != XConstants.Success || getter.getData() == 0) { return 0; } if (getter.getActualType() != XA_WINDOW || getter.getActualFormat() != 32) { diff --git a/jdk/src/solaris/classes/sun/awt/X11/XBaseMenuWindow.java b/jdk/src/solaris/classes/sun/awt/X11/XBaseMenuWindow.java index cb241c121b6..1655be61ece 100644 --- a/jdk/src/solaris/classes/sun/awt/X11/XBaseMenuWindow.java +++ b/jdk/src/solaris/classes/sun/awt/X11/XBaseMenuWindow.java @@ -1,5 +1,5 @@ /* - * Copyright 2005-2007 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2005-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -885,14 +885,14 @@ abstract public class XBaseMenuWindow extends XWindow { */ protected boolean isEventDisabled(XEvent e) { switch (e.get_type()) { - case XlibWrapper.Expose : - case XlibWrapper.GraphicsExpose : - case XlibWrapper.ButtonPress: - case XlibWrapper.ButtonRelease: - case XlibWrapper.MotionNotify: - case XlibWrapper.KeyPress: - case XlibWrapper.KeyRelease: - case XlibWrapper.DestroyNotify: + case XConstants.Expose : + case XConstants.GraphicsExpose : + case XConstants.ButtonPress: + case XConstants.ButtonRelease: + case XConstants.MotionNotify: + case XConstants.KeyPress: + case XConstants.KeyRelease: + case XConstants.DestroyNotify: return super.isEventDisabled(e); default: return true; diff --git a/jdk/src/solaris/classes/sun/awt/X11/XBaseWindow.java b/jdk/src/solaris/classes/sun/awt/X11/XBaseWindow.java index cdac58a1240..f853d506784 100644 --- a/jdk/src/solaris/classes/sun/awt/X11/XBaseWindow.java +++ b/jdk/src/solaris/classes/sun/awt/X11/XBaseWindow.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2007 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2003-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -30,7 +30,7 @@ import sun.awt.*; import java.util.logging.*; import java.util.*; -public class XBaseWindow implements XConstants, XUtilConstants { +public class XBaseWindow { private static final Logger log = Logger.getLogger("sun.awt.X11.XBaseWindow"); private static final Logger insLog = Logger.getLogger("sun.awt.X11.insets.XBaseWindow"); private static final Logger eventLog = Logger.getLogger("sun.awt.X11.event.XBaseWindow"); @@ -148,7 +148,7 @@ public class XBaseWindow implements XConstants, XUtilConstants { Long eventMask = (Long)params.get(EVENT_MASK); if (eventMask != null) { long mask = eventMask.longValue(); - mask |= SubstructureNotifyMask; + mask |= XConstants.SubstructureNotifyMask; params.put(EVENT_MASK, mask); } @@ -281,10 +281,10 @@ public class XBaseWindow implements XConstants, XUtilConstants { } params.putIfNull(PARENT_WINDOW, Long.valueOf(XToolkit.getDefaultRootWindow())); params.putIfNull(BOUNDS, new Rectangle(DEF_LOCATION, DEF_LOCATION, MIN_SIZE, MIN_SIZE)); - params.putIfNull(DEPTH, Integer.valueOf((int)XlibWrapper.CopyFromParent)); - params.putIfNull(VISUAL, Long.valueOf(XlibWrapper.CopyFromParent)); - params.putIfNull(VISUAL_CLASS, Integer.valueOf((int)XlibWrapper.InputOnly)); - params.putIfNull(VALUE_MASK, Long.valueOf(XlibWrapper.CWEventMask)); + params.putIfNull(DEPTH, Integer.valueOf((int)XConstants.CopyFromParent)); + params.putIfNull(VISUAL, Long.valueOf(XConstants.CopyFromParent)); + params.putIfNull(VISUAL_CLASS, Integer.valueOf((int)XConstants.InputOnly)); + params.putIfNull(VALUE_MASK, Long.valueOf(XConstants.CWEventMask)); Rectangle bounds = (Rectangle)params.get(BOUNDS); bounds.width = Math.max(MIN_SIZE, bounds.width); bounds.height = Math.max(MIN_SIZE, bounds.height); @@ -293,7 +293,7 @@ public class XBaseWindow implements XConstants, XUtilConstants { long eventMask = eventMaskObj != null ? eventMaskObj.longValue() : 0; // We use our own synthetic grab see XAwtState.getGrabWindow() // (see X vol. 1, 8.3.3.2) - eventMask |= PropertyChangeMask | OwnerGrabButtonMask; + eventMask |= XConstants.PropertyChangeMask | XConstants.OwnerGrabButtonMask; params.put(EVENT_MASK, Long.valueOf(eventMask)); } @@ -312,23 +312,23 @@ public class XBaseWindow implements XConstants, XUtilConstants { Long eventMask = (Long)params.get(EVENT_MASK); xattr.set_event_mask(eventMask.longValue()); - value_mask |= XlibWrapper.CWEventMask; + value_mask |= XConstants.CWEventMask; Long border_pixel = (Long)params.get(BORDER_PIXEL); if (border_pixel != null) { xattr.set_border_pixel(border_pixel.longValue()); - value_mask |= XlibWrapper.CWBorderPixel; + value_mask |= XConstants.CWBorderPixel; } Long colormap = (Long)params.get(COLORMAP); if (colormap != null) { xattr.set_colormap(colormap.longValue()); - value_mask |= XlibWrapper.CWColormap; + value_mask |= XConstants.CWColormap; } Long background_pixmap = (Long)params.get(BACKGROUND_PIXMAP); if (background_pixmap != null) { xattr.set_background_pixmap(background_pixmap.longValue()); - value_mask |= XlibWrapper.CWBackPixmap; + value_mask |= XConstants.CWBackPixmap; } Long parentWindow = (Long)params.get(PARENT_WINDOW); @@ -339,25 +339,25 @@ public class XBaseWindow implements XConstants, XUtilConstants { Boolean overrideRedirect = (Boolean)params.get(OVERRIDE_REDIRECT); if (overrideRedirect != null) { xattr.set_override_redirect(overrideRedirect.booleanValue()); - value_mask |= XlibWrapper.CWOverrideRedirect; + value_mask |= XConstants.CWOverrideRedirect; } Boolean saveUnder = (Boolean)params.get(SAVE_UNDER); if (saveUnder != null) { xattr.set_save_under(saveUnder.booleanValue()); - value_mask |= XlibWrapper.CWSaveUnder; + value_mask |= XConstants.CWSaveUnder; } Integer backingStore = (Integer)params.get(BACKING_STORE); if (backingStore != null) { xattr.set_backing_store(backingStore.intValue()); - value_mask |= XlibWrapper.CWBackingStore; + value_mask |= XConstants.CWBackingStore; } Integer bitGravity = (Integer)params.get(BIT_GRAVITY); if (bitGravity != null) { xattr.set_bit_gravity(bitGravity.intValue()); - value_mask |= XlibWrapper.CWBitGravity; + value_mask |= XConstants.CWBitGravity; } if (log.isLoggable(Level.FINE)) { @@ -487,25 +487,25 @@ public class XBaseWindow implements XConstants, XUtilConstants { // Note: if PPosition is not set in flags this means that // we want to reset PPosition in hints. This is necessary // for locationByPlatform functionality - if ((flags & XlibWrapper.PPosition) != 0) { + if ((flags & XUtilConstants.PPosition) != 0) { hints.set_x(x); hints.set_y(y); } - if ((flags & XlibWrapper.PSize) != 0) { + if ((flags & XUtilConstants.PSize) != 0) { hints.set_width(width); hints.set_height(height); - } else if ((hints.get_flags() & XlibWrapper.PSize) != 0) { - flags |= XlibWrapper.PSize; + } else if ((hints.get_flags() & XUtilConstants.PSize) != 0) { + flags |= XUtilConstants.PSize; } - if ((flags & XlibWrapper.PMinSize) != 0) { + if ((flags & XUtilConstants.PMinSize) != 0) { hints.set_min_width(width); hints.set_min_height(height); - } else if ((hints.get_flags() & XlibWrapper.PMinSize) != 0) { - flags |= XlibWrapper.PMinSize; + } else if ((hints.get_flags() & XUtilConstants.PMinSize) != 0) { + flags |= XUtilConstants.PMinSize; //Fix for 4320050: Minimum size for java.awt.Frame is not being enforced. //We don't need to reset minimum size if it's already set } - if ((flags & XlibWrapper.PMaxSize) != 0) { + if ((flags & XUtilConstants.PMaxSize) != 0) { if (maxBounds != null) { if (maxBounds.width != Integer.MAX_VALUE) { hints.set_max_width(maxBounds.width); @@ -521,8 +521,8 @@ public class XBaseWindow implements XConstants, XUtilConstants { hints.set_max_width(width); hints.set_max_height(height); } - } else if ((hints.get_flags() & XlibWrapper.PMaxSize) != 0) { - flags |= XlibWrapper.PMaxSize; + } else if ((hints.get_flags() & XUtilConstants.PMaxSize) != 0) { + flags |= XUtilConstants.PMaxSize; if (maxBounds != null) { if (maxBounds.width != Integer.MAX_VALUE) { hints.set_max_width(maxBounds.width); @@ -538,9 +538,9 @@ public class XBaseWindow implements XConstants, XUtilConstants { // Leave intact } } - flags |= XlibWrapper.PWinGravity; + flags |= XUtilConstants.PWinGravity; hints.set_flags(flags); - hints.set_win_gravity((int)XlibWrapper.NorthWestGravity); + hints.set_win_gravity((int)XConstants.NorthWestGravity); if (insLog.isLoggable(Level.FINER)) insLog.finer("Setting hints, resulted flags " + XlibWrapper.hintsToString(flags) + ", values " + hints); XlibWrapper.XSetWMNormalHints(XToolkit.getDisplay(), getWindow(), hints.pData); @@ -552,7 +552,7 @@ public class XBaseWindow implements XConstants, XUtilConstants { public boolean isMinSizeSet() { XSizeHints hints = getHints(); long flags = hints.get_flags(); - return ((flags & XlibWrapper.PMinSize) == XlibWrapper.PMinSize); + return ((flags & XUtilConstants.PMinSize) == XUtilConstants.PMinSize); } /** @@ -837,29 +837,29 @@ public class XBaseWindow implements XConstants, XUtilConstants { //6273031: PIT. Choice drop down does not close once it is right clicked to show a popup menu //remember previous window having grab and if it's not null ungrab it. XBaseWindow prevGrabWindow = XAwtState.getGrabWindow(); - final int eventMask = (int) (ButtonPressMask | ButtonReleaseMask - | EnterWindowMask | LeaveWindowMask | PointerMotionMask - | ButtonMotionMask); + final int eventMask = (int) (XConstants.ButtonPressMask | XConstants.ButtonReleaseMask + | XConstants.EnterWindowMask | XConstants.LeaveWindowMask | XConstants.PointerMotionMask + | XConstants.ButtonMotionMask); final int ownerEvents = 1; int ptrGrab = XlibWrapper.XGrabPointer(XToolkit.getDisplay(), - getContentWindow(), ownerEvents, eventMask, GrabModeAsync, - GrabModeAsync, None, (XWM.isMotif() ? XToolkit.arrowCursor : None), - CurrentTime); + getContentWindow(), ownerEvents, eventMask, XConstants.GrabModeAsync, + XConstants.GrabModeAsync, XConstants.None, (XWM.isMotif() ? XToolkit.arrowCursor : XConstants.None), + XConstants.CurrentTime); // Check grab results to be consistent with X server grab - if (ptrGrab != GrabSuccess) { - XlibWrapper.XUngrabPointer(XToolkit.getDisplay(), CurrentTime); + if (ptrGrab != XConstants.GrabSuccess) { + XlibWrapper.XUngrabPointer(XToolkit.getDisplay(), XConstants.CurrentTime); XAwtState.setGrabWindow(null); grabLog.fine(" Grab Failure - mouse"); return false; } int keyGrab = XlibWrapper.XGrabKeyboard(XToolkit.getDisplay(), - getContentWindow(), ownerEvents, GrabModeAsync, GrabModeAsync, - CurrentTime); - if (keyGrab != GrabSuccess) { - XlibWrapper.XUngrabPointer(XToolkit.getDisplay(), CurrentTime); - XlibWrapper.XUngrabKeyboard(XToolkit.getDisplay(), CurrentTime); + getContentWindow(), ownerEvents, XConstants.GrabModeAsync, XConstants.GrabModeAsync, + XConstants.CurrentTime); + if (keyGrab != XConstants.GrabSuccess) { + XlibWrapper.XUngrabPointer(XToolkit.getDisplay(), XConstants.CurrentTime); + XlibWrapper.XUngrabKeyboard(XToolkit.getDisplay(), XConstants.CurrentTime); XAwtState.setGrabWindow(null); grabLog.fine(" Grab Failure - keyboard"); return false; @@ -882,8 +882,8 @@ public class XBaseWindow implements XConstants, XUtilConstants { grabLog.log(Level.FINE, "UnGrab input on {0}", new Object[] {grabWindow}); if (grabWindow != null) { grabWindow.ungrabInputImpl(); - XlibWrapper.XUngrabPointer(XToolkit.getDisplay(), CurrentTime); - XlibWrapper.XUngrabKeyboard(XToolkit.getDisplay(), CurrentTime); + XlibWrapper.XUngrabPointer(XToolkit.getDisplay(), XConstants.CurrentTime); + XlibWrapper.XUngrabKeyboard(XToolkit.getDisplay(), XConstants.CurrentTime); XAwtState.setGrabWindow(null); // we need to call XFlush() here to force ungrab // see 6384219 for details @@ -979,15 +979,15 @@ public class XBaseWindow implements XConstants, XUtilConstants { */ public void handleButtonPressRelease(XEvent xev) { XButtonEvent xbe = xev.get_xbutton(); - final int buttonState = xbe.get_state() & (Button1Mask | Button2Mask - | Button3Mask | Button4Mask | Button5Mask); + final int buttonState = xbe.get_state() & (XConstants.Button1Mask | XConstants.Button2Mask + | XConstants.Button3Mask | XConstants.Button4Mask | XConstants.Button5Mask); switch (xev.get_type()) { - case ButtonPress: + case XConstants.ButtonPress: if (buttonState == 0) { XAwtState.setAutoGrabWindow(this); } break; - case ButtonRelease: + case XConstants.ButtonRelease: if (isFullRelease(buttonState, xbe.get_button())) { XAwtState.setAutoGrabWindow(null); } @@ -1012,30 +1012,30 @@ public class XBaseWindow implements XConstants, XUtilConstants { */ static boolean isFullRelease(int buttonState, int button) { switch (button) { - case Button1: - return buttonState == Button1Mask; - case Button2: - return buttonState == Button2Mask; - case Button3: - return buttonState == Button3Mask; - case Button4: - return buttonState == Button4Mask; - case Button5: - return buttonState == Button5Mask; + case XConstants.Button1: + return buttonState == XConstants.Button1Mask; + case XConstants.Button2: + return buttonState == XConstants.Button2Mask; + case XConstants.Button3: + return buttonState == XConstants.Button3Mask; + case XConstants.Button4: + return buttonState == XConstants.Button4Mask; + case XConstants.Button5: + return buttonState == XConstants.Button5Mask; } return buttonState == 0; } static boolean isGrabbedEvent(XEvent ev, XBaseWindow target) { switch (ev.get_type()) { - case ButtonPress: - case ButtonRelease: - case MotionNotify: - case KeyPress: - case KeyRelease: + case XConstants.ButtonPress: + case XConstants.ButtonRelease: + case XConstants.MotionNotify: + case XConstants.KeyPress: + case XConstants.KeyRelease: return true; - case LeaveNotify: - case EnterNotify: + case XConstants.LeaveNotify: + case XConstants.EnterNotify: // We shouldn't dispatch this events to the grabbed components (see 6317481) // But this logic is important if the grabbed component is top-level (see realSync) return (target instanceof XWindowPeer); @@ -1067,53 +1067,53 @@ public class XBaseWindow implements XConstants, XUtilConstants { switch (type) { - case VisibilityNotify: + case XConstants.VisibilityNotify: handleVisibilityEvent(xev); break; - case ClientMessage: + case XConstants.ClientMessage: handleClientMessage(xev); break; - case Expose : - case GraphicsExpose : + case XConstants.Expose : + case XConstants.GraphicsExpose : handleExposeEvent(xev); break; - case ButtonPress: - case ButtonRelease: + case XConstants.ButtonPress: + case XConstants.ButtonRelease: handleButtonPressRelease(xev); break; - case MotionNotify: + case XConstants.MotionNotify: handleMotionNotify(xev); break; - case KeyPress: + case XConstants.KeyPress: handleKeyPress(xev); break; - case KeyRelease: + case XConstants.KeyRelease: handleKeyRelease(xev); break; - case EnterNotify: - case LeaveNotify: + case XConstants.EnterNotify: + case XConstants.LeaveNotify: handleXCrossingEvent(xev); break; - case ConfigureNotify: + case XConstants.ConfigureNotify: handleConfigureNotifyEvent(xev); break; - case MapNotify: + case XConstants.MapNotify: handleMapNotifyEvent(xev); break; - case UnmapNotify: + case XConstants.UnmapNotify: handleUnmapNotifyEvent(xev); break; - case ReparentNotify: + case XConstants.ReparentNotify: handleReparentNotifyEvent(xev); break; - case PropertyNotify: + case XConstants.PropertyNotify: handlePropertyNotify(xev); break; - case DestroyNotify: + case XConstants.DestroyNotify: handleDestroyNotify(xev); break; - case CreateNotify: + case XConstants.CreateNotify: handleCreateNotify(xev); break; } diff --git a/jdk/src/solaris/classes/sun/awt/X11/XClipboard.java b/jdk/src/solaris/classes/sun/awt/X11/XClipboard.java index 138e11d9a8c..f6009e79c12 100644 --- a/jdk/src/solaris/classes/sun/awt/X11/XClipboard.java +++ b/jdk/src/solaris/classes/sun/awt/X11/XClipboard.java @@ -185,7 +185,7 @@ public final class XClipboard extends SunClipboard implements OwnershipListener private static class SelectionNotifyHandler implements XEventDispatcher { public void dispatchEvent(XEvent ev) { - if (ev.get_type() == XlibWrapper.SelectionNotify) { + if (ev.get_type() == XConstants.SelectionNotify) { final XSelectionEvent xse = ev.get_xselection(); XClipboard clipboard = null; synchronized (XClipboard.classLock) { @@ -223,7 +223,7 @@ public final class XClipboard extends SunClipboard implements OwnershipListener XDataTransferer.TARGETS_ATOM.getAtom(), getTargetsPropertyAtom().getAtom(), XWindow.getXAWTRootWindow().getWindow(), - XlibWrapper.CurrentTime); + XConstants.CurrentTime); isSelectionNotifyProcessed = false; } } finally { @@ -260,7 +260,7 @@ public final class XClipboard extends SunClipboard implements OwnershipListener long[] formats = null; - if (propertyAtom == XlibWrapper.None) { + if (propertyAtom == XConstants.None) { // We treat None property atom as "empty selection". formats = new long[0]; } else { @@ -268,7 +268,7 @@ public final class XClipboard extends SunClipboard implements OwnershipListener new WindowPropertyGetter(XWindow.getXAWTRootWindow().getWindow(), XAtom.get(propertyAtom), 0, XSelection.MAX_LENGTH, true, - XlibWrapper.AnyPropertyType); + XConstants.AnyPropertyType); try { targetsGetter.execute(); formats = XSelection.getFormats(targetsGetter); diff --git a/jdk/src/solaris/classes/sun/awt/X11/XComponentPeer.java b/jdk/src/solaris/classes/sun/awt/X11/XComponentPeer.java index fb687e36830..8e9c930889f 100644 --- a/jdk/src/solaris/classes/sun/awt/X11/XComponentPeer.java +++ b/jdk/src/solaris/classes/sun/awt/X11/XComponentPeer.java @@ -72,7 +72,7 @@ import sun.awt.image.SunVolatileImage; import sun.awt.image.ToolkitImage; import sun.java2d.pipe.Region; -public class XComponentPeer extends XWindow implements ComponentPeer, DropTargetPeer, XConstants { +public class XComponentPeer extends XWindow implements ComponentPeer, DropTargetPeer { /* FIX ME: these constants copied from java.awt.KeyboardFocusManager */ static final int SNFH_FAILURE = 0; static final int SNFH_SUCCESS_HANDLED = 1; @@ -718,7 +718,7 @@ public class XComponentPeer extends XWindow implements ComponentPeer, DropTarget * handleJavaMouseEvent() would be more suitable place to do this * but we want Swing to have this functionality also. */ - if (xev.get_type() == ButtonPress) { + if (xev.get_type() == XConstants.ButtonPress) { final XWindowPeer parentXWindow = getParentTopLevel(); Window parentWindow = (Window)parentXWindow.getTarget(); if (parentXWindow.isFocusableWindow() && parentXWindow.isSimpleWindow() && @@ -841,7 +841,7 @@ public class XComponentPeer extends XWindow implements ComponentPeer, DropTarget XSetWindowAttributes xwa = new XSetWindowAttributes(); xwa.set_cursor(xcursor); - long valuemask = XlibWrapper.CWCursor; + long valuemask = XConstants.CWCursor; XlibWrapper.XChangeWindowAttributes(XToolkit.getDisplay(),getWindow(),valuemask,xwa.pData); XlibWrapper.XFlush(XToolkit.getDisplay()); @@ -1342,20 +1342,20 @@ public class XComponentPeer extends XWindow implements ComponentPeer, DropTarget enableLog.log(Level.FINEST, "Component is {1}, checking for disabled event {0}", new Object[] {e, (isEnabled()?"enabled":"disable")}); if (!isEnabled()) { switch (e.get_type()) { - case ButtonPress: - case ButtonRelease: - case KeyPress: - case KeyRelease: - case EnterNotify: - case LeaveNotify: - case MotionNotify: + case XConstants.ButtonPress: + case XConstants.ButtonRelease: + case XConstants.KeyPress: + case XConstants.KeyRelease: + case XConstants.EnterNotify: + case XConstants.LeaveNotify: + case XConstants.MotionNotify: enableLog.log(Level.FINER, "Event {0} is disable", new Object[] {e}); return true; } } switch(e.get_type()) { - case MapNotify: - case UnmapNotify: + case XConstants.MapNotify: + case XConstants.UnmapNotify: return true; } return super.isEventDisabled(e); diff --git a/jdk/src/solaris/classes/sun/awt/X11/XConstants.java b/jdk/src/solaris/classes/sun/awt/X11/XConstants.java index 4c75f03fd34..e9de6804bea 100644 --- a/jdk/src/solaris/classes/sun/awt/X11/XConstants.java +++ b/jdk/src/solaris/classes/sun/awt/X11/XConstants.java @@ -1,5 +1,5 @@ /* - * Copyright 2003 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2003-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,7 +25,10 @@ package sun.awt.X11; -public interface XConstants { +final public class XConstants { + + private XConstants(){} + public static final int X_PROTOCOL = 11 ; /* current protocol version */ public static final int X_PROTOCOL_REVISION = 0 ; /* current minor version */ @@ -292,9 +295,9 @@ public interface XConstants { public static final int RevertToParent = 2 ; /* Used in XEventsQueued */ - int QueuedAlready = 0; - int QueuedAfterReading = 1; - int QueuedAfterFlush = 2; + public static final int QueuedAlready = 0; + public static final int QueuedAfterReading = 1; + public static final int QueuedAfterFlush = 2; /***************************************************************** diff --git a/jdk/src/solaris/classes/sun/awt/X11/XContentWindow.java b/jdk/src/solaris/classes/sun/awt/X11/XContentWindow.java index 268f7f5d151..6a32fe9bdc3 100644 --- a/jdk/src/solaris/classes/sun/awt/X11/XContentWindow.java +++ b/jdk/src/solaris/classes/sun/awt/X11/XContentWindow.java @@ -43,7 +43,7 @@ import sun.awt.ComponentAccessor; * It should always be located at (- left inset, - top inset) in the associated * decorated window. So coordinates in it would be the same as java coordinates. */ -public final class XContentWindow extends XWindow implements XConstants { +public final class XContentWindow extends XWindow { private static Logger insLog = Logger.getLogger("sun.awt.X11.insets.XContentWindow"); static XContentWindow createContent(XDecoratedPeer parentFrame) { @@ -76,10 +76,10 @@ public final class XContentWindow extends XWindow implements XConstants { void preInit(XCreateWindowParams params) { super.preInit(params); - params.putIfNull(BIT_GRAVITY, Integer.valueOf(NorthWestGravity)); + params.putIfNull(BIT_GRAVITY, Integer.valueOf(XConstants.NorthWestGravity)); Long eventMask = (Long)params.get(EVENT_MASK); if (eventMask != null) { - eventMask = eventMask & ~(StructureNotifyMask); + eventMask = eventMask & ~(XConstants.StructureNotifyMask); params.put(EVENT_MASK, eventMask); } } @@ -90,15 +90,15 @@ public final class XContentWindow extends XWindow implements XConstants { protected boolean isEventDisabled(XEvent e) { switch (e.get_type()) { // Override parentFrame to receive MouseEnter/Exit - case EnterNotify: - case LeaveNotify: + case XConstants.EnterNotify: + case XConstants.LeaveNotify: return false; // We handle ConfigureNotify specifically in XDecoratedPeer - case ConfigureNotify: + case XConstants.ConfigureNotify: return true; // We don't want SHOWN/HIDDEN on content window since it will duplicate XDecoratedPeer - case MapNotify: - case UnmapNotify: + case XConstants.MapNotify: + case XConstants.UnmapNotify: return true; default: return super.isEventDisabled(e) || parentFrame.isEventDisabled(e); diff --git a/jdk/src/solaris/classes/sun/awt/X11/XCursorFontConstants.java b/jdk/src/solaris/classes/sun/awt/X11/XCursorFontConstants.java index d57041523ca..baf33ab3b15 100644 --- a/jdk/src/solaris/classes/sun/awt/X11/XCursorFontConstants.java +++ b/jdk/src/solaris/classes/sun/awt/X11/XCursorFontConstants.java @@ -1,5 +1,5 @@ /* - * Copyright 2003 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2003-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,7 +25,10 @@ package sun.awt.X11; -public interface XCursorFontConstants { +final public class XCursorFontConstants { + + private XCursorFontConstants(){} + /* cursorfont defines */ static final int XC_num_glyphs=154; static final int XC_X_cursor=0; diff --git a/jdk/src/solaris/classes/sun/awt/X11/XCustomCursor.java b/jdk/src/solaris/classes/sun/awt/X11/XCustomCursor.java index 32f269595b0..d308ffd774c 100644 --- a/jdk/src/solaris/classes/sun/awt/X11/XCustomCursor.java +++ b/jdk/src/solaris/classes/sun/awt/X11/XCustomCursor.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2007 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2003-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -83,7 +83,7 @@ public class XCustomCursor extends X11CustomCursor { long colormap = XToolkit.getDefaultXColormap(); XColor fore_color = new XColor(); - fore_color.set_flags((byte) (XlibWrapper.DoRed | XlibWrapper.DoGreen | XlibWrapper.DoBlue)); + fore_color.set_flags((byte) (XConstants.DoRed | XConstants.DoGreen | XConstants.DoBlue)); fore_color.set_red((short)(((fcolor >> 16) & 0x000000ff) << 8)); fore_color.set_green((short) (((fcolor >> 8) & 0x000000ff) << 8)); fore_color.set_blue((short)(((fcolor >> 0) & 0x000000ff) << 8)); @@ -92,7 +92,7 @@ public class XCustomCursor extends X11CustomCursor { XColor back_color = new XColor(); - back_color.set_flags((byte) (XlibWrapper.DoRed | XlibWrapper.DoGreen | XlibWrapper.DoBlue)); + back_color.set_flags((byte) (XConstants.DoRed | XConstants.DoGreen | XConstants.DoBlue)); back_color.set_red((short) (((bcolor >> 16) & 0x000000ff) << 8)); back_color.set_green((short) (((bcolor >> 8) & 0x000000ff) << 8)); diff --git a/jdk/src/solaris/classes/sun/awt/X11/XDecoratedPeer.java b/jdk/src/solaris/classes/sun/awt/X11/XDecoratedPeer.java index a930dfb2be8..aea3baac72b 100644 --- a/jdk/src/solaris/classes/sun/awt/X11/XDecoratedPeer.java +++ b/jdk/src/solaris/classes/sun/awt/X11/XDecoratedPeer.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2007 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2002-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -89,7 +89,7 @@ abstract class XDecoratedPeer extends XWindowPeer { // Deny default processing of these events on the shell - proxy will take care of // them instead Long eventMask = (Long)params.get(EVENT_MASK); - params.add(EVENT_MASK, Long.valueOf(eventMask.longValue() & ~(FocusChangeMask | KeyPressMask | KeyReleaseMask))); + params.add(EVENT_MASK, Long.valueOf(eventMask.longValue() & ~(XConstants.FocusChangeMask | XConstants.KeyPressMask | XConstants.KeyReleaseMask))); } void postInit(XCreateWindowParams params) { @@ -131,7 +131,7 @@ abstract class XDecoratedPeer extends XWindowPeer { int minHeight = minimumSize.height - insets.top - insets.bottom; if (minWidth < 0) minWidth = 0; if (minHeight < 0) minHeight = 0; - setSizeHints(XlibWrapper.PMinSize | (isLocationByPlatform()?0:(XlibWrapper.PPosition | XlibWrapper.USPosition)), + setSizeHints(XUtilConstants.PMinSize | (isLocationByPlatform()?0:(XUtilConstants.PPosition | XUtilConstants.USPosition)), getX(), getY(), minWidth, minHeight); if (isVisible()) { Rectangle bounds = getShellBounds(); @@ -143,7 +143,7 @@ abstract class XDecoratedPeer extends XWindowPeer { } } else { boolean isMinSizeSet = isMinSizeSet(); - XWM.removeSizeHints(this, XlibWrapper.PMinSize); + XWM.removeSizeHints(this, XUtilConstants.PMinSize); /* Some WMs need remap to redecorate the window */ if (isMinSizeSet && isShowing() && XWM.needRemap(this)) { /* @@ -365,7 +365,7 @@ abstract class XDecoratedPeer extends XWindowPeer { return; } - if ((getHints().get_flags() & (USPosition | PPosition)) != 0) { + if ((getHints().get_flags() & (XUtilConstants.USPosition | XUtilConstants.PPosition)) != 0) { reshape(dimensions, SET_BOUNDS, false); } else { reshape(dimensions, SET_SIZE, false); @@ -841,10 +841,10 @@ abstract class XDecoratedPeer extends XWindowPeer { setReparented(false); } winAttr.isResizable = resizable; - if ((fs & MWM_FUNC_ALL) != 0) { - fs &= ~(MWM_FUNC_RESIZE | MWM_FUNC_MAXIMIZE); + if ((fs & MWMConstants.MWM_FUNC_ALL) != 0) { + fs &= ~(MWMConstants.MWM_FUNC_RESIZE | MWMConstants.MWM_FUNC_MAXIMIZE); } else { - fs |= (MWM_FUNC_RESIZE | MWM_FUNC_MAXIMIZE); + fs |= (MWMConstants.MWM_FUNC_RESIZE | MWMConstants.MWM_FUNC_MAXIMIZE); } winAttr.functions = fs; XWM.setShellResizable(this); @@ -855,10 +855,10 @@ abstract class XDecoratedPeer extends XWindowPeer { setReparented(false); } winAttr.isResizable = resizable; - if ((fs & MWM_FUNC_ALL) != 0) { - fs |= (MWM_FUNC_RESIZE | MWM_FUNC_MAXIMIZE); + if ((fs & MWMConstants.MWM_FUNC_ALL) != 0) { + fs |= (MWMConstants.MWM_FUNC_RESIZE | MWMConstants.MWM_FUNC_MAXIMIZE); } else { - fs &= ~(MWM_FUNC_RESIZE | MWM_FUNC_MAXIMIZE); + fs &= ~(MWMConstants.MWM_FUNC_RESIZE | MWMConstants.MWM_FUNC_MAXIMIZE); } winAttr.functions = fs; XWM.setShellNotResizable(this, dimensions, dimensions.getBounds(), false); @@ -936,10 +936,10 @@ abstract class XDecoratedPeer extends XWindowPeer { protected boolean isEventDisabled(XEvent e) { switch (e.get_type()) { // Do not generate MOVED/RESIZED events since we generate them by ourselves - case ConfigureNotify: + case XConstants.ConfigureNotify: return true; - case EnterNotify: - case LeaveNotify: + case XConstants.EnterNotify: + case XConstants.LeaveNotify: // Disable crossing event on outer borders of Frame so // we receive only one set of cross notifications(first set is from content window) return true; @@ -964,7 +964,7 @@ abstract class XDecoratedPeer extends XWindowPeer { if (winAttr.isResizable) { //Fix for 4320050: Minimum size for java.awt.Frame is not being enforced. //We need to update frame's minimum size, not to reset it - XWM.removeSizeHints(this, XlibWrapper.PMaxSize); + XWM.removeSizeHints(this, XUtilConstants.PMaxSize); updateMinimumSize(); } } else { diff --git a/jdk/src/solaris/classes/sun/awt/X11/XDialogPeer.java b/jdk/src/solaris/classes/sun/awt/X11/XDialogPeer.java index 40822e2c27d..2f81c9fe681 100644 --- a/jdk/src/solaris/classes/sun/awt/X11/XDialogPeer.java +++ b/jdk/src/solaris/classes/sun/awt/X11/XDialogPeer.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2007 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2002-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -51,7 +51,7 @@ class XDialogPeer extends XDecoratedPeer implements DialogPeer { } else { winAttr.decorations = winAttr.AWT_DECOR_NONE; } - winAttr.functions = MWM_FUNC_ALL; + winAttr.functions = MWMConstants.MWM_FUNC_ALL; winAttr.isResizable = true; //target.isResizable(); winAttr.initialResizability = target.isResizable(); winAttr.title = target.getTitle(); @@ -100,10 +100,10 @@ class XDialogPeer extends XDecoratedPeer implements DialogPeer { int getDecorations() { int d = super.getDecorations(); // remove minimize and maximize buttons for dialogs - if ((d & MWM_DECOR_ALL) != 0) { - d |= (MWM_DECOR_MINIMIZE | MWM_DECOR_MAXIMIZE); + if ((d & MWMConstants.MWM_DECOR_ALL) != 0) { + d |= (MWMConstants.MWM_DECOR_MINIMIZE | MWMConstants.MWM_DECOR_MAXIMIZE); } else { - d &= ~(MWM_DECOR_MINIMIZE | MWM_DECOR_MAXIMIZE); + d &= ~(MWMConstants.MWM_DECOR_MINIMIZE | MWMConstants.MWM_DECOR_MAXIMIZE); } return d; } @@ -111,10 +111,10 @@ class XDialogPeer extends XDecoratedPeer implements DialogPeer { int getFunctions() { int f = super.getFunctions(); // remove minimize and maximize functions for dialogs - if ((f & MWM_FUNC_ALL) != 0) { - f |= (MWM_FUNC_MINIMIZE | MWM_FUNC_MAXIMIZE); + if ((f & MWMConstants.MWM_FUNC_ALL) != 0) { + f |= (MWMConstants.MWM_FUNC_MINIMIZE | MWMConstants.MWM_FUNC_MAXIMIZE); } else { - f &= ~(MWM_FUNC_MINIMIZE | MWM_FUNC_MAXIMIZE); + f &= ~(MWMConstants.MWM_FUNC_MINIMIZE | MWMConstants.MWM_FUNC_MAXIMIZE); } return f; } diff --git a/jdk/src/solaris/classes/sun/awt/X11/XDnDDragSourceProtocol.java b/jdk/src/solaris/classes/sun/awt/X11/XDnDDragSourceProtocol.java index 5c2a329eea6..62ae6219244 100644 --- a/jdk/src/solaris/classes/sun/awt/X11/XDnDDragSourceProtocol.java +++ b/jdk/src/solaris/classes/sun/awt/X11/XDnDDragSourceProtocol.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2005 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2003-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -103,7 +103,7 @@ class XDnDDragSourceProtocol extends XDragSourceProtocol { XToolkit.RESTORE_XERROR_HANDLER(); if (XToolkit.saved_error != null && - XToolkit.saved_error.get_error_code() != XlibWrapper.Success) { + XToolkit.saved_error.get_error_code() != XConstants.Success) { cleanup(); throw new XException("Cannot write XdndActionList property"); } @@ -124,7 +124,7 @@ class XDnDDragSourceProtocol extends XDragSourceProtocol { XToolkit.RESTORE_XERROR_HANDLER(); if (XToolkit.saved_error != null && - XToolkit.saved_error.get_error_code() != XlibWrapper.Success) { + XToolkit.saved_error.get_error_code() != XConstants.Success) { cleanup(); throw new XException("Cannot write XdndActionList property"); } @@ -134,7 +134,7 @@ class XDnDDragSourceProtocol extends XDragSourceProtocol { } if (!XDnDConstants.XDnDSelection.setOwner(contents, formatMap, formats, - XlibWrapper.CurrentTime)) { + XConstants.CurrentTime)) { cleanup(); throw new InvalidDnDOperationException("Cannot acquire selection ownership"); } @@ -193,11 +193,11 @@ class XDnDDragSourceProtocol extends XDragSourceProtocol { WindowPropertyGetter wpg1 = new WindowPropertyGetter(window, XDnDConstants.XA_XdndAware, 0, 1, - false, XlibWrapper.AnyPropertyType); + false, XConstants.AnyPropertyType); int status = wpg1.execute(XToolkit.IgnoreBadWindowHandler); - if (status == XlibWrapper.Success && + if (status == XConstants.Success && wpg1.getData() != 0 && wpg1.getActualType() == XAtom.XA_ATOM) { int targetVersion = (int)Native.getLong(wpg1.getData()); @@ -217,7 +217,7 @@ class XDnDDragSourceProtocol extends XDragSourceProtocol { try { status = wpg2.execute(XToolkit.IgnoreBadWindowHandler); - if (status == XlibWrapper.Success && + if (status == XConstants.Success && wpg2.getData() != 0 && wpg2.getActualType() == XAtom.XA_WINDOW) { @@ -235,7 +235,7 @@ class XDnDDragSourceProtocol extends XDragSourceProtocol { try { status = wpg3.execute(XToolkit.IgnoreBadWindowHandler); - if (status != XlibWrapper.Success || + if (status != XConstants.Success || wpg3.getData() == 0 || wpg3.getActualType() != XAtom.XA_WINDOW || Native.getLong(wpg3.getData()) != proxy) { @@ -246,12 +246,12 @@ class XDnDDragSourceProtocol extends XDragSourceProtocol { new WindowPropertyGetter(proxy, XDnDConstants.XA_XdndAware, 0, 1, false, - XlibWrapper.AnyPropertyType); + XConstants.AnyPropertyType); try { status = wpg4.execute(XToolkit.IgnoreBadWindowHandler); - if (status != XlibWrapper.Success || + if (status != XConstants.Success || wpg4.getData() == 0 || wpg4.getActualType() != XAtom.XA_ATOM) { @@ -283,7 +283,7 @@ class XDnDDragSourceProtocol extends XDragSourceProtocol { XClientMessageEvent msg = new XClientMessageEvent(); try { - msg.set_type((int)XlibWrapper.ClientMessage); + msg.set_type((int)XConstants.ClientMessage); msg.set_window(getTargetWindow()); msg.set_format(32); msg.set_message_type(XDnDConstants.XA_XdndEnter.getAtom()); @@ -297,7 +297,7 @@ class XDnDDragSourceProtocol extends XDragSourceProtocol { msg.set_data(4, formats.length > 2 ? formats[2] : 0); XlibWrapper.XSendEvent(XToolkit.getDisplay(), getTargetProxyWindow(), - false, XlibWrapper.NoEventMask, + false, XConstants.NoEventMask, msg.pData); } finally { msg.dispose(); @@ -311,7 +311,7 @@ class XDnDDragSourceProtocol extends XDragSourceProtocol { XClientMessageEvent msg = new XClientMessageEvent(); try { - msg.set_type((int)XlibWrapper.ClientMessage); + msg.set_type((int)XConstants.ClientMessage); msg.set_window(getTargetWindow()); msg.set_format(32); msg.set_message_type(XDnDConstants.XA_XdndPosition.getAtom()); @@ -322,7 +322,7 @@ class XDnDDragSourceProtocol extends XDragSourceProtocol { msg.set_data(4, XDnDConstants.getXDnDActionForJavaAction(sourceAction)); XlibWrapper.XSendEvent(XToolkit.getDisplay(), getTargetProxyWindow(), - false, XlibWrapper.NoEventMask, + false, XConstants.NoEventMask, msg.pData); } finally { msg.dispose(); @@ -335,7 +335,7 @@ class XDnDDragSourceProtocol extends XDragSourceProtocol { XClientMessageEvent msg = new XClientMessageEvent(); try { - msg.set_type((int)XlibWrapper.ClientMessage); + msg.set_type((int)XConstants.ClientMessage); msg.set_window(getTargetWindow()); msg.set_format(32); msg.set_message_type(XDnDConstants.XA_XdndLeave.getAtom()); @@ -346,7 +346,7 @@ class XDnDDragSourceProtocol extends XDragSourceProtocol { msg.set_data(4, 0); XlibWrapper.XSendEvent(XToolkit.getDisplay(), getTargetProxyWindow(), - false, XlibWrapper.NoEventMask, + false, XConstants.NoEventMask, msg.pData); } finally { msg.dispose(); @@ -361,7 +361,7 @@ class XDnDDragSourceProtocol extends XDragSourceProtocol { XClientMessageEvent msg = new XClientMessageEvent(); try { - msg.set_type((int)XlibWrapper.ClientMessage); + msg.set_type((int)XConstants.ClientMessage); msg.set_window(getTargetWindow()); msg.set_format(32); msg.set_message_type(XDnDConstants.XA_XdndDrop.getAtom()); @@ -372,7 +372,7 @@ class XDnDDragSourceProtocol extends XDragSourceProtocol { msg.set_data(4, 0); XlibWrapper.XSendEvent(XToolkit.getDisplay(), getTargetProxyWindow(), - false, XlibWrapper.NoEventMask, + false, XConstants.NoEventMask, msg.pData); } finally { msg.dispose(); @@ -406,7 +406,7 @@ class XDnDDragSourceProtocol extends XDragSourceProtocol { assert XToolkit.isAWTLockHeldByCurrentThread(); XlibWrapper.XSendEvent(XToolkit.getDisplay(), sourceWindow, - false, XlibWrapper.NoEventMask, + false, XConstants.NoEventMask, xclient.pData); return true; diff --git a/jdk/src/solaris/classes/sun/awt/X11/XDnDDropTargetProtocol.java b/jdk/src/solaris/classes/sun/awt/X11/XDnDDropTargetProtocol.java index 00fe0430d36..5b518321626 100644 --- a/jdk/src/solaris/classes/sun/awt/X11/XDnDDropTargetProtocol.java +++ b/jdk/src/solaris/classes/sun/awt/X11/XDnDDropTargetProtocol.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2005 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2003-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -93,7 +93,7 @@ class XDnDDropTargetProtocol extends XDropTargetProtocol { XToolkit.RESTORE_XERROR_HANDLER(); if (XToolkit.saved_error != null && - XToolkit.saved_error.get_error_code() != XlibWrapper.Success) { + XToolkit.saved_error.get_error_code() != XConstants.Success) { throw new XException("Cannot write XdndAware property"); } } finally { @@ -119,12 +119,12 @@ class XDnDDropTargetProtocol extends XDropTargetProtocol { WindowPropertyGetter wpg1 = new WindowPropertyGetter(embedder, XDnDConstants.XA_XdndAware, 0, 1, - false, XlibWrapper.AnyPropertyType); + false, XConstants.AnyPropertyType); try { status = wpg1.execute(XToolkit.IgnoreBadWindowHandler); - if (status == XlibWrapper.Success && + if (status == XConstants.Success && wpg1.getData() != 0 && wpg1.getActualType() == XAtom.XA_ATOM) { overriden = true; @@ -143,7 +143,7 @@ class XDnDDropTargetProtocol extends XDropTargetProtocol { try { status = wpg2.execute(XToolkit.IgnoreBadWindowHandler); - if (status == XlibWrapper.Success && + if (status == XConstants.Success && wpg2.getData() != 0 && wpg2.getActualType() == XAtom.XA_WINDOW) { @@ -161,7 +161,7 @@ class XDnDDropTargetProtocol extends XDropTargetProtocol { try { status = wpg3.execute(XToolkit.IgnoreBadWindowHandler); - if (status != XlibWrapper.Success || + if (status != XConstants.Success || wpg3.getData() == 0 || wpg3.getActualType() != XAtom.XA_WINDOW || Native.getLong(wpg3.getData()) != proxy) { @@ -172,12 +172,12 @@ class XDnDDropTargetProtocol extends XDropTargetProtocol { new WindowPropertyGetter(proxy, XDnDConstants.XA_XdndAware, 0, 1, false, - XlibWrapper.AnyPropertyType); + XConstants.AnyPropertyType); try { status = wpg4.execute(XToolkit.IgnoreBadWindowHandler); - if (status != XlibWrapper.Success || + if (status != XConstants.Success || wpg4.getData() == 0 || wpg4.getActualType() != XAtom.XA_ATOM) { @@ -212,7 +212,7 @@ class XDnDDropTargetProtocol extends XDropTargetProtocol { if (XToolkit.saved_error != null && XToolkit.saved_error.get_error_code() != - XlibWrapper.Success) { + XConstants.Success) { throw new XException("Cannot write XdndAware property"); } @@ -226,7 +226,7 @@ class XDnDDropTargetProtocol extends XDropTargetProtocol { if (XToolkit.saved_error != null && XToolkit.saved_error.get_error_code() != - XlibWrapper.Success) { + XConstants.Success) { throw new XException("Cannot write XdndProxy property"); } @@ -239,7 +239,7 @@ class XDnDDropTargetProtocol extends XDropTargetProtocol { if (XToolkit.saved_error != null && XToolkit.saved_error.get_error_code() != - XlibWrapper.Success) { + XConstants.Success) { throw new XException("Cannot write XdndAware property"); } @@ -252,7 +252,7 @@ class XDnDDropTargetProtocol extends XDropTargetProtocol { if (XToolkit.saved_error != null && XToolkit.saved_error.get_error_code() != - XlibWrapper.Success) { + XConstants.Success) { throw new XException("Cannot write XdndProxy property"); } } finally { @@ -285,7 +285,7 @@ class XDnDDropTargetProtocol extends XDropTargetProtocol { if (XToolkit.saved_error != null && XToolkit.saved_error.get_error_code() != - XlibWrapper.Success) { + XConstants.Success) { throw new XException("Cannot write XdndAware property"); } @@ -298,7 +298,7 @@ class XDnDDropTargetProtocol extends XDropTargetProtocol { if (XToolkit.saved_error != null && XToolkit.saved_error.get_error_code() != - XlibWrapper.Success) { + XConstants.Success) { throw new XException("Cannot write XdndProxy property"); } } finally { @@ -326,12 +326,12 @@ class XDnDDropTargetProtocol extends XDropTargetProtocol { WindowPropertyGetter wpg1 = new WindowPropertyGetter(embedded, XDnDConstants.XA_XdndAware, 0, 1, - false, XlibWrapper.AnyPropertyType); + false, XConstants.AnyPropertyType); try { status = wpg1.execute(XToolkit.IgnoreBadWindowHandler); - if (status == XlibWrapper.Success && + if (status == XConstants.Success && wpg1.getData() != 0 && wpg1.getActualType() == XAtom.XA_ATOM) { overriden = true; @@ -350,7 +350,7 @@ class XDnDDropTargetProtocol extends XDropTargetProtocol { try { status = wpg2.execute(XToolkit.IgnoreBadWindowHandler); - if (status == XlibWrapper.Success && + if (status == XConstants.Success && wpg2.getData() != 0 && wpg2.getActualType() == XAtom.XA_WINDOW) { @@ -368,7 +368,7 @@ class XDnDDropTargetProtocol extends XDropTargetProtocol { try { status = wpg3.execute(XToolkit.IgnoreBadWindowHandler); - if (status != XlibWrapper.Success || + if (status != XConstants.Success || wpg3.getData() == 0 || wpg3.getActualType() != XAtom.XA_WINDOW || Native.getLong(wpg3.getData()) != proxy) { @@ -379,12 +379,12 @@ class XDnDDropTargetProtocol extends XDropTargetProtocol { new WindowPropertyGetter(proxy, XDnDConstants.XA_XdndAware, 0, 1, false, - XlibWrapper.AnyPropertyType); + XConstants.AnyPropertyType); try { status = wpg4.execute(XToolkit.IgnoreBadWindowHandler); - if (status != XlibWrapper.Success || + if (status != XConstants.Success || wpg4.getData() == 0 || wpg4.getActualType() != XAtom.XA_ATOM) { @@ -408,12 +408,12 @@ class XDnDDropTargetProtocol extends XDropTargetProtocol { WindowPropertyGetter wpg1 = new WindowPropertyGetter(window, XDnDConstants.XA_XdndAware, 0, 1, - false, XlibWrapper.AnyPropertyType); + false, XConstants.AnyPropertyType); try { int status = wpg1.execute(XToolkit.IgnoreBadWindowHandler); - if (status == XlibWrapper.Success && + if (status == XConstants.Success && wpg1.getData() != 0 && wpg1.getActualType() == XAtom.XA_ATOM) { return true; @@ -523,7 +523,7 @@ class XDnDDropTargetProtocol extends XDropTargetProtocol { for (int i = 0; i < 3; i++) { long j; - if ((j = xclient.get_data(2 + i)) != XlibWrapper.None) { + if ((j = xclient.get_data(2 + i)) != XConstants.None) { formats3[countFormats++] = j; } } @@ -549,7 +549,7 @@ class XDnDDropTargetProtocol extends XDropTargetProtocol { if (status == 0 || (XToolkit.saved_error != null && - XToolkit.saved_error.get_error_code() != XlibWrapper.Success)) { + XToolkit.saved_error.get_error_code() != XConstants.Success)) { throw new XException("XGetWindowAttributes failed"); } @@ -561,12 +561,12 @@ class XDnDDropTargetProtocol extends XDropTargetProtocol { XToolkit.WITH_XERROR_HANDLER(XToolkit.IgnoreBadWindowHandler); XlibWrapper.XSelectInput(XToolkit.getDisplay(), source_win, source_win_mask | - XlibWrapper.StructureNotifyMask); + XConstants.StructureNotifyMask); XToolkit.RESTORE_XERROR_HANDLER(); if (XToolkit.saved_error != null && - XToolkit.saved_error.get_error_code() != XlibWrapper.Success) { + XToolkit.saved_error.get_error_code() != XConstants.Success) { throw new XException("XSelectInput failed"); } @@ -581,7 +581,7 @@ class XDnDDropTargetProtocol extends XDropTargetProtocol { } private boolean processXdndPosition(XClientMessageEvent xclient) { - long time_stamp = (int)XlibWrapper.CurrentTime; + long time_stamp = (int)XConstants.CurrentTime; long xdnd_action = 0; int java_action = DnDConstants.ACTION_NONE; int x = 0; @@ -748,7 +748,7 @@ class XDnDDropTargetProtocol extends XDropTargetProtocol { long data3, long data4) { XClientMessageEvent enter = new XClientMessageEvent(); try { - enter.set_type((int)XlibWrapper.ClientMessage); + enter.set_type((int)XConstants.ClientMessage); enter.set_window(toplevel); enter.set_format(32); enter.set_message_type(XDnDConstants.XA_XdndEnter.getAtom()); @@ -774,7 +774,7 @@ class XDnDDropTargetProtocol extends XDropTargetProtocol { long sourceWindow) { XClientMessageEvent leave = new XClientMessageEvent(); try { - leave.set_type((int)XlibWrapper.ClientMessage); + leave.set_type((int)XConstants.ClientMessage); leave.set_window(toplevel); leave.set_format(32); leave.set_message_type(XDnDConstants.XA_XdndLeave.getAtom()); @@ -804,7 +804,7 @@ class XDnDDropTargetProtocol extends XDropTargetProtocol { XClientMessageEvent msg = new XClientMessageEvent(); try { - msg.set_type((int)XlibWrapper.ClientMessage); + msg.set_type((int)XConstants.ClientMessage); msg.set_window(xclient.get_data(0)); msg.set_format(32); msg.set_message_type(XDnDConstants.XA_XdndStatus.getAtom()); @@ -826,7 +826,7 @@ class XDnDDropTargetProtocol extends XDropTargetProtocol { try { XlibWrapper.XSendEvent(XToolkit.getDisplay(), xclient.get_data(0), - false, XlibWrapper.NoEventMask, + false, XConstants.NoEventMask, msg.pData); } finally { XToolkit.awtUnlock(); @@ -842,7 +842,7 @@ class XDnDDropTargetProtocol extends XDropTargetProtocol { throws IllegalArgumentException, IOException { XClientMessageEvent xclient = new XClientMessageEvent(ctxt); long message_type = xclient.get_message_type(); - long time_stamp = XlibWrapper.CurrentTime; + long time_stamp = XConstants.CurrentTime; // NOTE: we assume that the source supports at least version 1, so we // can use the time stamp @@ -892,7 +892,7 @@ class XDnDDropTargetProtocol extends XDropTargetProtocol { XClientMessageEvent msg = new XClientMessageEvent(); try { - msg.set_type((int)XlibWrapper.ClientMessage); + msg.set_type((int)XConstants.ClientMessage); msg.set_window(xclient.get_data(0)); msg.set_format(32); msg.set_message_type(XDnDConstants.XA_XdndFinished.getAtom()); @@ -914,7 +914,7 @@ class XDnDDropTargetProtocol extends XDropTargetProtocol { try { XlibWrapper.XSendEvent(XToolkit.getDisplay(), xclient.get_data(0), - false, XlibWrapper.NoEventMask, + false, XConstants.NoEventMask, msg.pData); } finally { XToolkit.awtUnlock(); @@ -1119,7 +1119,7 @@ class XDnDDropTargetProtocol extends XDropTargetProtocol { XToolkit.RESTORE_XERROR_HANDLER(); if (XToolkit.saved_error != null && - XToolkit.saved_error.get_error_code() != XlibWrapper.Success) { + XToolkit.saved_error.get_error_code() != XConstants.Success) { if (logger.isLoggable(Level.WARNING)) { logger.warning("Cannot set XdndTypeList on the proxy window"); } diff --git a/jdk/src/solaris/classes/sun/awt/X11/XDragSourceContextPeer.java b/jdk/src/solaris/classes/sun/awt/X11/XDragSourceContextPeer.java index 48ecd886c21..af3a3219cff 100644 --- a/jdk/src/solaris/classes/sun/awt/X11/XDragSourceContextPeer.java +++ b/jdk/src/solaris/classes/sun/awt/X11/XDragSourceContextPeer.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2007 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2003-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -55,11 +55,11 @@ public final class XDragSourceContextPeer Logger.getLogger("sun.awt.X11.xembed.xdnd.XDragSourceContextPeer"); /* The events selected on the root window when the drag begins. */ - private static final int ROOT_EVENT_MASK = (int)XlibWrapper.ButtonMotionMask | - (int)XlibWrapper.KeyPressMask | (int)XlibWrapper.KeyReleaseMask; + private static final int ROOT_EVENT_MASK = (int)XConstants.ButtonMotionMask | + (int)XConstants.KeyPressMask | (int)XConstants.KeyReleaseMask; /* The events to be delivered during grab. */ - private static final int GRAB_EVENT_MASK = (int)XlibWrapper.ButtonPressMask | - (int)XlibWrapper.ButtonMotionMask | (int)XlibWrapper.ButtonReleaseMask; + private static final int GRAB_EVENT_MASK = (int)XConstants.ButtonPressMask | + (int)XConstants.ButtonMotionMask | (int)XConstants.ButtonReleaseMask; /* The event mask of the root window before the drag operation starts. */ private long rootEventMask = 0; @@ -196,11 +196,11 @@ public final class XDragSourceContextPeer status = XlibWrapper.XGrabPointer(XToolkit.getDisplay(), rootWindow, 0, GRAB_EVENT_MASK, - XlibWrapper.GrabModeAsync, - XlibWrapper.GrabModeAsync, - XlibWrapper.None, xcursor, timeStamp); + XConstants.GrabModeAsync, + XConstants.GrabModeAsync, + XConstants.None, xcursor, timeStamp); - if (status != XlibWrapper.GrabSuccess) { + if (status != XConstants.GrabSuccess) { cleanup(timeStamp); throwGrabFailureException("Cannot grab pointer", status); return; @@ -208,11 +208,11 @@ public final class XDragSourceContextPeer status = XlibWrapper.XGrabKeyboard(XToolkit.getDisplay(), rootWindow, 0, - XlibWrapper.GrabModeAsync, - XlibWrapper.GrabModeAsync, + XConstants.GrabModeAsync, + XConstants.GrabModeAsync, timeStamp); - if (status != XlibWrapper.GrabSuccess) { + if (status != XConstants.GrabSuccess) { cleanup(timeStamp); throwGrabFailureException("Cannot grab keyboard", status); return; @@ -276,7 +276,7 @@ public final class XDragSourceContextPeer XlibWrapper.XChangeActivePointerGrab(XToolkit.getDisplay(), GRAB_EVENT_MASK, xcursor, - XlibWrapper.CurrentTime); + XConstants.CurrentTime); } protected boolean needsBogusExitBeforeDrop() { @@ -287,10 +287,10 @@ public final class XDragSourceContextPeer throws InvalidDnDOperationException { String msgCause = ""; switch (grabStatus) { - case XlibWrapper.GrabNotViewable: msgCause = "not viewable"; break; - case XlibWrapper.AlreadyGrabbed: msgCause = "already grabbed"; break; - case XlibWrapper.GrabInvalidTime: msgCause = "invalid time"; break; - case XlibWrapper.GrabFrozen: msgCause = "grab frozen"; break; + case XConstants.GrabNotViewable: msgCause = "not viewable"; break; + case XConstants.AlreadyGrabbed: msgCause = "already grabbed"; break; + case XConstants.GrabInvalidTime: msgCause = "invalid time"; break; + case XConstants.GrabFrozen: msgCause = "grab frozen"; break; default: msgCause = "unknown failure"; break; } throw new InvalidDnDOperationException(msg + ": " + msgCause); @@ -537,7 +537,7 @@ public final class XDragSourceContextPeer return false; } - if (ev.get_type() != (int)XlibWrapper.ClientMessage) { + if (ev.get_type() != (int)XConstants.ClientMessage) { return false; } @@ -579,18 +579,18 @@ public final class XDragSourceContextPeer } switch (ev.get_type()) { - case XlibWrapper.ClientMessage: { + case XConstants.ClientMessage: { XClientMessageEvent xclient = ev.get_xclient(); return processClientMessage(xclient); } - case XlibWrapper.DestroyNotify: { + case XConstants.DestroyNotify: { XDestroyWindowEvent xde = ev.get_xdestroywindow(); /* Target crashed during drop processing - cleanup. */ if (!dragInProgress && dragProtocol != null && xde.get_window() == dragProtocol.getTargetWindow()) { - cleanup(XlibWrapper.CurrentTime); + cleanup(XConstants.CurrentTime); return true; } /* Pass along */ @@ -604,14 +604,14 @@ public final class XDragSourceContextPeer /* Process drag-only messages. */ switch (ev.get_type()) { - case XlibWrapper.KeyRelease: - case XlibWrapper.KeyPress: { + case XConstants.KeyRelease: + case XConstants.KeyPress: { XKeyEvent xkey = ev.get_xkey(); long keysym = XlibWrapper.XKeycodeToKeysym(XToolkit.getDisplay(), xkey.get_keycode(), 0); switch ((int)keysym) { case (int)XKeySymConstants.XK_Escape: { - if (ev.get_type() == (int)XlibWrapper.KeyRelease) { + if (ev.get_type() == (int)XConstants.KeyRelease) { cleanup(xkey.get_time()); } break; @@ -631,7 +631,7 @@ public final class XDragSourceContextPeer XlibWrapper.larg7); // modifiers XMotionEvent xmotion = new XMotionEvent(); try { - xmotion.set_type(XlibWrapper.MotionNotify); + xmotion.set_type(XConstants.MotionNotify); xmotion.set_serial(xkey.get_serial()); xmotion.set_send_event(xkey.get_send_event()); xmotion.set_display(xkey.get_display()); @@ -658,12 +658,12 @@ public final class XDragSourceContextPeer } return true; } - case XlibWrapper.ButtonPress: + case XConstants.ButtonPress: return true; - case XlibWrapper.MotionNotify: + case XConstants.MotionNotify: processMouseMove(ev.get_xmotion()); return true; - case XlibWrapper.ButtonRelease: { + case XConstants.ButtonRelease: { XButtonEvent xbutton = ev.get_xbutton(); /* * On some X servers it could happen that ButtonRelease coordinates @@ -672,7 +672,7 @@ public final class XDragSourceContextPeer */ XMotionEvent xmotion = new XMotionEvent(); try { - xmotion.set_type(XlibWrapper.MotionNotify); + xmotion.set_type(XConstants.MotionNotify); xmotion.set_serial(xbutton.get_serial()); xmotion.set_send_event(xbutton.get_send_event()); xmotion.set_display(xbutton.get_display()); @@ -694,8 +694,8 @@ public final class XDragSourceContextPeer } finally { xmotion.dispose(); } - if (xbutton.get_button() == XlibWrapper.Button1 - || xbutton.get_button() == XlibWrapper.Button2) { + if (xbutton.get_button() == XConstants.Button1 + || xbutton.get_button() == XConstants.Button2) { // drag is initiated with Button1 or Button2 pressed and // ended on release of either of these buttons (as the same // behavior was with our old Motif DnD-based implementation) @@ -789,6 +789,6 @@ public final class XDragSourceContextPeer dragDropFinished(success, action, x, y); dndInProgress = false; - cleanup(XlibWrapper.CurrentTime); + cleanup(XConstants.CurrentTime); } } diff --git a/jdk/src/solaris/classes/sun/awt/X11/XDragSourceProtocol.java b/jdk/src/solaris/classes/sun/awt/X11/XDragSourceProtocol.java index baf58c48d26..40a7b045834 100644 --- a/jdk/src/solaris/classes/sun/awt/X11/XDragSourceProtocol.java +++ b/jdk/src/solaris/classes/sun/awt/X11/XDragSourceProtocol.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2005 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2003-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -189,7 +189,7 @@ abstract class XDragSourceProtocol { if (status == 0 || (XToolkit.saved_error != null && - XToolkit.saved_error.get_error_code() != XlibWrapper.Success)) { + XToolkit.saved_error.get_error_code() != XConstants.Success)) { throw new XException("XGetWindowAttributes failed"); } @@ -201,12 +201,12 @@ abstract class XDragSourceProtocol { XToolkit.WITH_XERROR_HANDLER(XToolkit.IgnoreBadWindowHandler); XlibWrapper.XSelectInput(XToolkit.getDisplay(), targetWindow, targetWindowMask | - XlibWrapper.StructureNotifyMask); + XConstants.StructureNotifyMask); XToolkit.RESTORE_XERROR_HANDLER(); if (XToolkit.saved_error != null && - XToolkit.saved_error.get_error_code() != XlibWrapper.Success) { + XToolkit.saved_error.get_error_code() != XConstants.Success) { throw new XException("XSelectInput failed"); } diff --git a/jdk/src/solaris/classes/sun/awt/X11/XDropTargetEventProcessor.java b/jdk/src/solaris/classes/sun/awt/X11/XDropTargetEventProcessor.java index 23bdf39a202..d8d6c25d16f 100644 --- a/jdk/src/solaris/classes/sun/awt/X11/XDropTargetEventProcessor.java +++ b/jdk/src/solaris/classes/sun/awt/X11/XDropTargetEventProcessor.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2007 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2003-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -43,7 +43,7 @@ final class XDropTargetEventProcessor { private XDropTargetEventProcessor() {} private boolean doProcessEvent(XEvent ev) { - if (ev.get_type() == (int)XlibWrapper.DestroyNotify && + if (ev.get_type() == (int)XConstants.DestroyNotify && protocol != null && ev.get_xany().get_window() == protocol.getSourceWindow()) { protocol.cleanup(); @@ -51,7 +51,7 @@ final class XDropTargetEventProcessor { return false; } - if (ev.get_type() == (int)XlibWrapper.PropertyNotify) { + if (ev.get_type() == (int)XConstants.PropertyNotify) { XPropertyEvent xproperty = ev.get_xproperty(); if (xproperty.get_atom() == MotifDnDConstants.XA_MOTIF_DRAG_RECEIVER_INFO.getAtom()) { @@ -60,7 +60,7 @@ final class XDropTargetEventProcessor { } } - if (ev.get_type() != (int)XlibWrapper.ClientMessage) { + if (ev.get_type() != (int)XConstants.ClientMessage) { return false; } diff --git a/jdk/src/solaris/classes/sun/awt/X11/XDropTargetProtocol.java b/jdk/src/solaris/classes/sun/awt/X11/XDropTargetProtocol.java index 658b7cbf3d5..7a7c7c10ee2 100644 --- a/jdk/src/solaris/classes/sun/awt/X11/XDropTargetProtocol.java +++ b/jdk/src/solaris/classes/sun/awt/X11/XDropTargetProtocol.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2005 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2003-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -149,7 +149,7 @@ abstract class XDropTargetProtocol { XToolkit.awtLock(); try { XlibWrapper.XSendEvent(XToolkit.getDisplay(), proxy, false, - XlibWrapper.NoEventMask, xclient.pData); + XConstants.NoEventMask, xclient.pData); } finally { XToolkit.awtUnlock(); } diff --git a/jdk/src/solaris/classes/sun/awt/X11/XDropTargetRegistry.java b/jdk/src/solaris/classes/sun/awt/X11/XDropTargetRegistry.java index 2d05578dd04..47353e03ebe 100644 --- a/jdk/src/solaris/classes/sun/awt/X11/XDropTargetRegistry.java +++ b/jdk/src/solaris/classes/sun/awt/X11/XDropTargetRegistry.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2006 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2003-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -27,18 +27,14 @@ package sun.awt.X11; import java.util.ArrayList; import java.util.Collections; -import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; -import java.util.Hashtable; import java.util.Iterator; import java.util.List; import java.util.logging.*; import java.awt.Point; -import sun.awt.dnd.SunDropTargetContextPeer; -import sun.awt.dnd.SunDropTargetEvent; /** * The class responsible for registration/deregistration of drop sites. @@ -179,11 +175,11 @@ final class XDropTargetRegistry { if (status == 0 || (XToolkit.saved_error != null && - XToolkit.saved_error.get_error_code() != XlibWrapper.Success)) { + XToolkit.saved_error.get_error_code() != XConstants.Success)) { continue; } - if (wattr.get_map_state() != XlibWrapper.IsUnmapped + if (wattr.get_map_state() != XConstants.IsUnmapped && dest_x < wattr.get_width() && dest_y < wattr.get_height()) { return window; @@ -233,7 +229,7 @@ final class XDropTargetRegistry { if (status == 0 || (XToolkit.saved_error != null && - XToolkit.saved_error.get_error_code() != XlibWrapper.Success)) { + XToolkit.saved_error.get_error_code() != XConstants.Success)) { throw new XException("XGetWindowAttributes failed"); } @@ -243,14 +239,14 @@ final class XDropTargetRegistry { wattr.dispose(); } - if ((event_mask & XlibWrapper.PropertyChangeMask) == 0) { + if ((event_mask & XConstants.PropertyChangeMask) == 0) { XToolkit.WITH_XERROR_HANDLER(XToolkit.IgnoreBadWindowHandler); XlibWrapper.XSelectInput(XToolkit.getDisplay(), embedder, - event_mask | XlibWrapper.PropertyChangeMask); + event_mask | XConstants.PropertyChangeMask); XToolkit.RESTORE_XERROR_HANDLER(); if (XToolkit.saved_error != null && - XToolkit.saved_error.get_error_code() != XlibWrapper.Success) { + XToolkit.saved_error.get_error_code() != XConstants.Success) { throw new XException("XSelectInput failed"); } } @@ -397,14 +393,14 @@ final class XDropTargetRegistry { long event_mask = entry.getEventMask(); /* Restore the original event mask for the embedder. */ - if ((event_mask & XlibWrapper.PropertyChangeMask) == 0) { + if ((event_mask & XConstants.PropertyChangeMask) == 0) { XToolkit.WITH_XERROR_HANDLER(XToolkit.IgnoreBadWindowHandler); XlibWrapper.XSelectInput(XToolkit.getDisplay(), embedder, event_mask); XToolkit.RESTORE_XERROR_HANDLER(); if (XToolkit.saved_error != null && - XToolkit.saved_error.get_error_code() != XlibWrapper.Success) { + XToolkit.saved_error.get_error_code() != XConstants.Success) { throw new XException("XSelectInput failed"); } } diff --git a/jdk/src/solaris/classes/sun/awt/X11/XEmbedCanvasPeer.java b/jdk/src/solaris/classes/sun/awt/X11/XEmbedCanvasPeer.java index 10b71a453b4..3d2c25658c4 100644 --- a/jdk/src/solaris/classes/sun/awt/X11/XEmbedCanvasPeer.java +++ b/jdk/src/solaris/classes/sun/awt/X11/XEmbedCanvasPeer.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2007 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2003-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -81,10 +81,10 @@ public class XEmbedCanvasPeer extends XCanvasPeer implements WindowFocusListener super.preInit(params); params.put(EVENT_MASK, - KeyPressMask | KeyReleaseMask - | FocusChangeMask | ButtonPressMask | ButtonReleaseMask - | EnterWindowMask | LeaveWindowMask | PointerMotionMask - | ButtonMotionMask | ExposureMask | StructureNotifyMask | SubstructureNotifyMask); + XConstants.KeyPressMask | XConstants.KeyReleaseMask + | XConstants.FocusChangeMask | XConstants.ButtonPressMask | XConstants.ButtonReleaseMask + | XConstants.EnterWindowMask | XConstants.LeaveWindowMask | XConstants.PointerMotionMask + | XConstants.ButtonMotionMask | XConstants.ExposureMask | XConstants.StructureNotifyMask | XConstants.SubstructureNotifyMask); } @@ -134,7 +134,7 @@ public class XEmbedCanvasPeer extends XCanvasPeer implements WindowFocusListener try { XToolkit.addEventDispatcher(xembed.handle, xembed); XlibWrapper.XSelectInput(XToolkit.getDisplay(), xembed.handle, - XlibWrapper.StructureNotifyMask | XlibWrapper.PropertyChangeMask); + XConstants.StructureNotifyMask | XConstants.PropertyChangeMask); XDropTargetRegistry.getRegistry().registerXEmbedClient(getWindow(), xembed.handle); } finally { @@ -194,7 +194,7 @@ public class XEmbedCanvasPeer extends XCanvasPeer implements WindowFocusListener public void dispatchEvent(XEvent ev) { super.dispatchEvent(ev); switch (ev.get_type()) { - case CreateNotify: + case XConstants.CreateNotify: XCreateWindowEvent cr = ev.get_xcreatewindow(); if (xembedLog.isLoggable(Level.FINEST)) { xembedLog.finest("Message on embedder: " + cr); @@ -205,7 +205,7 @@ public class XEmbedCanvasPeer extends XCanvasPeer implements WindowFocusListener } embedChild(cr.get_window()); break; - case DestroyNotify: + case XConstants.DestroyNotify: XDestroyWindowEvent dn = ev.get_xdestroywindow(); if (xembedLog.isLoggable(Level.FINEST)) { xembedLog.finest("Message on embedder: " + dn); @@ -215,7 +215,7 @@ public class XEmbedCanvasPeer extends XCanvasPeer implements WindowFocusListener } childDestroyed(); break; - case ReparentNotify: + case XConstants.ReparentNotify: XReparentEvent rep = ev.get_xreparent(); if (xembedLog.isLoggable(Level.FINEST)) { xembedLog.finest("Message on embedder: " + rep); @@ -309,7 +309,7 @@ public class XEmbedCanvasPeer extends XCanvasPeer implements WindowFocusListener if (status == 0 || (XToolkit.saved_error != null && - XToolkit.saved_error.get_error_code() != XlibWrapper.Success)) { + XToolkit.saved_error.get_error_code() != XConstants.Success)) { return null; } @@ -480,7 +480,7 @@ public class XEmbedCanvasPeer extends XCanvasPeer implements WindowFocusListener if (xembedLog.isLoggable(Level.FINE)) xembedLog.fine("Forwarding native key event: " + ke); XToolkit.awtLock(); try { - XlibWrapper.XSendEvent(XToolkit.getDisplay(), xembed.handle, false, XlibWrapper.NoEventMask, data); + XlibWrapper.XSendEvent(XToolkit.getDisplay(), xembed.handle, false, XConstants.NoEventMask, data); } finally { XToolkit.awtUnlock(); } @@ -742,7 +742,7 @@ public class XEmbedCanvasPeer extends XCanvasPeer implements WindowFocusListener version = Native.getCard32(xembed_info_data, 0); flags = Native.getCard32(xembed_info_data, 1); boolean new_mapped = (flags & XEMBED_MAPPED) != 0; - boolean currently_mapped = XlibUtil.getWindowMapState(handle) != XlibWrapper.IsUnmapped; + boolean currently_mapped = XlibUtil.getWindowMapState(handle) != XConstants.IsUnmapped; if (new_mapped != currently_mapped) { if (xembedLog.isLoggable(Level.FINER)) xembedLog.fine("Mapping state of the client has changed, old state: " + currently_mapped + ", new state: " + new_mapped); @@ -803,13 +803,13 @@ public class XEmbedCanvasPeer extends XCanvasPeer implements WindowFocusListener public void dispatchEvent(XEvent xev) { int type = xev.get_type(); switch (type) { - case PropertyNotify: + case XConstants.PropertyNotify: handlePropertyNotify(xev); break; - case ConfigureNotify: + case XConstants.ConfigureNotify: handleConfigureNotify(xev); break; - case ClientMessage: + case XConstants.ClientMessage: handleClientMessage(xev); break; } @@ -844,7 +844,7 @@ public class XEmbedCanvasPeer extends XCanvasPeer implements WindowFocusListener XKeyEvent ke = new XKeyEvent(data); // We recognize only these masks - modifiers = ke.get_state() & (ShiftMask | ControlMask | LockMask); + modifiers = ke.get_state() & (XConstants.ShiftMask | XConstants.ControlMask | XConstants.LockMask); if (xembedLog.isLoggable(Level.FINEST)) xembedLog.finest("Mapped " + e + " to " + this); } finally { XlibWrapper.unsafe.freeMemory(data); diff --git a/jdk/src/solaris/classes/sun/awt/X11/XEmbedChildProxyPeer.java b/jdk/src/solaris/classes/sun/awt/X11/XEmbedChildProxyPeer.java index 7e6ae054a87..b2a342757bd 100644 --- a/jdk/src/solaris/classes/sun/awt/X11/XEmbedChildProxyPeer.java +++ b/jdk/src/solaris/classes/sun/awt/X11/XEmbedChildProxyPeer.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2007 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2003-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -53,7 +53,7 @@ public class XEmbedChildProxyPeer implements ComponentPeer, XEventDispatcher{ try { XToolkit.addEventDispatcher(handle, this); XlibWrapper.XSelectInput(XToolkit.getDisplay(), handle, - XlibWrapper.StructureNotifyMask | XlibWrapper.PropertyChangeMask); + XConstants.StructureNotifyMask | XConstants.PropertyChangeMask); } finally { XToolkit.awtUnlock(); @@ -341,10 +341,10 @@ public class XEmbedChildProxyPeer implements ComponentPeer, XEventDispatcher{ public void dispatchEvent(XEvent xev) { int type = xev.get_type(); switch (type) { - case XlibWrapper.PropertyNotify: + case XConstants.PropertyNotify: handlePropertyNotify(xev); break; - case XlibWrapper.ConfigureNotify: + case XConstants.ConfigureNotify: handleConfigureNotify(xev); break; } diff --git a/jdk/src/solaris/classes/sun/awt/X11/XEmbedClientHelper.java b/jdk/src/solaris/classes/sun/awt/X11/XEmbedClientHelper.java index c56883e46af..139f375fa40 100644 --- a/jdk/src/solaris/classes/sun/awt/X11/XEmbedClientHelper.java +++ b/jdk/src/solaris/classes/sun/awt/X11/XEmbedClientHelper.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2007 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2003-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -145,10 +145,10 @@ public class XEmbedClientHelper extends XEmbedHelper implements XEventDispatcher public void dispatchEvent(XEvent xev) { switch(xev.get_type()) { - case XlibWrapper.ClientMessage: + case XConstants.ClientMessage: handleClientMessage(xev); break; - case XlibWrapper.ReparentNotify: + case XConstants.ReparentNotify: handleReparentNotify(xev); break; } diff --git a/jdk/src/solaris/classes/sun/awt/X11/XEmbedHelper.java b/jdk/src/solaris/classes/sun/awt/X11/XEmbedHelper.java index aab78552007..4b3c7d9fd88 100644 --- a/jdk/src/solaris/classes/sun/awt/X11/XEmbedHelper.java +++ b/jdk/src/solaris/classes/sun/awt/X11/XEmbedHelper.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2005 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2003-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -94,7 +94,7 @@ public class XEmbedHelper { } void sendMessage(long window, int message, long detail, long data1, long data2) { XClientMessageEvent msg = new XClientMessageEvent(); - msg.set_type((int)XlibWrapper.ClientMessage); + msg.set_type((int)XConstants.ClientMessage); msg.set_window(window); msg.set_message_type(XEmbed.getAtom()); msg.set_format(32); @@ -106,7 +106,7 @@ public class XEmbedHelper { XToolkit.awtLock(); try { if (xembedLog.isLoggable(Level.FINE)) xembedLog.fine("Sending " + XEmbedMessageToString(msg)); - XlibWrapper.XSendEvent(XToolkit.getDisplay(), window, false, XlibWrapper.NoEventMask, msg.pData); + XlibWrapper.XSendEvent(XToolkit.getDisplay(), window, false, XConstants.NoEventMask, msg.pData); } finally { XToolkit.awtUnlock(); diff --git a/jdk/src/solaris/classes/sun/awt/X11/XEmbedServerTester.java b/jdk/src/solaris/classes/sun/awt/X11/XEmbedServerTester.java index 28fd3c2246a..932f8bd31d6 100644 --- a/jdk/src/solaris/classes/sun/awt/X11/XEmbedServerTester.java +++ b/jdk/src/solaris/classes/sun/awt/X11/XEmbedServerTester.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2007 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2003-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -260,7 +260,7 @@ public class XEmbedServerTester implements XEventDispatcher { mapped = 0; embedCompletely(); sleep(1000); - if (XlibUtil.getWindowMapState(window.getWindow()) != XlibWrapper.IsUnmapped) { + if (XlibUtil.getWindowMapState(window.getWindow()) != IsUnmapped) { throw new RuntimeException("Client has been mapped"); } } @@ -613,12 +613,12 @@ public class XEmbedServerTester implements XEventDispatcher { } } private void checkMapped() { - if (XlibUtil.getWindowMapState(window.getWindow()) == XlibWrapper.IsUnmapped) { + if (XlibUtil.getWindowMapState(window.getWindow()) == IsUnmapped) { throw new RuntimeException("Client is not mapped"); } } private void checkNotMapped() { - if (XlibUtil.getWindowMapState(window.getWindow()) != XlibWrapper.IsUnmapped) { + if (XlibUtil.getWindowMapState(window.getWindow()) != IsUnmapped) { throw new RuntimeException("Client is mapped"); } } diff --git a/jdk/src/solaris/classes/sun/awt/X11/XEmbeddedFramePeer.java b/jdk/src/solaris/classes/sun/awt/X11/XEmbeddedFramePeer.java index b0cb3aa6d07..90eb7ff8ddc 100644 --- a/jdk/src/solaris/classes/sun/awt/X11/XEmbeddedFramePeer.java +++ b/jdk/src/solaris/classes/sun/awt/X11/XEmbeddedFramePeer.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2007 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2002-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -114,8 +114,8 @@ public class XEmbeddedFramePeer extends XFramePeer { protected boolean isEventDisabled(XEvent e) { if (embedder != null && embedder.isActive()) { switch (e.get_type()) { - case FocusIn: - case FocusOut: + case XConstants.FocusIn: + case XConstants.FocusOut: return true; } } diff --git a/jdk/src/solaris/classes/sun/awt/X11/XEmbeddingContainer.java b/jdk/src/solaris/classes/sun/awt/X11/XEmbeddingContainer.java index e5d5bed6bac..763729800c3 100644 --- a/jdk/src/solaris/classes/sun/awt/X11/XEmbeddingContainer.java +++ b/jdk/src/solaris/classes/sun/awt/X11/XEmbeddingContainer.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2007 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2003-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -121,7 +121,7 @@ public class XEmbeddingContainer extends XEmbedHelper implements XEventDispatche } public void dispatchEvent(XEvent xev) { switch(xev.get_type()) { - case XlibWrapper.ClientMessage: + case XConstants.ClientMessage: handleClientMessage(xev); break; } @@ -149,7 +149,7 @@ public class XEmbeddingContainer extends XEmbedHelper implements XEventDispatche ke.set_window(child); XToolkit.awtLock(); try { - XlibWrapper.XSendEvent(XToolkit.getDisplay(), child, false, XlibWrapper.NoEventMask, data); + XlibWrapper.XSendEvent(XToolkit.getDisplay(), child, false, XConstants.NoEventMask, data); } finally { XToolkit.awtUnlock(); diff --git a/jdk/src/solaris/classes/sun/awt/X11/XFocusProxyWindow.java b/jdk/src/solaris/classes/sun/awt/X11/XFocusProxyWindow.java index 045d10687d3..361ef87eeb6 100644 --- a/jdk/src/solaris/classes/sun/awt/X11/XFocusProxyWindow.java +++ b/jdk/src/solaris/classes/sun/awt/X11/XFocusProxyWindow.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2007 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2003-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -41,7 +41,7 @@ public class XFocusProxyWindow extends XBaseWindow { super(new XCreateWindowParams(new Object[] { BOUNDS, new Rectangle(-1, -1, 1, 1), PARENT_WINDOW, new Long(owner.getWindow()), - EVENT_MASK, new Long(FocusChangeMask | KeyPressMask | KeyReleaseMask) + EVENT_MASK, new Long(XConstants.FocusChangeMask | XConstants.KeyPressMask | XConstants.KeyReleaseMask) })); this.owner = owner; } @@ -67,8 +67,8 @@ public class XFocusProxyWindow extends XBaseWindow { int type = ev.get_type(); switch (type) { - case XlibWrapper.FocusIn: - case XlibWrapper.FocusOut: + case XConstants.FocusIn: + case XConstants.FocusOut: handleFocusEvent(ev); break; } diff --git a/jdk/src/solaris/classes/sun/awt/X11/XFramePeer.java b/jdk/src/solaris/classes/sun/awt/X11/XFramePeer.java index 28989acc609..9493b453feb 100644 --- a/jdk/src/solaris/classes/sun/awt/X11/XFramePeer.java +++ b/jdk/src/solaris/classes/sun/awt/X11/XFramePeer.java @@ -37,7 +37,7 @@ import java.awt.peer.FramePeer; import java.util.logging.Level; import java.util.logging.Logger; -class XFramePeer extends XDecoratedPeer implements FramePeer, XConstants { +class XFramePeer extends XDecoratedPeer implements FramePeer { private static Logger log = Logger.getLogger("sun.awt.X11.XFramePeer"); private static Logger stateLog = Logger.getLogger("sun.awt.X11.states"); private static Logger insLog = Logger.getLogger("sun.awt.X11.insets.XFramePeer"); @@ -71,7 +71,7 @@ class XFramePeer extends XDecoratedPeer implements FramePeer, XConstants { } else { winAttr.decorations = winAttr.AWT_DECOR_NONE; } - winAttr.functions = MWM_FUNC_ALL; + winAttr.functions = MWMConstants.MWM_FUNC_ALL; winAttr.isResizable = true; // target.isResizable(); winAttr.title = target.getTitle(); winAttr.initialResizability = target.isResizable(); @@ -109,9 +109,9 @@ class XFramePeer extends XDecoratedPeer implements FramePeer, XConstants { state = winAttr.initialState; } if ((state & Frame.ICONIFIED) != 0) { - setInitialState(IconicState); + setInitialState(XUtilConstants.IconicState); } else { - setInitialState(NormalState); + setInitialState(XUtilConstants.NormalState); } setExtendedState(state); } @@ -221,7 +221,7 @@ class XFramePeer extends XDecoratedPeer implements FramePeer, XConstants { XToolkit.awtLock(); try { XSizeHints hints = getHints(); - hints.set_flags(hints.get_flags() | (int)XlibWrapper.PMaxSize); + hints.set_flags(hints.get_flags() | (int)XUtilConstants.PMaxSize); if (b.width != Integer.MAX_VALUE) { hints.set_max_width(b.width); } else { @@ -344,7 +344,7 @@ class XFramePeer extends XDecoratedPeer implements FramePeer, XConstants { XToolkit.awtLock(); try { XWMHints hints = getWMHints(); - hints.set_flags((int)XlibWrapper.StateHint | hints.get_flags()); + hints.set_flags((int)XUtilConstants.StateHint | hints.get_flags()); hints.set_initial_state(wm_state); if (stateLog.isLoggable(Level.FINE)) stateLog.fine("Setting initial WM state on " + this + " to " + wm_state); XlibWrapper.XSetWMHints(XToolkit.getDisplay(), getWindow(), hints.pData); diff --git a/jdk/src/solaris/classes/sun/awt/X11/XGlobalCursorManager.java b/jdk/src/solaris/classes/sun/awt/X11/XGlobalCursorManager.java index eae5bbc2f5f..43ae1f89004 100644 --- a/jdk/src/solaris/classes/sun/awt/X11/XGlobalCursorManager.java +++ b/jdk/src/solaris/classes/sun/awt/X11/XGlobalCursorManager.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2007 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2003-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -229,46 +229,46 @@ public final class XGlobalCursorManager extends GlobalCursorManager { int cursorType = 0; switch (type) { case Cursor.DEFAULT_CURSOR: - cursorType = XlibWrapper.XC_left_ptr; + cursorType = XCursorFontConstants.XC_left_ptr; break; case Cursor.CROSSHAIR_CURSOR: - cursorType = XlibWrapper.XC_crosshair; + cursorType = XCursorFontConstants.XC_crosshair; break; case Cursor.TEXT_CURSOR: - cursorType = XlibWrapper.XC_xterm; + cursorType = XCursorFontConstants.XC_xterm; break; case Cursor.WAIT_CURSOR: - cursorType = XlibWrapper.XC_watch; + cursorType = XCursorFontConstants.XC_watch; break; case Cursor.SW_RESIZE_CURSOR: - cursorType = XlibWrapper.XC_bottom_left_corner; + cursorType = XCursorFontConstants.XC_bottom_left_corner; break; case Cursor.NW_RESIZE_CURSOR: - cursorType = XlibWrapper.XC_top_left_corner; + cursorType = XCursorFontConstants.XC_top_left_corner; break; case Cursor.SE_RESIZE_CURSOR: - cursorType = XlibWrapper.XC_bottom_right_corner; + cursorType = XCursorFontConstants.XC_bottom_right_corner; break; case Cursor.NE_RESIZE_CURSOR: - cursorType = XlibWrapper.XC_top_right_corner; + cursorType = XCursorFontConstants.XC_top_right_corner; break; case Cursor.S_RESIZE_CURSOR: - cursorType = XlibWrapper.XC_bottom_side; + cursorType = XCursorFontConstants.XC_bottom_side; break; case Cursor.N_RESIZE_CURSOR: - cursorType = XlibWrapper.XC_top_side; + cursorType = XCursorFontConstants.XC_top_side; break; case Cursor.W_RESIZE_CURSOR: - cursorType = XlibWrapper.XC_left_side; + cursorType = XCursorFontConstants.XC_left_side; break; case Cursor.E_RESIZE_CURSOR: - cursorType = XlibWrapper.XC_right_side; + cursorType = XCursorFontConstants.XC_right_side; break; case Cursor.HAND_CURSOR: - cursorType = XlibWrapper.XC_hand2; + cursorType = XCursorFontConstants.XC_hand2; break; case Cursor.MOVE_CURSOR: - cursorType = XlibWrapper.XC_fleur; + cursorType = XCursorFontConstants.XC_fleur; break; } diff --git a/jdk/src/solaris/classes/sun/awt/X11/XIconWindow.java b/jdk/src/solaris/classes/sun/awt/X11/XIconWindow.java index eab55f6b5fc..a6211a0e0b6 100644 --- a/jdk/src/solaris/classes/sun/awt/X11/XIconWindow.java +++ b/jdk/src/solaris/classes/sun/awt/X11/XIconWindow.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2006 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2003-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -293,7 +293,7 @@ public class XIconWindow extends XBaseWindow { long dst = XlibWrapper.XCreateImage(XToolkit.getDisplay(), visInfo.get_visual(), (int)awtImage.get_Depth(), - (int)XlibWrapper.ZPixmap, + (int)XConstants.ZPixmap, 0, bytes, iconWidth, @@ -470,9 +470,9 @@ public class XIconWindow extends XBaseWindow { params.add(BACKGROUND_PIXMAP, iconPixmap); params.add(COLORMAP, adata.get_awt_cmap()); params.add(DEPTH, awtImage.get_Depth()); - params.add(VISUAL_CLASS, (int)XlibWrapper.InputOutput); + params.add(VISUAL_CLASS, (int)XConstants.InputOutput); params.add(VISUAL, visInfo.get_visual()); - params.add(VALUE_MASK, XlibWrapper.CWBorderPixel | XlibWrapper.CWColormap | XlibWrapper.CWBackPixmap); + params.add(VALUE_MASK, XConstants.CWBorderPixel | XConstants.CWColormap | XConstants.CWBackPixmap); params.add(PARENT_WINDOW, XlibWrapper.RootWindow(XToolkit.getDisplay(), visInfo.get_screen())); params.add(BOUNDS, new Rectangle(0, 0, iconWidth, iconHeight)); params.remove(DELAYED); @@ -488,9 +488,9 @@ public class XIconWindow extends XBaseWindow { XlibWrapper.XClearWindow(XToolkit.getDisplay(), getWindow()); } // Provide both pixmap and window, WM or Taskbar will use the one they find more appropriate - long newFlags = hints.get_flags() | XlibWrapper.IconPixmapHint | XlibWrapper.IconMaskHint; + long newFlags = hints.get_flags() | XUtilConstants.IconPixmapHint | XUtilConstants.IconMaskHint; if (getWindow() != 0) { - newFlags |= XlibWrapper.IconWindowHint; + newFlags |= XUtilConstants.IconWindowHint; } hints.set_flags(newFlags); hints.set_icon_pixmap(iconPixmap); diff --git a/jdk/src/solaris/classes/sun/awt/X11/XMSelection.java b/jdk/src/solaris/classes/sun/awt/X11/XMSelection.java index 9d7059a8d05..8fb4f4bf3c0 100644 --- a/jdk/src/solaris/classes/sun/awt/X11/XMSelection.java +++ b/jdk/src/solaris/classes/sun/awt/X11/XMSelection.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2007 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2003-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -98,7 +98,7 @@ public class XMSelection { XToolkit.awtLock(); try { long root = XlibWrapper.RootWindow(display,screen); - XlibWrapper.XSelectInput(display, root, XlibWrapper.StructureNotifyMask); + XlibWrapper.XSelectInput(display, root, XConstants.StructureNotifyMask); XToolkit.addEventDispatcher(root, new XEventDispatcher() { public void dispatchEvent(XEvent ev) { @@ -130,7 +130,7 @@ public class XMSelection { synchronized(this) { setOwner(owner, screen); if (log.isLoggable(Level.FINE)) log.fine("New Selection Owner for screen " + screen + " = " + owner ); - XlibWrapper.XSelectInput(display, owner, XlibWrapper.StructureNotifyMask | eventMask); + XlibWrapper.XSelectInput(display, owner, XConstants.StructureNotifyMask | eventMask); XToolkit.addEventDispatcher(owner, new XEventDispatcher() { public void dispatchEvent(XEvent ev) { @@ -162,7 +162,7 @@ public class XMSelection { if (owner != 0) { setOwner(owner, screen); if (log.isLoggable(Level.FINE)) log.fine("Selection Owner for screen " + screen + " = " + owner ); - XlibWrapper.XSelectInput(display, owner, XlibWrapper.StructureNotifyMask | extra_mask); + XlibWrapper.XSelectInput(display, owner, XConstants.StructureNotifyMask | extra_mask); XToolkit.addEventDispatcher(owner, new XEventDispatcher() { public void dispatchEvent(XEvent ev) { @@ -205,7 +205,7 @@ public class XMSelection { static boolean processRootEvent(XEvent xev, int screen) { switch (xev.get_type()) { - case XlibWrapper.ClientMessage: { + case XConstants.ClientMessage: { return processClientMessage(xev, screen); } } @@ -225,7 +225,7 @@ public class XMSelection { */ public XMSelection (String selname) { - this(selname, XlibWrapper.PropertyChangeMask); + this(selname, XConstants.PropertyChangeMask); } @@ -319,11 +319,11 @@ public class XMSelection { void dispatchSelectionEvent(XEvent xev, int screen) { if (log.isLoggable(Level.FINE)) log.fine("Event =" + xev); - if (xev.get_type() == XlibWrapper.DestroyNotify) { + if (xev.get_type() == XConstants.DestroyNotify) { XDestroyWindowEvent de = xev.get_xdestroywindow(); dispatchOwnerDeath( de, screen); } - else if (xev.get_type() == XlibWrapper.PropertyNotify) { + else if (xev.get_type() == XConstants.PropertyNotify) { XPropertyEvent xpe = xev.get_xproperty(); dispatchSelectionChanged( xpe, screen); } diff --git a/jdk/src/solaris/classes/sun/awt/X11/XNETProtocol.java b/jdk/src/solaris/classes/sun/awt/X11/XNETProtocol.java index f61c476e57e..ccc1b124204 100644 --- a/jdk/src/solaris/classes/sun/awt/X11/XNETProtocol.java +++ b/jdk/src/solaris/classes/sun/awt/X11/XNETProtocol.java @@ -99,7 +99,7 @@ final class XNETProtocol extends XProtocol implements XStateProtocol, XLayerProt return; } if (log.isLoggable(Level.FINE)) log.fine("Requesting state on " + window + " for " + state); - req.set_type((int)XlibWrapper.ClientMessage); + req.set_type((int)XConstants.ClientMessage); req.set_window(window.getWindow()); req.set_message_type(XA_NET_WM_STATE.getAtom()); req.set_format(32); @@ -109,7 +109,7 @@ final class XNETProtocol extends XProtocol implements XStateProtocol, XLayerProt XlibWrapper.XSendEvent(XToolkit.getDisplay(), XlibWrapper.RootWindow(XToolkit.getDisplay(), window.getScreenNumber()), false, - XlibWrapper.SubstructureRedirectMask | XlibWrapper.SubstructureNotifyMask, + XConstants.SubstructureRedirectMask | XConstants.SubstructureNotifyMask, req.pData); } finally { @@ -183,7 +183,7 @@ final class XNETProtocol extends XProtocol implements XStateProtocol, XLayerProt if (window.isShowing()) { XClientMessageEvent req = new XClientMessageEvent(); try { - req.set_type((int)XlibWrapper.ClientMessage); + req.set_type((int)XConstants.ClientMessage); req.set_window(window.getWindow()); req.set_message_type(XA_NET_WM_STATE.getAtom()); req.set_format(32); @@ -195,7 +195,7 @@ final class XNETProtocol extends XProtocol implements XStateProtocol, XLayerProt XlibWrapper.XSendEvent(XToolkit.getDisplay(), XlibWrapper.RootWindow(XToolkit.getDisplay(), window.getScreenNumber()), false, - XlibWrapper.SubstructureRedirectMask | XlibWrapper.SubstructureNotifyMask, + XConstants.SubstructureRedirectMask | XConstants.SubstructureNotifyMask, req.pData); } finally { diff --git a/jdk/src/solaris/classes/sun/awt/X11/XProtocol.java b/jdk/src/solaris/classes/sun/awt/X11/XProtocol.java index 34c900ed4d0..1fb3de9fa31 100644 --- a/jdk/src/solaris/classes/sun/awt/X11/XProtocol.java +++ b/jdk/src/solaris/classes/sun/awt/X11/XProtocol.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2005 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2003-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -42,7 +42,7 @@ class XProtocol { static XToolkit.XErrorHandler VerifyChangePropertyHandler = new XToolkit.XErrorHandler() { public int handleError(long display, XErrorEvent err) { XToolkit.XERROR_SAVE(err); - if (err.get_request_code() == XlibWrapper.X_ChangeProperty) { + if (err.get_request_code() == XProtocolConstants.X_ChangeProperty) { return 0; } else { return XToolkit.SAVED_ERROR_HANDLER(display, err); diff --git a/jdk/src/solaris/classes/sun/awt/X11/XProtocolConstants.java b/jdk/src/solaris/classes/sun/awt/X11/XProtocolConstants.java index 475a348fc69..70aae76064c 100644 --- a/jdk/src/solaris/classes/sun/awt/X11/XProtocolConstants.java +++ b/jdk/src/solaris/classes/sun/awt/X11/XProtocolConstants.java @@ -1,5 +1,5 @@ /* - * Copyright 2003 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2003-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,7 +25,10 @@ package sun.awt.X11; -public interface XProtocolConstants { +final public class XProtocolConstants { + + private XProtocolConstants(){} + /* Reply codes */ public static final int X_Reply = 1 ; /* Normal reply */ public static final int X_Error = 0 ; /* Error */ diff --git a/jdk/src/solaris/classes/sun/awt/X11/XSelection.java b/jdk/src/solaris/classes/sun/awt/X11/XSelection.java index b472bec7646..0e7a8aafdc0 100644 --- a/jdk/src/solaris/classes/sun/awt/X11/XSelection.java +++ b/jdk/src/solaris/classes/sun/awt/X11/XSelection.java @@ -141,7 +141,7 @@ public final class XSelection { long selection = selectionAtom.getAtom(); // ICCCM prescribes that CurrentTime should not be used for SetSelectionOwner. - if (time == XlibWrapper.CurrentTime) { + if (time == XConstants.CurrentTime) { time = XToolkit.getCurrentServerTime(); } @@ -199,7 +199,7 @@ public final class XSelection { WindowPropertyGetter targetsGetter = new WindowPropertyGetter(XWindow.getXAWTRootWindow().getWindow(), selectionPropertyAtom, 0, MAX_LENGTH, - true, XlibWrapper.AnyPropertyType); + true, XConstants.AnyPropertyType); try { XToolkit.awtLock(); @@ -274,7 +274,7 @@ public final class XSelection { new WindowPropertyGetter(XWindow.getXAWTRootWindow().getWindow(), selectionPropertyAtom, 0, MAX_LENGTH, false, // don't delete to handle INCR properly. - XlibWrapper.AnyPropertyType); + XConstants.AnyPropertyType); try { XToolkit.awtLock(); @@ -353,7 +353,7 @@ public final class XSelection { new WindowPropertyGetter(XWindow.getXAWTRootWindow().getWindow(), selectionPropertyAtom, 0, MAX_LENGTH, false, - XlibWrapper.AnyPropertyType); + XConstants.AnyPropertyType); try { XToolkit.awtLock(); @@ -520,7 +520,7 @@ public final class XSelection { try { XlibWrapper.XChangeProperty(XToolkit.getDisplay(), requestor, property, format, dataFormat, - XlibWrapper.PropModeReplace, + XConstants.PropModeReplace, nativeDataPtr, count); } finally { XToolkit.awtUnlock(); @@ -543,14 +543,14 @@ public final class XSelection { boolean conversionSucceeded = false; if (ownershipTime != 0 && - (requestTime == XlibWrapper.CurrentTime || requestTime >= ownershipTime)) + (requestTime == XConstants.CurrentTime || requestTime >= ownershipTime)) { // Handle MULTIPLE requests as per ICCCM. if (format == XDataTransferer.MULTIPLE_ATOM.getAtom()) { conversionSucceeded = handleMultipleRequest(requestor, property); } else { // Support for obsolete clients as per ICCCM. - if (property == XlibWrapper.None) { + if (property == XConstants.None) { property = format; } @@ -564,12 +564,12 @@ public final class XSelection { if (!conversionSucceeded) { // None property indicates conversion failure. - property = XlibWrapper.None; + property = XConstants.None; } XSelectionEvent xse = new XSelectionEvent(); try { - xse.set_type(XlibWrapper.SelectionNotify); + xse.set_type(XConstants.SelectionNotify); xse.set_send_event(true); xse.set_requestor(requestor); xse.set_selection(selectionAtom.getAtom()); @@ -580,7 +580,7 @@ public final class XSelection { XToolkit.awtLock(); try { XlibWrapper.XSendEvent(XToolkit.getDisplay(), requestor, false, - XlibWrapper.NoEventMask, xse.pData); + XConstants.NoEventMask, xse.pData); } finally { XToolkit.awtUnlock(); } @@ -590,7 +590,7 @@ public final class XSelection { } private boolean handleMultipleRequest(final long requestor, long property) { - if (XlibWrapper.None == property) { + if (XConstants.None == property) { // The property cannot be None for a MULTIPLE request. return false; } @@ -601,7 +601,7 @@ public final class XSelection { WindowPropertyGetter wpg = new WindowPropertyGetter(requestor, XAtom.get(property), 0, MAX_LENGTH, false, - XlibWrapper.AnyPropertyType); + XConstants.AnyPropertyType); try { wpg.execute(); @@ -629,7 +629,7 @@ public final class XSelection { property, wpg.getActualType(), wpg.getActualFormat(), - XlibWrapper.PropModeReplace, + XConstants.PropModeReplace, wpg.getData(), wpg.getNumberOfItems()); } finally { @@ -673,7 +673,7 @@ public final class XSelection { try { XlibWrapper.XChangeProperty(XToolkit.getDisplay(), requestor, property, XAtom.XA_ATOM, dataFormat, - XlibWrapper.PropModeReplace, + XConstants.PropModeReplace, nativeDataPtr, count); } finally { XToolkit.awtUnlock(); @@ -712,7 +712,7 @@ public final class XSelection { private static class SelectionEventHandler implements XEventDispatcher { public void dispatchEvent(XEvent ev) { switch (ev.get_type()) { - case XlibWrapper.SelectionNotify: { + case XConstants.SelectionNotify: { XToolkit.awtLock(); try { XSelectionEvent xse = ev.get_xselection(); @@ -733,7 +733,7 @@ public final class XSelection { } break; } - case XlibWrapper.SelectionRequest: { + case XConstants.SelectionRequest: { XSelectionRequestEvent xsre = ev.get_xselectionrequest(); long atom = xsre.get_selection(); XSelection selection = XSelection.getSelection(XAtom.get(atom)); @@ -743,7 +743,7 @@ public final class XSelection { } break; } - case XlibWrapper.SelectionClear: { + case XConstants.SelectionClear: { XSelectionClearEvent xsce = ev.get_xselectionclear(); long atom = xsce.get_selection(); XSelection selection = XSelection.getSelection(XAtom.get(atom)); @@ -793,7 +793,7 @@ public final class XSelection { wattr.pData); XlibWrapper.XSelectInput(XToolkit.getDisplay(), requestor, wattr.get_your_event_mask() | - XlibWrapper.PropertyChangeMask); + XConstants.PropertyChangeMask); } finally { XToolkit.awtUnlock(); } @@ -805,10 +805,10 @@ public final class XSelection { public void dispatchEvent(XEvent ev) { switch (ev.get_type()) { - case XlibWrapper.PropertyNotify: + case XConstants.PropertyNotify: XPropertyEvent xpe = ev.get_xproperty(); if (xpe.get_window() == requestor && - xpe.get_state() == XlibWrapper.PropertyDelete && + xpe.get_state() == XConstants.PropertyDelete && xpe.get_atom() == property) { int count = data.length - offset; @@ -834,7 +834,7 @@ public final class XSelection { XlibWrapper.XChangeProperty(XToolkit.getDisplay(), requestor, property, target, format, - XlibWrapper.PropModeReplace, + XConstants.PropModeReplace, nativeDataPtr, count); } finally { XToolkit.awtUnlock(); @@ -853,9 +853,9 @@ public final class XSelection { private static class IncrementalTransferHandler implements XEventDispatcher { public void dispatchEvent(XEvent ev) { switch (ev.get_type()) { - case XlibWrapper.PropertyNotify: + case XConstants.PropertyNotify: XPropertyEvent xpe = ev.get_xproperty(); - if (xpe.get_state() == XlibWrapper.PropertyNewValue && + if (xpe.get_state() == XConstants.PropertyNewValue && xpe.get_atom() == selectionPropertyAtom.getAtom()) { XToolkit.awtLock(); try { diff --git a/jdk/src/solaris/classes/sun/awt/X11/XSystemTrayPeer.java b/jdk/src/solaris/classes/sun/awt/X11/XSystemTrayPeer.java index fa09a6f862c..83ba45ccbe8 100644 --- a/jdk/src/solaris/classes/sun/awt/X11/XSystemTrayPeer.java +++ b/jdk/src/solaris/classes/sun/awt/X11/XSystemTrayPeer.java @@ -1,5 +1,5 @@ /* - * Copyright 2005-2007 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2005-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -131,7 +131,7 @@ public class XSystemTrayPeer implements SystemTrayPeer, XMSelectionListener { XClientMessageEvent xev = new XClientMessageEvent(); try { - xev.set_type(XlibWrapper.ClientMessage); + xev.set_type(XConstants.ClientMessage); xev.set_window(win); xev.set_format(32); xev.set_message_type(_NET_SYSTEM_TRAY_OPCODE.getAtom()); @@ -144,7 +144,7 @@ public class XSystemTrayPeer implements SystemTrayPeer, XMSelectionListener { XToolkit.awtLock(); try { XlibWrapper.XSendEvent(XToolkit.getDisplay(), win, false, - XlibWrapper.NoEventMask, xev.pData); + XConstants.NoEventMask, xev.pData); } finally { XToolkit.awtUnlock(); } diff --git a/jdk/src/solaris/classes/sun/awt/X11/XToolkit.java b/jdk/src/solaris/classes/sun/awt/X11/XToolkit.java index 069568519d8..871f99368b6 100644 --- a/jdk/src/solaris/classes/sun/awt/X11/XToolkit.java +++ b/jdk/src/solaris/classes/sun/awt/X11/XToolkit.java @@ -54,8 +54,7 @@ import sun.font.FontManager; import sun.misc.PerformanceLogger; import sun.print.PrintJob2D; -public final class XToolkit extends UNIXToolkit implements Runnable, XConstants -{ +public final class XToolkit extends UNIXToolkit implements Runnable { private static Logger log = Logger.getLogger("sun.awt.X11.XToolkit"); private static Logger eventLog = Logger.getLogger("sun.awt.X11.event.XToolkit"); private static final Logger timeoutTaskLog = Logger.getLogger("sun.awt.X11.timeoutTask.XToolkit"); @@ -169,7 +168,7 @@ public final class XToolkit extends UNIXToolkit implements Runnable, XConstants static XErrorHandler IgnoreBadWindowHandler = new XErrorHandler() { public int handleError(long display, XErrorEvent err) { XERROR_SAVE(err); - if (err.get_error_code() == BadWindow) { + if (err.get_error_code() == XConstants.BadWindow) { return 0; } else { return SAVED_ERROR_HANDLER(display, err); @@ -425,7 +424,7 @@ public final class XToolkit extends UNIXToolkit implements Runnable, XConstants // Only our windows guaranteely generate MotionNotify, so we // should track enter/leave, to catch the moment when to // switch to XQueryPointer - if (e.get_type() == MotionNotify) { + if (e.get_type() == XConstants.MotionNotify) { XMotionEvent ev = e.get_xmotion(); awtLock(); try { @@ -437,7 +436,7 @@ public final class XToolkit extends UNIXToolkit implements Runnable, XConstants } finally { awtUnlock(); } - } else if (e.get_type() == LeaveNotify) { + } else if (e.get_type() == XConstants.LeaveNotify) { // Leave from our window awtLock(); try { @@ -445,7 +444,7 @@ public final class XToolkit extends UNIXToolkit implements Runnable, XConstants } finally { awtUnlock(); } - } else if (e.get_type() == EnterNotify) { + } else if (e.get_type() == XConstants.EnterNotify) { // Entrance into our window XCrossingEvent ev = e.get_xcrossing(); awtLock(); @@ -492,7 +491,7 @@ public final class XToolkit extends UNIXToolkit implements Runnable, XConstants final XAnyEvent xany = ev.get_xany(); if (windowToXWindow(xany.get_window()) != null && - (ev.get_type() == MotionNotify || ev.get_type() == EnterNotify || ev.get_type() == LeaveNotify)) + (ev.get_type() == XConstants.MotionNotify || ev.get_type() == XConstants.EnterNotify || ev.get_type() == XConstants.LeaveNotify)) { processGlobalMotionEvent(ev); } @@ -549,15 +548,15 @@ public final class XToolkit extends UNIXToolkit implements Runnable, XConstants // If no events are queued, waitForEvents() causes calls to // awtUnlock(), awtJNI_ThreadYield, poll, awtLock(), // so it spends most of its time in poll, without holding the lock. - while ((XlibWrapper.XEventsQueued(getDisplay(), XlibWrapper.QueuedAfterReading) == 0) && - (XlibWrapper.XEventsQueued(getDisplay(), XlibWrapper.QueuedAfterFlush) == 0)) { + while ((XlibWrapper.XEventsQueued(getDisplay(), XConstants.QueuedAfterReading) == 0) && + (XlibWrapper.XEventsQueued(getDisplay(), XConstants.QueuedAfterFlush) == 0)) { callTimeoutTasks(); waitForEvents(getNextTaskTime()); } XlibWrapper.XNextEvent(getDisplay(),ev.pData); } - if (ev.get_type() != NoExpose) { + if (ev.get_type() != XConstants.NoExpose) { eventNumber++; } @@ -582,13 +581,13 @@ public final class XToolkit extends UNIXToolkit implements Runnable, XConstants } } } - if( keyEventLog.isLoggable(Level.FINE) && (ev.get_type() == KeyPress || ev.get_type() == KeyRelease) ) { + if( keyEventLog.isLoggable(Level.FINE) && (ev.get_type() == XConstants.KeyPress || ev.get_type() == XConstants.KeyRelease) ) { keyEventLog.fine("before XFilterEvent:"+ev); } if (XlibWrapper.XFilterEvent(ev.getPData(), w)) { continue; } - if( keyEventLog.isLoggable(Level.FINE) && (ev.get_type() == KeyPress || ev.get_type() == KeyRelease) ) { + if( keyEventLog.isLoggable(Level.FINE) && (ev.get_type() == XConstants.KeyPress || ev.get_type() == XConstants.KeyRelease) ) { keyEventLog.fine("after XFilterEvent:"+ev); // IS THIS CORRECT? } @@ -750,7 +749,7 @@ public final class XToolkit extends UNIXToolkit implements Runnable, XConstants * _NET_WM_STRUT[_PARTIAL] hints for iconified windows * are not included to the screen insets. */ - if (XlibUtil.getWindowMapState(window) == XlibWrapper.IsUnmapped) + if (XlibUtil.getWindowMapState(window) == XConstants.IsUnmapped) { continue; } @@ -1289,7 +1288,7 @@ public final class XToolkit extends UNIXToolkit implements Runnable, XConstants new XEventDispatcher() { public void dispatchEvent(XEvent ev) { switch (ev.get_type()) { - case PropertyNotify: + case XConstants.PropertyNotify: XPropertyEvent xpe = ev.get_xproperty(); awtLock(); @@ -1322,7 +1321,7 @@ public final class XToolkit extends UNIXToolkit implements Runnable, XConstants XlibWrapper.XChangeProperty(XToolkit.getDisplay(), XBaseWindow.getXAWTRootWindow().getWindow(), _XA_JAVA_TIME_PROPERTY_ATOM.getAtom(), XAtom.XA_ATOM, 32, - PropModeAppend, + XConstants.PropModeAppend, 0, 0); XlibWrapper.XFlush(XToolkit.getDisplay()); @@ -1539,8 +1538,8 @@ public final class XToolkit extends UNIXToolkit implements Runnable, XConstants final int shiftLock = keysymToPrimaryKeycode(XKeySymConstants.XK_Shift_Lock); final int capsLock = keysymToPrimaryKeycode(XKeySymConstants.XK_Caps_Lock); - final int modmask[] = { ShiftMask, LockMask, ControlMask, Mod1Mask, - Mod2Mask, Mod3Mask, Mod4Mask, Mod5Mask }; + final int modmask[] = { XConstants.ShiftMask, XConstants.LockMask, XConstants.ControlMask, XConstants.Mod1Mask, + XConstants.Mod2Mask, XConstants.Mod3Mask, XConstants.Mod4Mask, XConstants.Mod5Mask }; log.fine("In setupModifierMap"); awtLock(); @@ -2047,7 +2046,7 @@ public final class XToolkit extends UNIXToolkit implements Runnable, XConstants if (oops_waiter == null) { oops_waiter = new XEventDispatcher() { public void dispatchEvent(XEvent e) { - if (e.get_type() == SelectionNotify) { + if (e.get_type() == XConstants.SelectionNotify) { XSelectionEvent pe = e.get_xselection(); if (pe.get_property() == oops.getAtom()) { oops_updated = true; @@ -2083,7 +2082,7 @@ public final class XToolkit extends UNIXToolkit implements Runnable, XConstants eventLog.log(Level.FINER, "WM_S0 selection owner {0}", new Object[] {XlibWrapper.XGetSelectionOwner(getDisplay(), atom.getAtom())}); XlibWrapper.XConvertSelection(getDisplay(), atom.getAtom(), XAtom.get("VERSION").getAtom(), oops.getAtom(), - win.getWindow(), XlibWrapper.CurrentTime); + win.getWindow(), XConstants.CurrentTime); XSync(); diff --git a/jdk/src/solaris/classes/sun/awt/X11/XTrayIconPeer.java b/jdk/src/solaris/classes/sun/awt/X11/XTrayIconPeer.java index e3bfacb4353..ff690bf9d06 100644 --- a/jdk/src/solaris/classes/sun/awt/X11/XTrayIconPeer.java +++ b/jdk/src/solaris/classes/sun/awt/X11/XTrayIconPeer.java @@ -98,7 +98,7 @@ public class XTrayIconPeer implements TrayIconPeer { parentXED = new XEventDispatcher() { // It's executed under AWTLock. public void dispatchEvent(XEvent ev) { - if (isDisposed() || ev.get_type() != XlibWrapper.ConfigureNotify) { + if (isDisposed() || ev.get_type() != XConstants.ConfigureNotify) { return; } @@ -194,7 +194,7 @@ public class XTrayIconPeer implements TrayIconPeer { XTrayIconPeer xtiPeer = XTrayIconPeer.this; public void dispatchEvent(XEvent ev) { - if (isDisposed() || ev.get_type() != XlibWrapper.ReparentNotify) { + if (isDisposed() || ev.get_type() != XConstants.ReparentNotify) { return; } @@ -214,7 +214,7 @@ public class XTrayIconPeer implements TrayIconPeer { } if (!isTrayIconDisplayed) { - addXED(eframeParentID, parentXED, XlibWrapper.StructureNotifyMask); + addXED(eframeParentID, parentXED, XConstants.StructureNotifyMask); isTrayIconDisplayed = true; XToolkit.awtLockNotifyAll(); @@ -222,7 +222,7 @@ public class XTrayIconPeer implements TrayIconPeer { } }; - addXED(getWindow(), eframeXED, XlibWrapper.StructureNotifyMask); + addXED(getWindow(), eframeXED, XConstants.StructureNotifyMask); XSystemTrayPeer.getPeerInstance().addTrayIcon(this); // throws AWTException diff --git a/jdk/src/solaris/classes/sun/awt/X11/XUtilConstants.java b/jdk/src/solaris/classes/sun/awt/X11/XUtilConstants.java index 9b15fc079ba..048ab113439 100644 --- a/jdk/src/solaris/classes/sun/awt/X11/XUtilConstants.java +++ b/jdk/src/solaris/classes/sun/awt/X11/XUtilConstants.java @@ -1,5 +1,5 @@ /* - * Copyright 2003 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2003-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,7 +25,10 @@ package sun.awt.X11; -public interface XUtilConstants { +final public class XUtilConstants { + + private XUtilConstants(){} + /* * Bitmask returned by XParseGeometry(). Each bit tells if the corresponding * value (x, y, width, height) was found in the parsed string. diff --git a/jdk/src/solaris/classes/sun/awt/X11/XWINProtocol.java b/jdk/src/solaris/classes/sun/awt/X11/XWINProtocol.java index 94465466950..83b676a1a60 100644 --- a/jdk/src/solaris/classes/sun/awt/X11/XWINProtocol.java +++ b/jdk/src/solaris/classes/sun/awt/X11/XWINProtocol.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2007 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2003-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -58,7 +58,7 @@ class XWINProtocol extends XProtocol implements XStateProtocol, XLayerProtocol { } XClientMessageEvent req = new XClientMessageEvent(); - req.set_type(XlibWrapper.ClientMessage); + req.set_type(XConstants.ClientMessage); req.set_window(window.getWindow()); req.set_message_type(XA_WIN_STATE.getAtom()); req.set_format(32); @@ -71,7 +71,7 @@ class XWINProtocol extends XProtocol implements XStateProtocol, XLayerProtocol { XlibWrapper.RootWindow(XToolkit.getDisplay(), window.getScreenNumber()), false, - XlibWrapper.SubstructureRedirectMask | XlibWrapper.SubstructureNotifyMask, + XConstants.SubstructureRedirectMask | XConstants.SubstructureNotifyMask, req.pData); } finally { @@ -150,7 +150,7 @@ class XWINProtocol extends XProtocol implements XStateProtocol, XLayerProtocol { public void setLayer(XWindowPeer window, int layer) { if (window.isShowing()) { XClientMessageEvent req = new XClientMessageEvent(); - req.set_type(XlibWrapper.ClientMessage); + req.set_type(XConstants.ClientMessage); req.set_window(window.getWindow()); req.set_message_type(XA_WIN_LAYER.getAtom()); req.set_format(32); @@ -164,7 +164,7 @@ class XWINProtocol extends XProtocol implements XStateProtocol, XLayerProtocol { XlibWrapper.RootWindow(XToolkit.getDisplay(), window.getScreenNumber()), false, - /*XlibWrapper.SubstructureRedirectMask | */XlibWrapper.SubstructureNotifyMask, + /*XConstants.SubstructureRedirectMask | */XConstants.SubstructureNotifyMask, req.pData); } finally { diff --git a/jdk/src/solaris/classes/sun/awt/X11/XWM.java b/jdk/src/solaris/classes/sun/awt/X11/XWM.java index d8e0d6b031d..c3adec9aa02 100644 --- a/jdk/src/solaris/classes/sun/awt/X11/XWM.java +++ b/jdk/src/solaris/classes/sun/awt/X11/XWM.java @@ -46,7 +46,7 @@ import java.util.regex.Pattern; * Class incapsulating knowledge about window managers in general * Descendants should provide some information about specific window manager. */ -final class XWM implements MWMConstants, XUtilConstants +final class XWM { private final static Logger log = Logger.getLogger("sun.awt.X11.XWM"); @@ -274,12 +274,12 @@ final class XWM implements MWMConstants, XUtilConstants } winmgr_running = false; - substruct.set_event_mask(XlibWrapper.SubstructureRedirectMask); + substruct.set_event_mask(XConstants.SubstructureRedirectMask); XToolkit.WITH_XERROR_HANDLER(DetectWMHandler); XlibWrapper.XChangeWindowAttributes(XToolkit.getDisplay(), XToolkit.getDefaultRootWindow(), - XlibWrapper.CWEventMask, + XConstants.CWEventMask, substruct.pData); XToolkit.RESTORE_XERROR_HANDLER(); @@ -291,7 +291,7 @@ final class XWM implements MWMConstants, XUtilConstants substruct.set_event_mask(0); XlibWrapper.XChangeWindowAttributes(XToolkit.getDisplay(), XToolkit.getDefaultRootWindow(), - XlibWrapper.CWEventMask, + XConstants.CWEventMask, substruct.pData); if (insLog.isLoggable(Level.FINE)) { insLog.finer("It looks like there is no WM thus NO_WM"); @@ -322,7 +322,7 @@ final class XWM implements MWMConstants, XUtilConstants XAtom.XA_STRING); try { int status = getter.execute(XToolkit.IgnoreBadWindowHandler); - if (status != XlibWrapper.Success || getter.getData() == 0) { + if (status != XConstants.Success || getter.getData() == 0) { return 0; } @@ -411,7 +411,7 @@ final class XWM implements MWMConstants, XUtilConstants false, XA_DT_SM_WINDOW_INFO); try { int status = getter.execute(); - if (status != XlibWrapper.Success || getter.getData() == 0) { + if (status != XConstants.Success || getter.getData() == 0) { log.finer("Getting of _DT_SM_WINDOW_INFO is not successfull"); return false; } @@ -442,7 +442,7 @@ final class XWM implements MWMConstants, XUtilConstants status = getter2.execute(XToolkit.IgnoreBadWindowHandler); - if (status != XlibWrapper.Success || getter2.getData() == 0) { + if (status != XConstants.Success || getter2.getData() == 0) { log.finer("Getting of _DT_SM_STATE_INFO is not successfull"); return false; } @@ -480,18 +480,18 @@ final class XWM implements MWMConstants, XUtilConstants WindowPropertyGetter getter = new WindowPropertyGetter(XToolkit.getDefaultRootWindow(), XA_MOTIF_WM_INFO, 0, - PROP_MOTIF_WM_INFO_ELEMENTS, + MWMConstants.PROP_MOTIF_WM_INFO_ELEMENTS, false, XA_MOTIF_WM_INFO); try { int status = getter.execute(); - if (status != XlibWrapper.Success || getter.getData() == 0) { + if (status != XConstants.Success || getter.getData() == 0) { return false; } if (getter.getActualType() != XA_MOTIF_WM_INFO.getAtom() || getter.getActualFormat() != 32 - || getter.getNumberOfItems() != PROP_MOTIF_WM_INFO_ELEMENTS + || getter.getNumberOfItems() != MWMConstants.PROP_MOTIF_WM_INFO_ELEMENTS || getter.getBytesAfter() != 0) { return false; @@ -516,7 +516,7 @@ final class XWM implements MWMConstants, XUtilConstants 0, 1, false, XA_WM_STATE); try { - if (state_getter.execute() == XlibWrapper.Success && + if (state_getter.execute() == XConstants.Success && state_getter.getData() != 0 && state_getter.getActualType() == XA_WM_STATE.getAtom()) { @@ -577,7 +577,7 @@ final class XWM implements MWMConstants, XUtilConstants static XToolkit.XErrorHandler VerifyChangePropertyHandler = new XToolkit.XErrorHandler() { public int handleError(long display, XErrorEvent err) { XToolkit.XERROR_SAVE(err); - if (err.get_request_code() == XlibWrapper.X_ChangeProperty) { + if (err.get_request_code() == XProtocolConstants.X_ChangeProperty) { return 0; } else { return XToolkit.SAVED_ERROR_HANDLER(display, err); @@ -621,11 +621,11 @@ final class XWM implements MWMConstants, XUtilConstants XlibWrapper.XChangePropertyS(XToolkit.getDisplay(), XToolkit.getDefaultRootWindow(), XA_ICEWM_WINOPTHINT.getAtom(), XA_ICEWM_WINOPTHINT.getAtom(), - 8, XlibWrapper.PropModeReplace, + 8, XConstants.PropModeReplace, new String(opt)); XToolkit.RESTORE_XERROR_HANDLER(); - if (XToolkit.saved_error != null && XToolkit.saved_error.get_error_code() != XlibWrapper.Success) { + if (XToolkit.saved_error != null && XToolkit.saved_error.get_error_code() != XConstants.Success) { log.finer("Erorr getting XA_ICEWM_WINOPTHINT property"); return false; } @@ -654,7 +654,7 @@ final class XWM implements MWMConstants, XUtilConstants true, XA_ICEWM_WINOPTHINT); try { int status = getter.execute(); - boolean res = (status == XlibWrapper.Success && getter.getActualType() != 0); + boolean res = (status == XConstants.Success && getter.getActualType() != 0); log.finer("Status getting XA_ICEWM_WINOPTHINT: " + !res); return !res || isNetWMName("IceWM"); } finally { @@ -686,8 +686,8 @@ final class XWM implements MWMConstants, XUtilConstants static XToolkit.XErrorHandler DetectWMHandler = new XToolkit.XErrorHandler() { public int handleError(long display, XErrorEvent err) { XToolkit.XERROR_SAVE(err); - if (err.get_request_code() == XlibWrapper.X_ChangeWindowAttributes - && err.get_error_code() == XlibWrapper.BadAccess) + if (err.get_request_code() == XProtocolConstants.X_ChangeWindowAttributes + && err.get_error_code() == XConstants.BadAccess) { winmgr_running = true; return 0; @@ -804,7 +804,7 @@ final class XWM implements MWMConstants, XUtilConstants * XXX: Why do we need this in the first place??? */ static void removeSizeHints(XDecoratedPeer window, long mask) { - mask &= PMaxSize | PMinSize; + mask &= XUtilConstants.PMaxSize | XUtilConstants.PMinSize; XToolkit.awtLock(); try { @@ -830,13 +830,13 @@ final class XWM implements MWMConstants, XUtilConstants * rest of the code. */ static int normalizeMotifDecor(int decorations) { - if ((decorations & MWM_DECOR_ALL) == 0) { + if ((decorations & MWMConstants.MWM_DECOR_ALL) == 0) { return decorations; } - int d = MWM_DECOR_BORDER | MWM_DECOR_RESIZEH - | MWM_DECOR_TITLE - | MWM_DECOR_MENU | MWM_DECOR_MINIMIZE - | MWM_DECOR_MAXIMIZE; + int d = MWMConstants.MWM_DECOR_BORDER | MWMConstants.MWM_DECOR_RESIZEH + | MWMConstants.MWM_DECOR_TITLE + | MWMConstants.MWM_DECOR_MENU | MWMConstants.MWM_DECOR_MINIMIZE + | MWMConstants.MWM_DECOR_MAXIMIZE; d &= ~decorations; return d; } @@ -848,14 +848,14 @@ final class XWM implements MWMConstants, XUtilConstants * rest of the code. */ static int normalizeMotifFunc(int functions) { - if ((functions & MWM_FUNC_ALL) == 0) { + if ((functions & MWMConstants.MWM_FUNC_ALL) == 0) { return functions; } - int f = MWM_FUNC_RESIZE | - MWM_FUNC_MOVE | - MWM_FUNC_MAXIMIZE | - MWM_FUNC_MINIMIZE | - MWM_FUNC_CLOSE; + int f = MWMConstants.MWM_FUNC_RESIZE | + MWMConstants.MWM_FUNC_MOVE | + MWMConstants.MWM_FUNC_MAXIMIZE | + MWMConstants.MWM_FUNC_MINIMIZE | + MWMConstants.MWM_FUNC_CLOSE; f &= ~functions; return f; } @@ -872,15 +872,15 @@ final class XWM implements MWMConstants, XUtilConstants XAtomList decorDel = new XAtomList(); decorations = normalizeMotifDecor(decorations); if (insLog.isLoggable(Level.FINER)) insLog.finer("Setting OL_DECOR to " + Integer.toBinaryString(decorations)); - if ((decorations & MWM_DECOR_TITLE) == 0) { + if ((decorations & MWMConstants.MWM_DECOR_TITLE) == 0) { decorDel.add(XA_OL_DECOR_HEADER); } - if ((decorations & (MWM_DECOR_RESIZEH | MWM_DECOR_MAXIMIZE)) == 0) { + if ((decorations & (MWMConstants.MWM_DECOR_RESIZEH | MWMConstants.MWM_DECOR_MAXIMIZE)) == 0) { decorDel.add(XA_OL_DECOR_RESIZE); } - if ((decorations & (MWM_DECOR_MENU | - MWM_DECOR_MAXIMIZE | - MWM_DECOR_MINIMIZE)) == 0) + if ((decorations & (MWMConstants.MWM_DECOR_MENU | + MWMConstants.MWM_DECOR_MAXIMIZE | + MWMConstants.MWM_DECOR_MINIMIZE)) == 0) { decorDel.add(XA_OL_DECOR_CLOSE); } @@ -898,19 +898,21 @@ final class XWM implements MWMConstants, XUtilConstants */ static void setMotifDecor(XWindowPeer window, boolean resizable, int decorations, int functions) { /* Apparently some WMs don't implement MWM_*_ALL semantic correctly */ - if ((decorations & MWM_DECOR_ALL) != 0 - && (decorations != MWM_DECOR_ALL)) + if ((decorations & MWMConstants.MWM_DECOR_ALL) != 0 + && (decorations != MWMConstants.MWM_DECOR_ALL)) { decorations = normalizeMotifDecor(decorations); } - if ((functions & MWM_FUNC_ALL) != 0 - && (functions != MWM_FUNC_ALL)) + if ((functions & MWMConstants.MWM_FUNC_ALL) != 0 + && (functions != MWMConstants.MWM_FUNC_ALL)) { functions = normalizeMotifFunc(functions); } PropMwmHints hints = window.getMWMHints(); - hints.set_flags(hints.get_flags() | MWM_HINTS_FUNCTIONS | MWM_HINTS_DECORATIONS); + hints.set_flags(hints.get_flags() | + MWMConstants.MWM_HINTS_FUNCTIONS | + MWMConstants.MWM_HINTS_DECORATIONS); hints.set_functions(functions); hints.set_decorations(decorations); @@ -950,10 +952,10 @@ final class XWM implements MWMConstants, XUtilConstants boolean resizable = window.isResizable(); if (!resizable) { - if ((decorations & MWM_DECOR_ALL) != 0) { - decorations |= MWM_DECOR_RESIZEH | MWM_DECOR_MAXIMIZE; + if ((decorations & MWMConstants.MWM_DECOR_ALL) != 0) { + decorations |= MWMConstants.MWM_DECOR_RESIZEH | MWMConstants.MWM_DECOR_MAXIMIZE; } else { - decorations &= ~(MWM_DECOR_RESIZEH | MWM_DECOR_MAXIMIZE); + decorations &= ~(MWMConstants.MWM_DECOR_RESIZEH | MWMConstants.MWM_DECOR_MAXIMIZE); } } setMotifDecor(window, resizable, decorations, functions); @@ -988,7 +990,7 @@ final class XWM implements MWMConstants, XUtilConstants /* REMINDER: will need to revisit when setExtendedStateBounds is added */ //Fix for 4320050: Minimum size for java.awt.Frame is not being enforced. //We need to update frame's minimum size, not to reset it - removeSizeHints(window, PMaxSize); + removeSizeHints(window, XUtilConstants.PMaxSize); window.updateMinimumSize(); /* Restore decorations */ @@ -1134,7 +1136,7 @@ final class XWM implements MWMConstants, XUtilConstants } int wm_state = window.getWMState(); - if (wm_state == XlibWrapper.WithdrawnState) { + if (wm_state == XUtilConstants.WithdrawnState) { stateLog.finer("WithdrawnState"); return false; } else { @@ -1158,7 +1160,7 @@ final class XWM implements MWMConstants, XUtilConstants int getState(XDecoratedPeer window) { int res = 0; final int wm_state = window.getWMState(); - if (wm_state == XlibWrapper.IconicState) { + if (wm_state == XUtilConstants.IconicState) { res = Frame.ICONIFIED; } else { res = Frame.NORMAL; @@ -1397,7 +1399,7 @@ final class XWM implements MWMConstants, XUtilConstants new WindowPropertyGetter(window, atom, 0, 4, false, XAtom.XA_CARDINAL); try { - if (getter.execute() != XlibWrapper.Success + if (getter.execute() != XConstants.Success || getter.getData() == 0 || getter.getActualType() != XAtom.XA_CARDINAL || getter.getActualFormat() != 32) @@ -1426,7 +1428,7 @@ final class XWM implements MWMConstants, XUtilConstants XClientMessageEvent msg = new XClientMessageEvent(); msg.zero(); - msg.set_type(XlibWrapper.ClientMessage); + msg.set_type(XConstants.ClientMessage); msg.set_display(XToolkit.getDisplay()); msg.set_window(window); msg.set_format(32); @@ -1436,13 +1438,15 @@ final class XWM implements MWMConstants, XUtilConstants if (net_protocol != null && net_protocol.active()) { msg.set_message_type(XA_NET_REQUEST_FRAME_EXTENTS.getAtom()); XlibWrapper.XSendEvent(XToolkit.getDisplay(), XToolkit.getDefaultRootWindow(), - false, XlibWrapper.SubstructureRedirectMask | XlibWrapper.SubstructureNotifyMask, + false, + XConstants.SubstructureRedirectMask | XConstants.SubstructureNotifyMask, msg.getPData()); } if (getWMID() == XWM.KDE2_WM) { msg.set_message_type(XA_KDE_NET_WM_FRAME_STRUT.getAtom()); XlibWrapper.XSendEvent(XToolkit.getDisplay(), XToolkit.getDefaultRootWindow(), - false, XlibWrapper.SubstructureRedirectMask | XlibWrapper.SubstructureNotifyMask, + false, + XConstants.SubstructureRedirectMask | XConstants.SubstructureNotifyMask, msg.getPData()); } // XXX: should we wait for response? XIfEvent() would be useful here :) diff --git a/jdk/src/solaris/classes/sun/awt/X11/XWindow.java b/jdk/src/solaris/classes/sun/awt/X11/XWindow.java index 2d55ef889fb..f7ef09b2e11 100644 --- a/jdk/src/solaris/classes/sun/awt/X11/XWindow.java +++ b/jdk/src/solaris/classes/sun/awt/X11/XWindow.java @@ -178,10 +178,10 @@ public class XWindow extends XBaseWindow implements X11ComponentPeer { AwtGraphicsConfigData gData = getGraphicsConfigurationData(); X11GraphicsConfig config = (X11GraphicsConfig) getGraphicsConfiguration(); XVisualInfo visInfo = gData.get_awt_visInfo(); - params.putIfNull(EVENT_MASK, KeyPressMask | KeyReleaseMask - | FocusChangeMask | ButtonPressMask | ButtonReleaseMask - | EnterWindowMask | LeaveWindowMask | PointerMotionMask - | ButtonMotionMask | ExposureMask | StructureNotifyMask); + params.putIfNull(EVENT_MASK, XConstants.KeyPressMask | XConstants.KeyReleaseMask + | XConstants.FocusChangeMask | XConstants.ButtonPressMask | XConstants.ButtonReleaseMask + | XConstants.EnterWindowMask | XConstants.LeaveWindowMask | XConstants.PointerMotionMask + | XConstants.ButtonMotionMask | XConstants.ExposureMask | XConstants.StructureNotifyMask); if (target != null) { params.putIfNull(BOUNDS, target.getBounds()); @@ -192,9 +192,9 @@ public class XWindow extends XBaseWindow implements X11ComponentPeer { getColorModel(); // fix 4948833: this call forces the color map to be initialized params.putIfNull(COLORMAP, gData.get_awt_cmap()); params.putIfNull(DEPTH, gData.get_awt_depth()); - params.putIfNull(VISUAL_CLASS, Integer.valueOf((int)XlibWrapper.InputOutput)); + params.putIfNull(VISUAL_CLASS, Integer.valueOf((int)XConstants.InputOutput)); params.putIfNull(VISUAL, visInfo.get_visual()); - params.putIfNull(VALUE_MASK, XlibWrapper.CWBorderPixel | XlibWrapper.CWEventMask | XlibWrapper.CWColormap); + params.putIfNull(VALUE_MASK, XConstants.CWBorderPixel | XConstants.CWEventMask | XConstants.CWColormap); Long parentWindow = (Long)params.get(PARENT_WINDOW); if (parentWindow == null || parentWindow.longValue() == 0) { XToolkit.awtLock(); @@ -553,10 +553,10 @@ public class XWindow extends XBaseWindow implements X11ComponentPeer { static int getModifiers(int state, int button, int keyCode) { int modifiers = 0; - if (((state & XlibWrapper.ShiftMask) != 0) ^ (keyCode == KeyEvent.VK_SHIFT)) { + if (((state & XConstants.ShiftMask) != 0) ^ (keyCode == KeyEvent.VK_SHIFT)) { modifiers |= InputEvent.SHIFT_DOWN_MASK; } - if (((state & XlibWrapper.ControlMask) != 0) ^ (keyCode == KeyEvent.VK_CONTROL)) { + if (((state & XConstants.ControlMask) != 0) ^ (keyCode == KeyEvent.VK_CONTROL)) { modifiers |= InputEvent.CTRL_DOWN_MASK; } if (((state & XToolkit.metaMask) != 0) ^ (keyCode == KeyEvent.VK_META)) { @@ -568,13 +568,13 @@ public class XWindow extends XBaseWindow implements X11ComponentPeer { if (((state & XToolkit.modeSwitchMask) != 0) ^ (keyCode == KeyEvent.VK_ALT_GRAPH)) { modifiers |= InputEvent.ALT_GRAPH_DOWN_MASK; } - if (((state & XlibWrapper.Button1Mask) != 0) ^ (button == MouseEvent.BUTTON1)) { + if (((state & XConstants.Button1Mask) != 0) ^ (button == MouseEvent.BUTTON1)) { modifiers |= InputEvent.BUTTON1_DOWN_MASK; } - if (((state & XlibWrapper.Button2Mask) != 0) ^ (button == MouseEvent.BUTTON2)) { + if (((state & XConstants.Button2Mask) != 0) ^ (button == MouseEvent.BUTTON2)) { modifiers |= InputEvent.BUTTON2_DOWN_MASK; } - if (((state & XlibWrapper.Button3Mask) != 0) ^ (button == MouseEvent.BUTTON3)) { + if (((state & XConstants.Button3Mask) != 0) ^ (button == MouseEvent.BUTTON3)) { modifiers |= InputEvent.BUTTON3_DOWN_MASK; } return modifiers; @@ -584,10 +584,10 @@ public class XWindow extends XBaseWindow implements X11ComponentPeer { int mods = stroke.getModifiers(); int res = 0; if ((mods & (InputEvent.SHIFT_DOWN_MASK | InputEvent.SHIFT_MASK)) != 0) { - res |= XToolkit.ShiftMask; + res |= XConstants.ShiftMask; } if ((mods & (InputEvent.CTRL_DOWN_MASK | InputEvent.CTRL_MASK)) != 0) { - res |= XToolkit.ControlMask; + res |= XConstants.ControlMask; } if ((mods & (InputEvent.ALT_DOWN_MASK | InputEvent.ALT_MASK)) != 0) { res |= XToolkit.altMask; @@ -602,12 +602,12 @@ public class XWindow extends XBaseWindow implements X11ComponentPeer { } private static int getButtonMask(long mouseButton) { - if (mouseButton == XlibWrapper.Button1) { - return XlibWrapper.Button1Mask; - } else if (mouseButton == XlibWrapper.Button2) { - return XlibWrapper.Button2Mask; - } else if (mouseButton == XlibWrapper.Button3) { - return XlibWrapper.Button3Mask; + if (mouseButton == XConstants.Button1) { + return XConstants.Button1Mask; + } else if (mouseButton == XConstants.Button2) { + return XConstants.Button2Mask; + } else if (mouseButton == XConstants.Button3) { + return XConstants.Button3Mask; } return 0; } @@ -659,7 +659,7 @@ public class XWindow extends XBaseWindow implements X11ComponentPeer { y = localXY.y; } - if (type == XlibWrapper.ButtonPress) { + if (type == XConstants.ButtonPress) { XWindow lastWindow = (lastWindowRef != null) ? ((XWindow)lastWindowRef.get()):(null); /* multiclick checking @@ -689,16 +689,16 @@ public class XWindow extends XBaseWindow implements X11ComponentPeer { } } - if (lbutton == XlibWrapper.Button1) + if (lbutton == XConstants.Button1) button = MouseEvent.BUTTON1; - else if (lbutton == XlibWrapper.Button2 ) + else if (lbutton == XConstants.Button2 ) button = MouseEvent.BUTTON2; - else if (lbutton == XlibWrapper.Button3) + else if (lbutton == XConstants.Button3) button = MouseEvent.BUTTON3; - else if (lbutton == XlibWrapper.Button4) { + else if (lbutton == XConstants.Button4) { button = 4; wheel_mouse = true; - } else if (lbutton == XlibWrapper.Button5) { + } else if (lbutton == XConstants.Button5) { button = 5; wheel_mouse = true; } @@ -707,7 +707,7 @@ public class XWindow extends XBaseWindow implements X11ComponentPeer { if (!wheel_mouse) { MouseEvent me = new MouseEvent((Component)getEventSource(), - type == XlibWrapper.ButtonPress ? MouseEvent.MOUSE_PRESSED : MouseEvent.MOUSE_RELEASED, + type == XConstants.ButtonPress ? MouseEvent.MOUSE_PRESSED : MouseEvent.MOUSE_RELEASED, jWhen,modifiers, x, y, xbe.get_x_root(), xbe.get_y_root(), @@ -716,7 +716,7 @@ public class XWindow extends XBaseWindow implements X11ComponentPeer { postEventToEventQueue(me); if (((mouseDragState & getButtonMask(lbutton)) == 0) && // No up-button in the drag-state - (type == XlibWrapper.ButtonRelease)) + (type == XConstants.ButtonRelease)) { postEventToEventQueue(me = new MouseEvent((Component)getEventSource(), MouseEvent.MOUSE_CLICKED, @@ -731,7 +731,7 @@ public class XWindow extends XBaseWindow implements X11ComponentPeer { } else { - if (xev.get_type() == XlibWrapper.ButtonPress) { + if (xev.get_type() == XConstants.ButtonPress) { MouseWheelEvent mwe = new MouseWheelEvent((Component)getEventSource(),MouseEvent.MOUSE_WHEEL, jWhen, modifiers, x, y, @@ -753,7 +753,7 @@ public class XWindow extends XBaseWindow implements X11ComponentPeer { return; } - int mouseKeyState = (xme.get_state() & (Button1Mask | Button2Mask | Button3Mask)); + int mouseKeyState = (xme.get_state() & (XConstants.Button1Mask | XConstants.Button2Mask | XConstants.Button3Mask)); boolean isDragging = (mouseKeyState != 0); int mouseEventType = 0; @@ -823,10 +823,10 @@ public class XWindow extends XBaseWindow implements X11ComponentPeer { // accordingly. This leads to impossibility to make a double click on Component (6404708) XWindowPeer toplevel = getToplevelXWindow(); if (toplevel != null && !toplevel.isModalBlocked()){ - if (xce.get_mode() != NotifyNormal) { + if (xce.get_mode() != XConstants.NotifyNormal) { // 6404708 : need update cursor in accordance with skipping Leave/EnterNotify event // whereas it doesn't need to handled further. - if (xce.get_type() == EnterNotify) { + if (xce.get_type() == XConstants.EnterNotify) { XAwtState.setComponentMouseEntered(getEventSource()); XGlobalCursorManager.nativeUpdateCursor(getEventSource()); } else { // LeaveNotify: @@ -840,7 +840,7 @@ public class XWindow extends XBaseWindow implements X11ComponentPeer { // From java point the event is bogus as ancestor is obscured, so if // the child can get java event itself, we skip it on ancestor. long childWnd = xce.get_subwindow(); - if (childWnd != None) { + if (childWnd != XConstants.None) { XBaseWindow child = XToolkit.windowToXWindow(childWnd); if (child != null && child instanceof XWindow && !child.isEventDisabled(xev)) @@ -853,7 +853,7 @@ public class XWindow extends XBaseWindow implements X11ComponentPeer { final Component compWithMouse = XAwtState.getComponentMouseEntered(); if (toplevel != null) { if(!toplevel.isModalBlocked()){ - if (xce.get_type() == EnterNotify) { + if (xce.get_type() == XConstants.EnterNotify) { // Change XAwtState's component mouse entered to the up-to-date one before requesting // to update the cursor since XAwtState.getComponentMouseEntered() is used when the // cursor is updated (in XGlobalCursorManager.findHeavyweightUnderCursor()). @@ -895,7 +895,7 @@ public class XWindow extends XBaseWindow implements X11ComponentPeer { eventLog.finest("Clearing last window ref"); lastWindowRef = null; } - if (xce.get_type() == EnterNotify) { + if (xce.get_type() == XConstants.EnterNotify) { MouseEvent me = new MouseEvent(getEventSource(), MouseEvent.MOUSE_ENTERED, jWhen, modifiers, xce.get_x(), xce.get_y(), xce.get_x_root(), xce.get_y_root(), clickCount, popupTrigger, MouseEvent.NOBUTTON); @@ -990,7 +990,7 @@ public class XWindow extends XBaseWindow implements X11ComponentPeer { final void handleKeyPress(XKeyEvent ev) { long keysym[] = new long[2]; char unicodeKey = 0; - keysym[0] = NoSymbol; + keysym[0] = XConstants.NoSymbol; if (keyEventLog.isLoggable(Level.FINE)) { logIncomingKeyEvent( ev ); @@ -1073,7 +1073,7 @@ public class XWindow extends XBaseWindow implements X11ComponentPeer { private void handleKeyRelease(XKeyEvent ev) { long keysym[] = new long[2]; char unicodeKey = 0; - keysym[0] = NoSymbol; + keysym[0] = XConstants.NoSymbol; if (keyEventLog.isLoggable(Level.FINE)) { logIncomingKeyEvent( ev ); @@ -1153,10 +1153,10 @@ public class XWindow extends XBaseWindow implements X11ComponentPeer { } void updateSizeHints(int x, int y, int width, int height) { - long flags = XlibWrapper.PSize | (isLocationByPlatform() ? 0 : (XlibWrapper.PPosition | XlibWrapper.USPosition)); + long flags = XUtilConstants.PSize | (isLocationByPlatform() ? 0 : (XUtilConstants.PPosition | XUtilConstants.USPosition)); if (!isResizable()) { log.log(Level.FINER, "Window {0} is not resizable", new Object[] {this}); - flags |= XlibWrapper.PMinSize | XlibWrapper.PMaxSize; + flags |= XUtilConstants.PMinSize | XUtilConstants.PMaxSize; } else { log.log(Level.FINER, "Window {0} is resizable", new Object[] {this}); } @@ -1164,10 +1164,10 @@ public class XWindow extends XBaseWindow implements X11ComponentPeer { } void updateSizeHints(int x, int y) { - long flags = isLocationByPlatform() ? 0 : (XlibWrapper.PPosition | XlibWrapper.USPosition); + long flags = isLocationByPlatform() ? 0 : (XUtilConstants.PPosition | XUtilConstants.USPosition); if (!isResizable()) { log.log(Level.FINER, "Window {0} is not resizable", new Object[] {this}); - flags |= XlibWrapper.PMinSize | XlibWrapper.PMaxSize | XlibWrapper.PSize; + flags |= XUtilConstants.PMinSize | XUtilConstants.PMaxSize | XUtilConstants.PSize; } else { log.log(Level.FINER, "Window {0} is resizable", new Object[] {this}); } diff --git a/jdk/src/solaris/classes/sun/awt/X11/XWindowPeer.java b/jdk/src/solaris/classes/sun/awt/X11/XWindowPeer.java index c5fc7e1a7d4..2222163b4ab 100644 --- a/jdk/src/solaris/classes/sun/awt/X11/XWindowPeer.java +++ b/jdk/src/solaris/classes/sun/awt/X11/XWindowPeer.java @@ -50,7 +50,7 @@ import sun.awt.X11GraphicsDevice; import sun.awt.X11GraphicsEnvironment; class XWindowPeer extends XPanelPeer implements WindowPeer, - DisplayChangedListener, MWMConstants { + DisplayChangedListener { private static final Logger log = Logger.getLogger("sun.awt.X11.XWindowPeer"); private static final Logger focusLog = Logger.getLogger("sun.awt.X11.focus.XWindowPeer"); @@ -133,9 +133,9 @@ class XWindowPeer extends XPanelPeer implements WindowPeer, params.put(REPARENTED, Boolean.valueOf(isOverrideRedirect() || isSimpleWindow())); super.preInit(params); - params.putIfNull(BIT_GRAVITY, Integer.valueOf(NorthWestGravity)); + params.putIfNull(BIT_GRAVITY, Integer.valueOf(XConstants.NorthWestGravity)); - savedState = WithdrawnState; + savedState = XUtilConstants.WithdrawnState; XA_NET_WM_STATE = XAtom.get("_NET_WM_STATE"); winAttr = new XWindowAttributesData(); @@ -239,7 +239,7 @@ class XWindowPeer extends XPanelPeer implements WindowPeer, // Set group leader XWMHints hints = getWMHints(); - hints.set_flags(hints.get_flags() | (int)XlibWrapper.WindowGroupHint); + hints.set_flags(hints.get_flags() | (int)XUtilConstants.WindowGroupHint); hints.set_window_group(ownerWindow); XlibWrapper.XSetWMHints(XToolkit.getDisplay(), getWindow(), hints.pData); } @@ -503,7 +503,7 @@ class XWindowPeer extends XPanelPeer implements WindowPeer, Rectangle bounds = getBounds(); XSizeHints hints = getHints(); - setSizeHints(hints.get_flags() | XlibWrapper.PPosition | XlibWrapper.PSize, + setSizeHints(hints.get_flags() | XUtilConstants.PPosition | XUtilConstants.PSize, bounds.x, bounds.y, bounds.width, bounds.height); XWM.setMotifDecor(this, false, 0, 0); @@ -531,7 +531,7 @@ class XWindowPeer extends XPanelPeer implements WindowPeer, XToolkit.awtLock(); try { XWMHints hints = getWMHints(); - hints.set_flags(hints.get_flags() | (int)XlibWrapper.InputHint); + hints.set_flags(hints.get_flags() | (int)XUtilConstants.InputHint); hints.set_input(false/*isNativelyNonFocusableWindow() ? (0):(1)*/); XlibWrapper.XSetWMHints(XToolkit.getDisplay(), getWindow(), hints.pData); } @@ -821,12 +821,12 @@ class XWindowPeer extends XPanelPeer implements WindowPeer, if (isEventDisabled(xev)) { return; } - if (xev.get_type() == XlibWrapper.FocusIn) + if (xev.get_type() == XConstants.FocusIn) { // If this window is non-focusable don't post any java focus event if (focusAllowedFor()) { - if (xfe.get_mode() == XlibWrapper.NotifyNormal // Normal notify - || xfe.get_mode() == XlibWrapper.NotifyWhileGrabbed) // Alt-Tab notify + if (xfe.get_mode() == XConstants.NotifyNormal // Normal notify + || xfe.get_mode() == XConstants.NotifyWhileGrabbed) // Alt-Tab notify { handleWindowFocusIn(xfe.get_serial()); } @@ -834,8 +834,8 @@ class XWindowPeer extends XPanelPeer implements WindowPeer, } else { - if (xfe.get_mode() == XlibWrapper.NotifyNormal // Normal notify - || xfe.get_mode() == XlibWrapper.NotifyWhileGrabbed) // Alt-Tab notify + if (xfe.get_mode() == XConstants.NotifyNormal // Normal notify + || xfe.get_mode() == XConstants.NotifyWhileGrabbed) // Alt-Tab notify { // If this window is non-focusable don't post any java focus event if (!isNativelyNonFocusableWindow()) { @@ -1022,7 +1022,7 @@ class XWindowPeer extends XPanelPeer implements WindowPeer, try { Rectangle bounds = getBounds(); XSizeHints hints = getHints(); - setSizeHints(hints.get_flags() & ~(USPosition | PPosition), + setSizeHints(hints.get_flags() & ~(XUtilConstants.USPosition | XUtilConstants.PPosition), bounds.x, bounds.y, bounds.width, bounds.height); } finally { XToolkit.awtUnlock(); @@ -1059,10 +1059,10 @@ class XWindowPeer extends XPanelPeer implements WindowPeer, XUnmapEvent unmap = new XUnmapEvent(); unmap.set_window(window); unmap.set_event(XToolkit.getDefaultRootWindow()); - unmap.set_type((int)XlibWrapper.UnmapNotify); + unmap.set_type((int)XConstants.UnmapNotify); unmap.set_from_configure(false); XlibWrapper.XSendEvent(XToolkit.getDisplay(), XToolkit.getDefaultRootWindow(), - false, XlibWrapper.SubstructureNotifyMask | XlibWrapper.SubstructureRedirectMask, + false, XConstants.SubstructureNotifyMask | XConstants.SubstructureRedirectMask, unmap.pData); unmap.dispose(); } @@ -1305,12 +1305,12 @@ class XWindowPeer extends XPanelPeer implements WindowPeer, XWM.XA_WM_STATE); try { int status = getter.execute(); - if (status != XlibWrapper.Success || getter.getData() == 0) { - return savedState = XlibWrapper.WithdrawnState; + if (status != XConstants.Success || getter.getData() == 0) { + return savedState = XUtilConstants.WithdrawnState; } if (getter.getActualType() != XWM.XA_WM_STATE.getAtom() && getter.getActualFormat() != 32) { - return savedState = XlibWrapper.WithdrawnState; + return savedState = XUtilConstants.WithdrawnState; } savedState = (int)Native.getCard32(getter.getData()); } finally { @@ -1321,7 +1321,7 @@ class XWindowPeer extends XPanelPeer implements WindowPeer, } boolean isWithdrawn() { - return getWMState() == XlibWrapper.WithdrawnState; + return getWMState() == XUtilConstants.WithdrawnState; } boolean hasDecorations(int decor) { @@ -1818,14 +1818,14 @@ class XWindowPeer extends XPanelPeer implements WindowPeer, if( rootPropertyEventDispatcher == null ) { rootPropertyEventDispatcher = new XEventDispatcher() { public void dispatchEvent(XEvent ev) { - if( ev.get_type() == PropertyNotify ) { + if( ev.get_type() == XConstants.PropertyNotify ) { handleRootPropertyNotify( ev ); } } }; XlibWrapper.XSelectInput( XToolkit.getDisplay(), XToolkit.getDefaultRootWindow(), - XlibWrapper.PropertyChangeMask); + XConstants.PropertyChangeMask); XToolkit.addEventDispatcher(XToolkit.getDefaultRootWindow(), rootPropertyEventDispatcher); } @@ -1860,7 +1860,7 @@ class XWindowPeer extends XPanelPeer implements WindowPeer, public PropMwmHints getMWMHints() { if (mwm_hints == null) { mwm_hints = new PropMwmHints(); - if (!XWM.XA_MWM_HINTS.getAtomData(getWindow(), mwm_hints.pData, PROP_MWM_HINTS_ELEMENTS)) { + if (!XWM.XA_MWM_HINTS.getAtomData(getWindow(), mwm_hints.pData, MWMConstants.PROP_MWM_HINTS_ELEMENTS)) { mwm_hints.zero(); } } @@ -1870,7 +1870,7 @@ class XWindowPeer extends XPanelPeer implements WindowPeer, public void setMWMHints(PropMwmHints hints) { mwm_hints = hints; if (hints != null) { - XWM.XA_MWM_HINTS.setAtomData(getWindow(), mwm_hints.pData, PROP_MWM_HINTS_ELEMENTS); + XWM.XA_MWM_HINTS.setAtomData(getWindow(), mwm_hints.pData, MWMConstants.PROP_MWM_HINTS_ELEMENTS); } } @@ -1960,7 +1960,7 @@ class XWindowPeer extends XPanelPeer implements WindowPeer, new Object[] {xme, isGrabbed(), containsGlobal(xme.get_x_root(), xme.get_y_root())}); } if (isGrabbed()) { - boolean dragging = (xme.get_state() & (Button1Mask | Button2Mask | Button3Mask)) != 0; + boolean dragging = (xme.get_state() & (XConstants.Button1Mask | XConstants.Button2Mask | XConstants.Button3Mask)) != 0; // When window is grabbed, all events are dispatched to // it. Retarget them to the corresponding windows (notice // that XBaseWindow.dispatchEvent does the opposite @@ -2014,12 +2014,12 @@ class XWindowPeer extends XPanelPeer implements WindowPeer, try { grabLog.log(Level.FINER, " - Grab event target {0} (press target {1})", new Object[] {target, pressTarget}); if (xbe.get_type() == XConstants.ButtonPress - && xbe.get_button() == XlibWrapper.Button1) + && xbe.get_button() == XConstants.Button1) { // need to keep it to retarget mouse release pressTarget = target; } else if (xbe.get_type() == XConstants.ButtonRelease - && xbe.get_button() == XlibWrapper.Button1 + && xbe.get_button() == XConstants.Button1 && pressTarget != target) { // during grab we do receive mouse release on different component (not on the source diff --git a/jdk/src/solaris/classes/sun/awt/X11/XlibUtil.java b/jdk/src/solaris/classes/sun/awt/X11/XlibUtil.java index b6086ef469b..bdc6e7c376e 100644 --- a/jdk/src/solaris/classes/sun/awt/X11/XlibUtil.java +++ b/jdk/src/solaris/classes/sun/awt/X11/XlibUtil.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2007 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2006-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -152,7 +152,7 @@ public class XlibUtil int status = xtc.execute(XToolkit.IgnoreBadWindowHandler); if ((status != 0) && ((XToolkit.saved_error == null) || - (XToolkit.saved_error.get_error_code() == XlibWrapper.Success))) + (XToolkit.saved_error.get_error_code() == XConstants.Success))) { translated = new Point(xtc.get_dest_x(), xtc.get_dest_y()); } @@ -351,7 +351,7 @@ public class XlibUtil XToolkit.RESTORE_XERROR_HANDLER(); if ((status != 0) && ((XToolkit.saved_error == null) || - (XToolkit.saved_error.get_error_code() == XlibWrapper.Success))) + (XToolkit.saved_error.get_error_code() == XConstants.Success))) { return wattr.get_map_state(); } @@ -362,7 +362,7 @@ public class XlibUtil XToolkit.awtUnlock(); } - return XlibWrapper.IsUnmapped; + return XConstants.IsUnmapped; } /** diff --git a/jdk/src/solaris/classes/sun/awt/X11/XlibWrapper.java b/jdk/src/solaris/classes/sun/awt/X11/XlibWrapper.java index 079f7ac8d28..50be5f54da7 100644 --- a/jdk/src/solaris/classes/sun/awt/X11/XlibWrapper.java +++ b/jdk/src/solaris/classes/sun/awt/X11/XlibWrapper.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2007 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2002-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -29,8 +29,7 @@ import java.security.AccessController; import java.security.PrivilegedAction; import sun.misc.*; -public class XlibWrapper implements XConstants, XUtilConstants, XProtocolConstants, - XCursorFontConstants +final public class XlibWrapper { static Unsafe unsafe = Unsafe.getUnsafe(); // strange constants @@ -321,7 +320,7 @@ static native String XSetLocaleModifiers(String modifier_list); if (XPropertyCache.isCachingSupported() && XToolkit.windowToXWindow(window) != null && WindowPropertyGetter.isCacheableProperty(XAtom.get(atom)) && - mode == PropModeReplace) + mode == XConstants.PropModeReplace) { int length = (format / 8) * nelements; XPropertyCache.storeCache( @@ -585,25 +584,25 @@ static native String XSetLocaleModifiers(String modifier_list); static String hintsToString(long flags) { StringBuffer buf = new StringBuffer(); - if ((flags & PMaxSize) != 0) { + if ((flags & XUtilConstants.PMaxSize) != 0) { buf.append("PMaxSize "); } - if ((flags & PMinSize) != 0) { + if ((flags & XUtilConstants.PMinSize) != 0) { buf.append("PMinSize "); } - if ((flags & USSize) != 0) { + if ((flags & XUtilConstants.USSize) != 0) { buf.append("USSize "); } - if ((flags & USPosition) != 0) { + if ((flags & XUtilConstants.USPosition) != 0) { buf.append("USPosition "); } - if ((flags & PPosition) != 0) { + if ((flags & XUtilConstants.PPosition) != 0) { buf.append("PPosition "); } - if ((flags & PSize) != 0) { + if ((flags & XUtilConstants.PSize) != 0) { buf.append("PSize "); } - if ((flags & PWinGravity) != 0) { + if ((flags & XUtilConstants.PWinGravity) != 0) { buf.append("PWinGravity "); } return buf.toString(); From bfbfdfa4289ac351182ed2a643b110ef68b2b60a Mon Sep 17 00:00:00 2001 From: Chuck Rasbold Date: Mon, 7 Apr 2008 15:15:16 -0700 Subject: [PATCH 146/258] 6663908: NegativeArraySizeException is not thrown Don't optimize zero length array allocations at compile time. Reviewed-by: kvn, never --- hotspot/src/share/vm/opto/parse3.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/hotspot/src/share/vm/opto/parse3.cpp b/hotspot/src/share/vm/opto/parse3.cpp index d32053ce299..cfd042959c9 100644 --- a/hotspot/src/share/vm/opto/parse3.cpp +++ b/hotspot/src/share/vm/opto/parse3.cpp @@ -408,7 +408,7 @@ void Parse::do_multianewarray() { jint dim_con = find_int_con(length[j], -1); expand_fanout *= dim_con; expand_count += expand_fanout; // count the level-J sub-arrays - if (dim_con < 0 + if (dim_con <= 0 || dim_con > expand_limit || expand_count > expand_limit) { expand_count = 0; From 5887f56e62e1861fae6bd0c09dbcd62f3863494d Mon Sep 17 00:00:00 2001 From: Andrei Dmitriev Date: Tue, 8 Apr 2008 12:46:39 +0400 Subject: [PATCH 147/258] 6520716: event classes lack info about parameters Clarify allowed values for event constructors Reviewed-by: son, denis --- .../java/awt/dnd/DragGestureEvent.java | 34 +++- .../classes/java/awt/dnd/DropTargetEvent.java | 9 +- .../classes/java/awt/event/ActionEvent.java | 69 +++++-- .../java/awt/event/AdjustmentEvent.java | 62 ++++-- .../java/awt/event/ComponentEvent.java | 15 +- .../java/awt/event/ContainerEvent.java | 16 +- .../classes/java/awt/event/FocusEvent.java | 52 +++-- .../java/awt/event/HierarchyEvent.java | 99 +++++---- .../classes/java/awt/event/InputEvent.java | 37 +++- .../java/awt/event/InvocationEvent.java | 39 ++-- .../classes/java/awt/event/ItemEvent.java | 33 ++- .../classes/java/awt/event/KeyEvent.java | 87 +++++--- .../classes/java/awt/event/MouseEvent.java | 192 ++++++++++++------ .../java/awt/event/MouseWheelEvent.java | 2 +- .../classes/java/awt/event/PaintEvent.java | 18 +- .../classes/java/awt/event/TextEvent.java | 15 +- .../classes/java/awt/event/WindowEvent.java | 89 +++++--- 17 files changed, 591 insertions(+), 277 deletions(-) diff --git a/jdk/src/share/classes/java/awt/dnd/DragGestureEvent.java b/jdk/src/share/classes/java/awt/dnd/DragGestureEvent.java index 9996275225c..73885d436a1 100644 --- a/jdk/src/share/classes/java/awt/dnd/DragGestureEvent.java +++ b/jdk/src/share/classes/java/awt/dnd/DragGestureEvent.java @@ -1,5 +1,5 @@ /* - * Copyright 1998-2006 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1998-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -55,9 +55,19 @@ import java.io.ObjectOutputStream; * platform dependent drag initiating gesture has occurred * on the Component that it is tracking. * + * The {@code action} field of any {@code DragGestureEvent} instance should take one of the following + * values: + *

    + *
  • {@code DnDConstants.ACTION_COPY} + *
  • {@code DnDConstants.ACTION_MOVE} + *
  • {@code DnDConstants.ACTION_LINK} + *
+ * Assigning the value different from listed above will cause an unspecified behavior. + * * @see java.awt.dnd.DragGestureRecognizer * @see java.awt.dnd.DragGestureListener * @see java.awt.dnd.DragSource + * @see java.awt.dnd.DnDConstants */ public class DragGestureEvent extends EventObject { @@ -65,19 +75,25 @@ public class DragGestureEvent extends EventObject { private static final long serialVersionUID = 9080172649166731306L; /** - * Constructs a DragGestureEvent given the - * DragGestureRecognizer firing this event, - * an int representing - * the user's preferred action, a Point - * indicating the origin of the drag, and a List - * of events that comprise the gesture. + * Constructs a DragGestureEvent object given by the + * DragGestureRecognizer instance firing this event, + * an {@code act} parameter representing + * the user's preferred action, an {@code ori} parameter + * indicating the origin of the drag, and a {@code List} of + * events that comprise the gesture({@code evs} parameter). *

* @param dgr The DragGestureRecognizer firing this event - * @param act The the user's preferred action + * @param act The user's preferred action. + * For information on allowable values, see + * the class description for {@link DragGestureEvent} * @param ori The origin of the drag * @param evs The List of events that comprise the gesture *

- * @throws IllegalArgumentException if input parameters are {@code null} + * @throws IllegalArgumentException if any parameter equals {@code null} + * @throws IllegalArgumentException if the act parameter does not comply with + * the values given in the class + * description for {@link DragGestureEvent} + * @see java.awt.dnd.DnDConstants */ public DragGestureEvent(DragGestureRecognizer dgr, int act, Point ori, diff --git a/jdk/src/share/classes/java/awt/dnd/DropTargetEvent.java b/jdk/src/share/classes/java/awt/dnd/DropTargetEvent.java index 64d0b44d170..42fd397c701 100644 --- a/jdk/src/share/classes/java/awt/dnd/DropTargetEvent.java +++ b/jdk/src/share/classes/java/awt/dnd/DropTargetEvent.java @@ -45,10 +45,13 @@ public class DropTargetEvent extends java.util.EventObject { private static final long serialVersionUID = 2821229066521922993L; /** - * Construct a DropTargetEvent with - * a specified DropTargetContext. + * Construct a DropTargetEvent object with + * the specified DropTargetContext. *

- * @param dtc the DropTargetContext + * @param dtc The DropTargetContext + * @throws NullPointerException if {@code dtc} equals {@code null}. + * @see #getSource() + * @see #getDropTargetContext() */ public DropTargetEvent(DropTargetContext dtc) { diff --git a/jdk/src/share/classes/java/awt/event/ActionEvent.java b/jdk/src/share/classes/java/awt/event/ActionEvent.java index 41ed7d6488c..b81ab8a8f4f 100644 --- a/jdk/src/share/classes/java/awt/event/ActionEvent.java +++ b/jdk/src/share/classes/java/awt/event/ActionEvent.java @@ -1,5 +1,5 @@ /* - * Copyright 1996-2006 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1996-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -45,6 +45,10 @@ import java.awt.Event; * is therefore spared the details of processing individual mouse movements * and mouse clicks, and can instead process a "meaningful" (semantic) * event like "button pressed". + *

+ * An unspecified behavior will be caused if the {@code id} parameter + * of any particular {@code ActionEvent} instance is not + * in the range from {@code ACTION_FIRST} to {@code ACTION_LAST}. * * @see ActionListener * @see Tutorial: Java 1.1 Event Model @@ -134,18 +138,22 @@ public class ActionEvent extends AWTEvent { /** * Constructs an ActionEvent object. *

- * Note that passing in an invalid id results in - * unspecified behavior. This method throws an + * This method throws an * IllegalArgumentException if source * is null. * A null command string is legal, * but not recommended. * - * @param source the object that originated the event - * @param id an integer that identifies the event - * @param command a string that may specify a command (possibly one + * @param source The object that originated the event + * @param id An integer that identifies the event. + * For information on allowable values, see + * the class description for {@link ActionEvent} + * @param command A string that may specify a command (possibly one * of several) associated with the event * @throws IllegalArgumentException if source is null + * @see #getSource() + * @see #getID() + * @see #getActionCommand() */ public ActionEvent(Object source, int id, String command) { this(source, id, command, 0); @@ -154,19 +162,27 @@ public class ActionEvent extends AWTEvent { /** * Constructs an ActionEvent object with modifier keys. *

- * Note that passing in an invalid id results in - * unspecified behavior. This method throws an + * This method throws an * IllegalArgumentException if source * is null. * A null command string is legal, * but not recommended. * - * @param source the object that originated the event - * @param id an integer that identifies the event - * @param command a string that may specify a command (possibly one - * of several) associated with the event - * @param modifiers the modifier keys held down during this action + * @param source The object that originated the event + * @param id An integer that identifies the event. + * For information on allowable values, see + * the class description for {@link ActionEvent} + * @param command A string that may specify a command (possibly one + * of several) associated with the event + * @param modifiers The modifier keys down during event + * (shift, ctrl, alt, meta). + * Passing negative parameter is not recommended. + * Zero value means that no modifiers were passed * @throws IllegalArgumentException if source is null + * @see #getSource() + * @see #getID() + * @see #getActionCommand() + * @see #getModifiers() */ public ActionEvent(Object source, int id, String command, int modifiers) { this(source, id, command, 0, modifiers); @@ -176,20 +192,31 @@ public class ActionEvent extends AWTEvent { * Constructs an ActionEvent object with the specified * modifier keys and timestamp. *

- * Note that passing in an invalid id results in - * unspecified behavior. This method throws an + * This method throws an * IllegalArgumentException if source * is null. * A null command string is legal, * but not recommended. * - * @param source the object that originated the event - * @param id an integer that identifies the event - * @param command a string that may specify a command (possibly one - * of several) associated with the event - * @param when the time the event occurred - * @param modifiers the modifier keys held down during this action + * @param source The object that originated the event + * @param id An integer that identifies the event. + * For information on allowable values, see + * the class description for {@link ActionEvent} + * @param command A string that may specify a command (possibly one + * of several) associated with the event + * @param modifiers The modifier keys down during event + * (shift, ctrl, alt, meta). + * Passing negative parameter is not recommended. + * Zero value means that no modifiers were passed + * @param when A long that gives the time the event occurred. + * Passing negative or zero value + * is not recommended * @throws IllegalArgumentException if source is null + * @see #getSource() + * @see #getID() + * @see #getActionCommand() + * @see #getModifiers() + * @see #getWhen() * * @since 1.4 */ diff --git a/jdk/src/share/classes/java/awt/event/AdjustmentEvent.java b/jdk/src/share/classes/java/awt/event/AdjustmentEvent.java index b928899b2ec..590dae60ffb 100644 --- a/jdk/src/share/classes/java/awt/event/AdjustmentEvent.java +++ b/jdk/src/share/classes/java/awt/event/AdjustmentEvent.java @@ -29,7 +29,25 @@ import java.awt.Adjustable; import java.awt.AWTEvent; /** - * The adjustment event emitted by Adjustable objects. + * The adjustment event emitted by Adjustable objects like + * {@link java.awt.Scrollbar} and {@link java.awt.ScrollPane}. + * When the user changes the value of the scrolling component, + * it receives an instance of {@code AdjustmentEvent}. + *

+ * An unspecified behavior will be caused if the {@code id} parameter + * of any particular {@code AdjustmentEvent} instance is not + * in the range from {@code ADJUSTMENT_FIRST} to {@code ADJUSTMENT_LAST}. + *

+ * The {@code type} of any {@code AdjustmentEvent} instance takes one of the following + * values: + *

    + *
  • {@code UNIT_INCREMENT} + *
  • {@code UNIT_DECREMENT} + *
  • {@code BLOCK_INCREMENT} + *
  • {@code BLOCK_DECREMENT} + *
  • {@code TRACK} + *
+ * Assigning the value different from listed above will cause an unspecified behavior. * @see java.awt.Adjustable * @see AdjustmentListener * @@ -130,17 +148,24 @@ public class AdjustmentEvent extends AWTEvent { * Constructs an AdjustmentEvent object with the * specified Adjustable source, event type, * adjustment type, and value. - *

Note that passing in an invalid id results in - * unspecified behavior. This method throws an + *

This method throws an * IllegalArgumentException if source * is null. * - * @param source the Adjustable object where the + * @param source The Adjustable object where the * event originated - * @param id the event type - * @param type the adjustment type - * @param value the current value of the adjustment + * @param id An integer indicating the type of event. + * For information on allowable values, see + * the class description for {@link AdjustmentEvent} + * @param type An integer indicating the adjustment type. + * For information on allowable values, see + * the class description for {@link AdjustmentEvent} + * @param value The current value of the adjustment * @throws IllegalArgumentException if source is null + * @see #getSource() + * @see #getID() + * @see #getAdjustmentType() + * @see #getValue() */ public AdjustmentEvent(Adjustable source, int id, int type, int value) { this(source, id, type, value, false); @@ -149,22 +174,29 @@ public class AdjustmentEvent extends AWTEvent { /** * Constructs an AdjustmentEvent object with the * specified Adjustable source, event type, adjustment type, and value. - *

Note that passing in an invalid id results in - * unspecified behavior. This method throws an + *

This method throws an * IllegalArgumentException if source * is null. - * - * @param source the Adjustable object where the + * @param source The Adjustable object where the * event originated - * @param id the event type - * @param type the adjustment type - * @param value the current value of the adjustment - * @param isAdjusting true if the event is one + * @param id An integer indicating the type of event. + * For information on allowable values, see + * the class description for {@link AdjustmentEvent} + * @param type An integer indicating the adjustment type. + * For information on allowable values, see + * the class description for {@link AdjustmentEvent} + * @param value The current value of the adjustment + * @param isAdjusting A boolean that equals true if the event is one * of a series of multiple adjusting events, * otherwise false * @throws IllegalArgumentException if source is null * @since 1.4 + * @see #getSource() + * @see #getID() + * @see #getAdjustmentType() + * @see #getValue() + * @see #getValueIsAdjusting() */ public AdjustmentEvent(Adjustable source, int id, int type, int value, boolean isAdjusting) { super(source, id); diff --git a/jdk/src/share/classes/java/awt/event/ComponentEvent.java b/jdk/src/share/classes/java/awt/event/ComponentEvent.java index a0264b81af0..bd51d262ef7 100644 --- a/jdk/src/share/classes/java/awt/event/ComponentEvent.java +++ b/jdk/src/share/classes/java/awt/event/ComponentEvent.java @@ -52,6 +52,10 @@ import java.awt.Rectangle; * (ComponentAdapter objects implement the * ComponentListener interface.) Each such listener object * gets this ComponentEvent when the event occurs. + *

+ * An unspecified behavior will be caused if the {@code id} parameter + * of any particular {@code ComponentEvent} instance is not + * in the range from {@code COMPONENT_FIRST} to {@code COMPONENT_LAST}. * * @see ComponentAdapter * @see ComponentListener @@ -99,14 +103,17 @@ public class ComponentEvent extends AWTEvent { /** * Constructs a ComponentEvent object. - *

Note that passing in an invalid id results in - * unspecified behavior. This method throws an + *

This method throws an * IllegalArgumentException if source * is null. * - * @param source the Component that originated the event - * @param id an integer indicating the type of event + * @param source The Component that originated the event + * @param id An integer indicating the type of event. + * For information on allowable values, see + * the class description for {@link ComponentEvent} * @throws IllegalArgumentException if source is null + * @see #getComponent() + * @see #getID() */ public ComponentEvent(Component source, int id) { super(source, id); diff --git a/jdk/src/share/classes/java/awt/event/ContainerEvent.java b/jdk/src/share/classes/java/awt/event/ContainerEvent.java index f927312ba0b..16ef5b1c92f 100644 --- a/jdk/src/share/classes/java/awt/event/ContainerEvent.java +++ b/jdk/src/share/classes/java/awt/event/ContainerEvent.java @@ -45,6 +45,10 @@ import java.awt.Component; * (ContainerAdapter objects implement the * ContainerListener interface.) Each such listener object * gets this ContainerEvent when the event occurs. + *

+ * An unspecified behavior will be caused if the {@code id} parameter + * of any particular {@code ContainerEvent} instance is not + * in the range from {@code CONTAINER_FIRST} to {@code CONTAINER_LAST}. * * @see ContainerAdapter * @see ContainerListener @@ -92,16 +96,20 @@ public class ContainerEvent extends ComponentEvent { /** * Constructs a ContainerEvent object. - *

Note that passing in an invalid id results in - * unspecified behavior. This method throws an + *

This method throws an * IllegalArgumentException if source * is null. * - * @param source the Component object (container) + * @param source The Component object (container) * that originated the event - * @param id an integer indicating the type of event + * @param id An integer indicating the type of event. + * For information on allowable values, see + * the class description for {@link ContainerEvent} * @param child the component that was added or removed * @throws IllegalArgumentException if source is null + * @see #getContainer() + * @see #getID() + * @see #getChild() */ public ContainerEvent(Component source, int id, Component child) { super(source, id); diff --git a/jdk/src/share/classes/java/awt/event/FocusEvent.java b/jdk/src/share/classes/java/awt/event/FocusEvent.java index 188ce44b720..ec018e0126e 100644 --- a/jdk/src/share/classes/java/awt/event/FocusEvent.java +++ b/jdk/src/share/classes/java/awt/event/FocusEvent.java @@ -50,6 +50,10 @@ import sun.awt.SunToolkit; * reactivated. Both permanent and temporary focus events are delivered using * the FOCUS_GAINED and FOCUS_LOST event ids; the level may be distinguished in * the event using the isTemporary() method. + *

+ * An unspecified behavior will be caused if the {@code id} parameter + * of any particular {@code FocusEvent} instance is not + * in the range from {@code FOCUS_FIRST} to {@code FOCUS_LAST}. * * @see FocusAdapter * @see FocusListener @@ -121,18 +125,23 @@ public class FocusEvent extends ComponentEvent { * application, with a Java application in a different VM, * or with no other Component, then the opposite * Component is null. - *

Note that passing in an invalid id results in - * unspecified behavior. This method throws an + *

This method throws an * IllegalArgumentException if source * is null. * - * @param source the Component that originated the event - * @param id FOCUS_GAINED or FOCUS_LOST - * @param temporary true if the focus change is temporary; + * @param source The Component that originated the event + * @param id An integer indicating the type of event. + * For information on allowable values, see + * the class description for {@link FocusEvent} + * @param temporary Equals true if the focus change is temporary; * false otherwise - * @param opposite the other Component involved in the focus change, + * @param opposite The other Component involved in the focus change, * or null - * @throws IllegalArgumentException if source is null + * @throws IllegalArgumentException if source equals {@code null} + * @see #getSource() + * @see #getID() + * @see #isTemporary() + * @see #getOppositeComponent() * @since 1.4 */ public FocusEvent(Component source, int id, boolean temporary, @@ -145,16 +154,20 @@ public class FocusEvent extends ComponentEvent { /** * Constructs a FocusEvent object and identifies * whether or not the change is temporary. - *

Note that passing in an invalid id results in - * unspecified behavior. This method throws an + *

This method throws an * IllegalArgumentException if source * is null. * - * @param source the Component that originated the event - * @param id an integer indicating the type of event - * @param temporary true if the focus change is temporary; + * @param source The Component that originated the event + * @param id An integer indicating the type of event. + * For information on allowable values, see + * the class description for {@link FocusEvent} + * @param temporary Equals true if the focus change is temporary; * false otherwise - * @throws IllegalArgumentException if source is null + * @throws IllegalArgumentException if source equals {@code null} + * @see #getSource() + * @see #getID() + * @see #isTemporary() */ public FocusEvent(Component source, int id, boolean temporary) { this(source, id, temporary, null); @@ -163,14 +176,17 @@ public class FocusEvent extends ComponentEvent { /** * Constructs a FocusEvent object and identifies it * as a permanent change in focus. - *

Note that passing in an invalid id results in - * unspecified behavior. This method throws an + *

This method throws an * IllegalArgumentException if source * is null. * - * @param source the Component that originated the event - * @param id an integer indicating the type of event - * @throws IllegalArgumentException if source is null + * @param source The Component that originated the event + * @param id An integer indicating the type of event. + * For information on allowable values, see + * the class description for {@link FocusEvent} + * @throws IllegalArgumentException if source equals {@code null} + * @see #getSource() + * @see #getID() */ public FocusEvent(Component source, int id) { this(source, id, false); diff --git a/jdk/src/share/classes/java/awt/event/HierarchyEvent.java b/jdk/src/share/classes/java/awt/event/HierarchyEvent.java index d57256a45a2..6ed6ab18edb 100644 --- a/jdk/src/share/classes/java/awt/event/HierarchyEvent.java +++ b/jdk/src/share/classes/java/awt/event/HierarchyEvent.java @@ -1,5 +1,5 @@ /* - * Copyright 1999-2004 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1999-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -31,7 +31,7 @@ import java.awt.Container; /** * An event which indicates a change to the Component - * hierarchy to which a Component belongs. + * hierarchy to which Component belongs. *